0

I want a code that whenever the player and the fruit collide... to just end the game.

player:

playerImg = pygame.image.load('trash.png')    
x = 370    
y = 480    

def player(x, y):    
    screen.blit(playerImg, (x, y))

fruit1:

fruitImg = pygame.image.load('001-apple.png')    
fruit_x = random.randrange(0, width)    
fruit_y = -600    
fruit_speed = 5    
fruit_width = 100    
fruit_height = 100

def fruit(fruit_x, fruit_y, fruit_width, fruit_height):    
    screen.blit(fruitImg, (fruit_x, fruit_y, fruit_width, fruit_height))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
michel
  • 11
  • What have you tried so far? It'll be helpful if you can state your approach. It's called collision detection. Google is your friend. – Rohan Bojja Apr 17 '20 at 02:02
  • Does this answer your question? [How to detect collision of two images in pygame](https://stackoverflow.com/questions/59551594/how-to-detect-collision-of-two-images-in-pygame) – Rohan Bojja Apr 17 '20 at 02:07
  • 1
    Does this answer your question? [How do I detect collision in pygame?](https://stackoverflow.com/questions/29640685/how-do-i-detect-collision-in-pygame) – Jack Moody Apr 17 '20 at 02:07
  • Please try searching before posting your question. Thanks! – Rohan Bojja Apr 17 '20 at 02:08

1 Answers1

2

Use pygame.Rect objects and .colliderect():

fruit_rect = fruitImg.get_rect(topleft = (fruit_x, fruit_y))
player_rect = playerImg.get_rect(topleft = (x, y))
if player_rect.colliderect(fruit_rect):
    print("collide")

colliderect returns True if 2 rectangles are intersecting.
get_rect() returns a pygame.Rect which contains the size of a pygame.Surface. This rectangle will always start at (0, 0). The location of the rectangle can be set a keyword argument (e.g. topleft = (x, y))

Rabbid76
  • 202,892
  • 27
  • 131
  • 174