Search code examples
pythonpygamespritecollision

How do I use .spritecollide() in pygame to detect for collisions?


I am trying to learn how to use pygame by creating a simple 'shmup' game with blocks. When running the code, no errors are shown, however the game does not seem to be detecting collisions between the sprites. Am I using this incorrectly? Any help much appreciated. If it would be easier to run the code for yourself that should be possible as there are no external files used.

    hits = pygame.sprite.spritecollide(player,mobs, False) 
    if hits:
        running = False

All code:

import pygame
import random
import time

pygame.init()
pygame.mixer.init()

width = 480
height = 600

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

#initialise pygame and create window
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("Shoot 'Em Up!")
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self):  #this is mandatory, it loads the built in sprite 
function/code
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50,40))
        self.image.fill(green)

        self.rect = self.image.get_rect()
        self.rect.centerx = width / 2
        self.rect.bottom = height - 10
        self.speedx = 0

    def update(self):
        self.speedx = 0    #thi section makes the sprite move, sets x speed
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -5
        if keystate[pygame.K_RIGHT]:
            self.speedx = 5

        self.rect.x += self.speedx
        # sets the boundaries of screen
        if self.rect.right > width:
            self.rect.right = width
        if self.rect.left < 0:
            self.rect.left = 0

class Mob(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30,40))
        self.image.fill(red)
        self.rect = self.image.get_rect()

        self.rect.x = random.randrange(0, width - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(1, 8)
        #randomising angle of movement
        self.speedx = random.randrange(-3, 3)

    def update(self):
        self.rect.x += self.speedx
        self.rect.y += self.speedy
        if self.rect.top > height + 10 or self.rect.left < -30 or 
self.rect.right > width + 30:
            self.rect.x = random.randrange(0, width - self.rect.width)
            self.rect.y = random.randrange(-100, -40)
            self.speedy = random.randrange(3, 8)


all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()  #make a spearte group for mobs to enable 
collisions between groups
player = Player()
all_sprites.add(player)

# spawning the mobs
for i in range (8):  #start with spawning 8
    m = Mob()
    all_sprites.add(m)
    mobs.add

#Game Loop
running = True

while running:
    clock.tick(60) #keep running at the right speed

    for event in pygame.event.get():  #process events (inputs)
        if event.type == pygame.QUIT:  #check for closing of window
            running = False

    #update
    all_sprites.update()


    # check to see if a mob hit a player
    hits = pygame.sprite.spritecollide(player,mobs, False) # which sprites 
do you want to check for collisisons
    if hits:
        running = False

    #render
    screen.fill(black)
    all_sprites.draw(screen) #where to draw sprites in the group
    pygame.display.flip()

pygame.quit()

Solution

  • You just have to add the Mob instance m to the mobs sprite group:

    for i in range (8):  #start with spawning 8
        m = Mob()
        all_sprites.add(m)
        mobs.add(m)  # Add `m` to the group.