Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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):
        pygame.sprite.Sprite.__init__(self)
        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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.