Please help.
I am new to pygame. I can't work out why my collision detection isn't working. I am using spritecollide and just cannot see why sprites aren't being removed from sprites_list. I am using an image and a circle drawn by pygame could this have something to do with it?
The game should be a very simple collection game where the player sprite can move around using arrow keys and cause the red circles to disappear. Many thanksin advance for any help with this.
import pygame, sys
from pygame.locals import *
import random
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("king_black.png")
self.rect = self.image.get_rect()
class CircleSprite(pygame.sprite.Sprite):
def __init__(self, colour, width, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width, height])
self.rect = self.image.get_rect()
self.image.set_colorkey((0,0,0))
pygame.draw.ellipse(self.image, colour, [0, 0, width, height])
#initialise pygame
pygame.init()
#Setup game clock
FPS = 30 #Frames per second
clock = pygame.time.Clock()
#Setup display
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Hello world!")
#Setup colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
rect_x = 200
rect_y = 150
rect_width = 100
rect_height = 50
player = Player()
#Create a sprite group
sprites_list = pygame.sprite.Group()
#Circle list
circle_list = pygame.sprite.Group()
for i in range(10):
circle = CircleSprite(RED, 40, 40)
# Set a random location for the circle
circle.rect.x = random.randrange(400)
circle.rect.y = random.randrange(300)
# Add the circle to the list of objects
sprites_list.add(circle)
sprites_list.add(player)
#Main game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#Looks for pressed keys
keys_pressed = pygame.key.get_pressed()
#Responds to most recent key pressed
if keys_pressed[K_LEFT]:
rect_x -= 5
if keys_pressed[K_RIGHT]:
rect_x += 5
if keys_pressed[K_UP]:
rect_y -= 5
if keys_pressed[K_DOWN]:
rect_y += 5
#Collision detection
sprite_hits = pygame.sprite.spritecollide(player, sprites_list, True)
#Draw screen background
DISPLAYSURF.fill((WHITE))
#Draw circles to display
sprites_list.draw(DISPLAYSURF)
#Blit image to display and flip it.
DISPLAYSURF.blit(player.image, (rect_x, rect_y))
pygame.display.flip()
clock.tick(FPS)