0
votes

I've been working on creating a small, space invaders style game in pygame. I've almost reached the end however, I want to make it so if the enemy ships collide with my ship, a collision is detected and the game ends.

So far I have the code for detecting when a bullet and an enemy ship collides, however when I tried to rewrite this for a enemy/player collision it doesnt work as expected, so I think im doing something incorrect.

Code in question:

for block in block_list:

    player_hit_list = pygame.sprite.spritecollide(block, player_list, True)

    for player in player_hit_list:
        explosion.play()
        block_list.remove(block)
        player_list.remove(player)
        all_sprites_list.remove(block)
        all_sprites_list.remove(player)

    if block.rect.y < +10:
        block_list.remove(block)
        all_sprites_list.remove(block)  

Full code: http://pastebin.com/FShPuR6A

Is anyone able to tell my why the code I have isnt functioning?

Thanks a lot

1
And what is actually happening? Does the game never quit, the player disappears? - Bartlomiej Lewandowski
@BartlomiejLewandowski The enemy ships just pass over the player as normal, nothing disappears and the game doesnt quit :( - Oscar

1 Answers

0
votes
class Block(pygame.sprite.Sprite):
    def __init__(self, color):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("spaceship.png")
        self.rect = self.image.get_rect()

    def update(self):
        self.rect.y += 1

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.x=0
        self.y=0
        self.image = pygame.image.load("alien.png")
        self.rect = self.image.get_rect()

    def update(self):
        pos = pygame.mouse.get_pos()
        self.rect.x = pos[0]

At first glance, you have a Block class, with a picture of a spaceship that moves like an Alien. The Player class, has an alien image, and moves with the mouse.

My advice would be to rename the classes so that you will know what is what. It will be easier to spot the error.

EDIT:

It also looks like your Player does not move at all:

def render(self):
        if (self.currentImage==0):
            screen.blit(self.image, (self.x, self.y))

You update the player via self.rect.x, but you draw using self.x and self.y.