1

I am just starting off with pygame and python so no judgement (thanks:)) but I have been trying to use colliderect() to check for collision of two rect (snake, food; I think). I keep getting this error. AttributeError: 'Food' object has no attribute 'colliderect' What am I doing wrong?

# main function
def main():
    clock = pygame.time.Clock()
    FPS = 17
    run = True
    snake = Snake(random.randint(0, 400), random.randint(0, 400), 10, 10)
    food = Food(random.randint(0, 400), random.randint(0, 400), 10, 10)
    snakeVelocity_X = 0
    snakeVelocity_Y = 0
    lost = False
# snake object
# Rect object: Rect(x, y, width, height)
class Snake():
    def __init__(self, x, y, width, height):
        self.x = x 
        self.y = y
        self.width = width
        self.height = height

    def draw(self, gameScreen):
        pygame.draw.rect(gameScreen, colors.BLACK, (self.x, self.y, self.width, self.height))

    # def get_head_position(self):
    #   return self.x, self.y, self.width, self.height

# food object
class Food():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.collide = False

    def draw(self, gameScreen):
        pygame.draw.rect(gameScreen, colors.YELLOW, (self.x, self.y, self.width, self.height))
# check for collision
        if food.colliderect(snake):
            print("collision")

Above is the code I think is sufficient to get my point across.

Ps. I am new to stackoverflow too any do/don'ts.

  • `food` seems to be an instance of `Food`. Why would you expect `food` to have a method `colliderect`? According to your code snippet you didn't define such a method. – Matthias Apr 23 '21 at 14:21
  • @Matthias it is already a method of the Rect object from the Pygame module. :) – tk_unatnahs Apr 28 '21 at 06:17

1 Answers1

0

colliderect is a method of pygame.Rect. However Food is not a pygame.Rect object.

Remove the attributes x, y, width and height, but add a rect` attribute:

class Food():
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height)
        self.collide = False

    def draw(self, gameScreen):
        pygame.draw.rect(gameScreen, colors.YELLOW, self.rect)

Now you can use the method colliderect with food.rect:

if food.rect.colliderect(snake):
    print("collision")
Rabbid76
  • 202,892
  • 27
  • 131
  • 174