Reputation: 11
I am currently working on a simple pygame that has a bunny and candies falling on the screen, if the bunny touches the candy, the candy disappears. But the collision detection is not working. When I run it, I get the following error:
Traceback (most recent call last):
File "C:\mashi.py", line 79, in <module>
candy.checkCollision(bunny.image_b, candy.image_b)
TypeError: checkCollision() takes exactly 2 arguments (3 given)
Here's my code:
import pygame
import os, sys
import random
import time
pygame.display.set_caption("Mashimaro Game")
# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('mashimaro.png')
img_path2 = os.path.join('candy.png')
background_image = pygame.image.load('food.png')
class Bunny(object): # represents the bunny, not the game
def __init__(self):
""" The constructor of the class """
self.image_s = pygame.image.load(img_path)
self.image_b = self.image_s.get_rect()
# the bunny's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 5 # distance moved in 5 frame
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
class Candy(object):
def __init__(self, x=640, y=0):
self.image_s = pygame.image.load(img_path2)
self.image_b = self.image_s.get_rect()
self.x = x
self.y = y
dist = 10
self.dist = dist
def candy(self):
dist = 10
self.x -=dist
def candy_draw(self, surface):
surface.blit(self.image, (self.x, self.y))
def checkCollision(sprite1, sprite2):
col = pygame.sprite.spritecollide(sprite1, sprite2)
if col == True:
sys.exit()
return col
pygame.init()
screen = pygame.display.set_mode((640, 400))
bunny = Bunny() # create an instance
candy = Candy()
clock = pygame.time.Clock()
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
if candy.x < 0:
y = random.randint(10, 190)
candy = Candy(640, y)
candy.checkCollision(bunny.image_b, candy.image_b)
bunny.handle_keys() # handle the keys
candy.candy()
screen.blit(background_image,[0,0]) # fill the screen with background
bunny.draw(screen) # draw the bunny to the screen
rock.rock_draw(screen)
pygame.display.update() # update the screen
clock.tick(120)
What have I been doing wrong?
Upvotes: 1
Views: 307
Reputation: 87134
In your Candy.checkCollision()
method you forgot to include the self
argument in the definition. It should be:
def checkCollision(self, sprite1, sprite2):
Upvotes: 1