Malcadicta
Malcadicta

Reputation: 37

pygame.colliderect moving rectangles

I'm trying to write a pacman clone using pygame. I have a ghost and our pacman moving around the maze and I tried to define a function that would recognise whether they collided and change the variable which tells whether the game is supposed to go on.

This is the function:

def eat(self, pacman):
    if self.rect.colliderect(pacman):
        return False
    else:
        return True

And this is game loop:

while (game_on == True):
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    pacman.change_direction(tiles)
    ghost.Move(tiles, layout)
    for tile in tiles:
        pacman.collision(tile)
    screen.blit(background, (0,0))
    for tile in tiles:
        tile.draw(screen)
    ghost.draw(screen)
    pacman.draw(screen)
    pygame.display.update()
    game_on = ghost.eat(pacman)

if game_on is False:
    screen.blit(background, (0,0))
    text = font.render('GAME OVER', True, (255,255,0))
    screen.blit(text, SCREEN_SIZE)
    time.sleep(5)

Both pacman and ghost are classes with self.rect that is a pygame.Rect Same method to check collision works just fine for ghost and maze tiles; here they just go through each other.

Upvotes: 0

Views: 138

Answers (1)

Larry McMuffin
Larry McMuffin

Reputation: 227

You were giving your eat() function the whole pacman class for collision detection. Use pacman.rect instead.

Example: Instead of game_on = ghost.eat(pacman), use game_on = ghost.eat(pacman.rect).

Upvotes: 1

Related Questions