I am writing a game in Pygame and want to get collision detection working. The aim is that when an object hits another, the target object disappears. I want to avoid having classes for now, to keep things simple. This makes it difficult to get collision detection working, because the Rect method in Pygame assumes classes.

The logic I want to achieve is:

if object hits a target object
    target object disappears

What's the minimal code I'd need to achieve this?


2 Answers 2


I think you mean you don't want to create your own classes such as:

class Player(pygame.sprite.Sprite):
    def __init__(self, rect, image):
        self.rect = rect
        self.image = image

Which is doable, but not a very good practice. With that in mind, here's how you do it.

Create a player sprite:

player = pygame.sprite.Sprite()
# size is 40x40, position is 0, 0
player.rect = pygame.Rect(0, 0, 40, 40)

# image is 40x40 grey block
player.image = pygame.Surface((40, 40))
player.image.fill((60, 60, 60))

Then add a block sprite that the player can collect:

blocks = pygame.sprite.Sprite()
# size is 20x20, position is 300, 300
block.rect = pygame.Rect(300, 300, 20, 20)

# image is 20x20 green block
block.image = pygame.Surface((20, 20))
block.image.fill((60, 200, 60))

With two sprites, pygame.sprite.collide_rect() can be used for collision detection:

if pygame.sprite.collide_rect(player, block):
    # move block to a new position
    block.rect.x = random.randint(20, 480)
    block.rect.y = random.randint(20, 480)
    print "You ate a block!"

The sprites can be drawn on the screen like this:

# topleft is the position of the top left corner of the sprite
screen.blit(block.image, block.rect.topleft)
screen.blit(player.image, player.rect.topleft)

Here's a fully working example.


Another approach (If you don't want to use sprite for whatever reasons) is to write your own collision detection logic. The logic will basically check if difference in x and y co-ordinates of each rect objects is within the delta. The delta is width and height of one of the objects capturing collision.

from math import fabs
def has_collided_with(rect1,rect2):
    deltay = fabs(rect1.centery - rect2.centery)
    deltax = fabs(rect1.centerx - rect2.centerx)
    return deltay < rect2.height and deltax < rect2.width

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .