How to Use Sprite Collide in Pygame
Asked Answered
E

3

5

I am making a very simple game where the bird (player) has to dodge the rock and if it gets hit by the rock you lose. I am trying to use pygame.sprite.collide_rect() to tell if they touched but I cant seem to figure how to correctly use it.

Here is my code:

import pygame
import os, sys
import random
import time

img_path = os.path.join('C:\Python27', 'player.png')
img_path2 = os.path.join('C:\Python27', 'rock.png')

class Bird(object):  
    def __init__(self):           
        self.image_s = pygame.image.load(img_path)
        self.image_b = self.image_s.get_rect()
        self.x = 0
        self.y = 0

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 2 
        if key[pygame.K_DOWN]:
            self.y += dist 
        elif key[pygame.K_UP]: 
            self.y -= dist
        if key[pygame.K_RIGHT]: 
            self.x += dist 
        elif key[pygame.K_LEFT]:
            self.x -= dist 

   def draw(self, surface):
       surface.blit(self.image, (self.x, self.y))

    def background(self, surface):
        bg = os.path.join('C:\Python27', 'bg.png')
        self.image2 = pygame.image.load(bg)
        surface.blit(self.image2, (0,0))

class Rock(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 rock(self):
        dist = 10
        self.x -=dist

    def rock_draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

    def checkCollision(sprite1, sprite2):
        col = pygame.sprite.collide_rect(sprite1, sprite2)
        if col == True:
            sys.exit()

pygame.init()
screen = pygame.display.set_mode((640, 200))

bird = Bird() 
rock = Rock()
clock = pygame.time.Clock()


running = True
while running:

    for event in pygame.event.get():
       if event.type == pygame.QUIT:
            pygame.quit()
            running = False

        if rock.x < 0:
            y = random.randint(10, 190)
            rock = Rock(640, y)
        rock.checkCollision(bird.image_b, rock.image_b)

    bird.handle_keys()     
    rock.rock()

    screen.fill((255,255,255))
    bird.background(screen)
    bird.draw(screen)
    rock.rock_draw(screen)
    pygame.display.update() 

    clock.tick(40)

When I try to run it it tells me it only takes 2 arguments and I gave three when I try to fix that I get all kinds of different error messages.

Epicycle answered 26/4, 2013 at 2:3 Comment(4)
if collide_rect is an instance method of sprite, then you need to call it like this: sprite1.collide_rect(sprite2). If it is an instance method of rect, then you call it on sprite1's rect. And so on.Acre
im trying to do it like this if pygame.sprite.collide_rect(rock.image_b, bird.image_b)==True: sys.exit() but im getting this error message Traceback (most recent call last): File "C:\Python27\BIRDGAME.py", line 111, in <module> if pygame.sprite.collide_rect(rock.image_b, bird.image_b)==True: File "C:\Python27\lib\site-packages\pygame\sprite.py", line 1147, in collide_rect return left.rect.colliderect(right.rect) AttributeError: 'pygame.Rect' object has no attribute 'rect'Epicycle
Did you read the error message? It says you passed it a parameter with no attribute rect and it expected it to have one. So you need to pass it a parameter with attribute rect.Acre
ohhhh sorry im a begginer thank you!Epicycle
B
8
def checkCollision(sprite1, sprite2):
    col = pygame.sprite.collide_rect(sprite1, sprite2)
    if col == True:
        sys.exit()

should be

def checkCollision(self, sprite1, sprite2):
    col = pygame.sprite.collide_rect(sprite1, sprite2)
    if col == True:
        sys.exit()

since it's a method bound to an object.

Brockway answered 26/4, 2013 at 6:48 Comment(0)
C
4

You have this:

col = pygame.sprite.collide_rect(sprite1, sprite2)

But an easier way to do this would be to simply use colliderect which is a function of rect. It might be easier to try this:

col=sprite1.rect.colliderect(sprite2.rect)
Chromoplast answered 26/4, 2013 at 16:10 Comment(4)
That is false. pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rectPutandtake
Ok, in that case, he can either use the way I mentioned in my answer, or he can use collide_rect() but the problem is that he is passing two sprites instead of one integer number.Chromoplast
No, the Sprite class has no collision functions. The sprite module has a few collision functions, but none of them match what you've entered as an answer.Putandtake
Oops, sorry, I totally forgot, your right. Its actually a function of rect itself, I will edit the answer to fix thatChromoplast
G
3

Change

def checkCollision(sprite1, sprite2):

To

def checkCollision(self, sprite1, sprite2):

And you don't have to check the collision on every event, reduce the indent of rock.checkCollision(bird.image_b, rock.image_b) by 1.

Godoy answered 27/4, 2013 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.