I am trying to add collision detection to this simple game, but I am a little lost on where to begin. I know I need to use rects to do this but I am struggling to find out what I need to code to make this work. Any pseudocode or any hints pointing me in the right direction would be greatly appreciated.

Here is my code:

#Image Variables
bg = 'bg.jpg'
bunk = 'bunker.png'
enemytank = 'enemy-tank.png'

#Import Pygame Modules
import pygame, sys
from pygame.locals import *

#Initializing the Screen
pygame.init()
screen = pygame.display.set_mode((640,360), 0, 32)

#Loading Images and More Variables
background = pygame.image.load(bg).convert()
bunker = pygame.image.load(bunk).convert_alpha()
e_tank = pygame.image.load(enemytank).convert_alpha()
bunker_x, bunker_y = (160,0)

#Setting Up The Animation
x = 0
clock = pygame.time.Clock()
speed = 250

#Main Loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    screen.blit(background, (0,0))
    screen.blit(bunker, (bunker_x, bunker_y))
    screen.blit(e_tank, (x, 0))

    #Animation
    milli = clock.tick()
    seconds = milli/1000.
    dm = seconds*speed
    x += dm

    if x>640:
        x=0


    #Update the Screen
    pygame.display.update()

Recommended Answers

All 4 Replies

PyGame offers sprites and sprite groups that help with doing collision detection. Documentation on sprites can be found here: http://www.pygame.org/docs/ref/sprite.html

I'm using objects in my game, and I extend the pygame sprite class for all of my sprites. All sprite objects have a .rect property that represents their position and size. You can place sprites inside a sprite group to help with drawing, updates, and collisions.

As an example, I have a sprite group that contains all of the walls and characters in my game. My collision detection method looks like:

 def getCollisionObjects(self, obj):
        if (obj not in self._visibleObjects):
            return False
        self._visibleObjects.remove(obj)
        result = pygame.sprite.spritecollide(obj, self._visibleObjects, False)
        self._visibleObjects.add(obj)
        return result

In my example, I remove the current object from the list, then call the sprite collide method which checks my object against all the visible objects, and then place the object back in the visible object group. Result contains a list of objects that collided with my object.

I give a few more examples and ideas in this blog post: http://burnhamup.com/blog/2012/09/collision-detection-in-pygame/

commented: nice help +13

Ok, I have been rewriting my code, adding classes and objects. But when it comes to making rects. I am a little confused. According to the Pygame documentation, there are a couple ways to make rects.

pygame.Rect(left, top, width, height): return Rect
pygame.Rect((left, top), (width, height)): return Rect
pygame.Rect(object): return Rect

The first two I could probably do without a problem, but I don't want to have to find the sizes of every single sprite in my game. So can someone explain how the last option works. I have tried to put one of the objects in the parameters but I get this error.

'Argument must be Rect style object'

I would appreciate any help on this problem.

Right. You don't need to manually calculate your rects for all your sprites.
I grabbed this code snippet from http://www.pygame.org/docs/tut/chimp/ChimpLineByLine.html

def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

I call this on all the sprites I want to load. The image returned by pygame.image.load() has a method called get_rect which returns a rect object with the dimensions of the sprite you loaded. I think its x and y coordinates default to 0,0 so I move the rect to where to object is supposed to be. I store the image as self.image and the rect as self.rect

Thank you very much for helping me out.

I am very sorry about all of these questions but if you don't mind I have one final question concerning collision detection.

I have rewritten my code using classes and objects. And in my tank class I have a function called collide. I have added an if statement in my main loop that should check for collision. But I can figure this out on my own through trial and error. So if you do not mind could you point me in the right direction.

I promise this is the last question I will ask you.

class EnemyTank(pygame.sprite.Sprite):
     def __init__(self):
         pygame.sprite.Sprite.__init__(self)
         enemytank = pygame.image.load(enemy_tank).convert_alpha()
         self.image = enemytank
         self.rect = self.image.get_rect()
     def update(self):
         self.pos = self.rect.center
         return self.pos






if player.collide == True:
     e_tank_x += 0
     player.pos += 0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.