Pygame Collision Not Working - pygame.sprite.collide_rect() - python

I'm working on a space shooter game and In that game, when an alien sprite collides with a player sprite, I want the game to end. When wrote the code for the collision, It didn't end the game. Can someone help me?
main.py
# IMPORTS
import pygame
from sprites import *
from config import *
# GAME
class Game():
def __init__(self):
# INIT PYGAME
pygame.init()
pygame.mixer.init()
pygame.display.set_caption(TITLE)
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
self.running = True
self.player = Player()
# NEW GAME
def new(self):
self.allSprites = pygame.sprite.Group()
self.allAliens = pygame.sprite.Group()
for amount in range(ALIEN_AMOUNT):
self.alien = Alien()
self.allAliens.add(self.alien)
self.allSprites.add(self.alien)
self.allSprites.add(self.player)
self.run()
# RUN GAME
def run(self):
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
self.animate()
self.collision()
# DRAW
def draw(self):
self.screen.fill(BLACK)
self.allAliens.draw(self.screen)
self.allSprites.draw(self.screen)
pygame.display.update()
# ANIMATE
def animate(self):
pass
# DETECT COLLISION
def collision(self):
# player collition with alien
hits = pygame.sprite.collide_rect(self.alien, self.player)
if hits:
self.playing = False
self.running = False
# CHECK FOR EVENTS
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
if self.playing:
self.playing = False
self.running = False
# UPDATE GAME
def update(self):
self.allSprites.update()
# GAME OVER
def gameOver(self):
pass
# START SCREEN
def startScreen(self):
pass
# END SCREEN
def endScreen(self):
pass
game = Game()
game.startScreen()
while game.running:
game.new()
game.gameOver()
# QUIT
pygame.quit()
quit()
sprites.py
# IMPORTS
import pygame, random
from config import *
# PLAYER
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("assets/img/player.png").convert()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.x = WIDTH / 2
self.rect.y = HEIGHT - 50
self.velX = 0
def animate(self):
self.rect.x += self.velX
def control(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.velX = -5
elif keys[pygame.K_RIGHT]:
self.velX = 5
else:
self.velX = 0
def collision(self):
# collision with walls
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > WIDTH:
self.rect.right = WIDTH
def update(self):
self.animate()
self.control()
self.collision()
# ALIEN
class Alien(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("assets/img/rsz_alien.png").convert()
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(10, WIDTH - self.rect.w - 10)
self.rect.y = random.randrange(-100, -10)
self.velY = random.randrange(2, 8)
def animate(self):
self.rect.y += self.velY
def collision(self):
if self.rect.y > HEIGHT:
self.reset()
def update(self):
self.animate()
self.collision()
def reset(self):
self.rect.x = random.randrange(0, WIDTH)
self.rect.y = random.randrange(-100, -10)
self.velY = random.randrange(2, 8)
There's a config.py file but I don't think its needed for this question

You're only testing for collision with a single alien (which will be the last one that you created and assigned to self.alien). You need to iterate over all the aliens and test for collisions between the player and each of them.
def collision(self):
# player collision with each alien
for alien in self.allAliens:
hits = pygame.sprite.collide_rect(alien, self.player)
if hits:
self.playing = False
self.running = False

Related

How to delete a sprite at collision in a TDS game pygame

I simply just want to delete the zombie sprite from my sprite group when the bullet collides with the zombie to create the sense the zombie is dying.
I already tried the Zombie(1,1).kill() but it did not work unfortunatley.
here is my code if it will be helpful...
import pygame
from sys import exit
from random import randint
import math
from pygame.math import Vector2
from pygame.constants import K_LSHIFT, K_SPACE, MOUSEBUTTONDOWN, MOUSEBUTTONUP, K_e
pygame.init()
import time
pygame.mouse.set_visible(True)
class Player(pygame.sprite.Sprite):
def __init__(self, x , y):
super().__init__()
self.x = x
self.y = y
self.image = pygame.image.load('graphics/Robot 1/robot1_gun.png').convert_alpha()
self.rect = self.image.get_rect()
self.orig_image = pygame.image.load('graphics/Robot 1/robot1_gun.png').convert_alpha()
self.rotate_vel = 1
self.cross_image = pygame.image.load('graphics/crosshair049.png')
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, self.rect)
dir_vec = pygame.math.Vector2()
dir_vec.from_polar((180, -self.rotate_vel))
cross_pos = dir_vec + self.rect.center
cross_x, cross_y = round(cross_pos.x), round(cross_pos.y)
surface.blit(self.cross_image, self.cross_image.get_rect(center = (cross_x, cross_y)))
def movement(self):
key = pygame.key.get_pressed()
self.rect = self.image.get_rect(center = (self.x, self.y))
dist = 3 # distance moved in 1 frame, try changing it to 5
if key[pygame.K_DOWN] or key[pygame.K_s]: # down key
self.y += dist # move down
elif key[pygame.K_UP] or key[pygame.K_w]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT] or key[pygame.K_d]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT] or key[pygame.K_a]: # left key
self.x -= dist # move left
def rotate(self, surface):
keys = pygame.key.get_pressed()
if keys[K_LSHIFT]:
self.rotate_vel += 5
self.image = pygame.transform.rotate(self.orig_image, self.rotate_vel)
self.rect = self.image.get_rect(center=self.rect.center)
surface.blit(self.image, self.rect)
if keys[K_SPACE]:
self.rotate_vel += -5
self.image = pygame.transform.rotate(self.orig_image, self.rotate_vel)
self.rect = self.image.get_rect(center=self.rect.center)
surface.blit(self.image, self.rect)
def update(self):
self.movement()
self.draw(screen)
self.rotate(screen)
class Bullet(pygame.sprite.Sprite):
def __init__(self, pos, angle):
super().__init__()
self.image = pygame.image.load('graphics/weapons/bullets/default_bullet.png')
self.image = pygame.transform.rotate(self.image, angle)
self.rect = self.image.get_rect(center = pos)
self.speed = 25
self.pos = pos
self.dir_vec = pygame.math.Vector2()
self.dir_vec.from_polar((self.speed, -angle))
def update(self, screen):
self.pos += self.dir_vec
self.rect.center = round(self.pos.x), round(self.pos.y)
class Zombie(pygame.sprite.Sprite):
def __init__(self, x , y):
super().__init__()
self.x = x
self.y = y
self.image = pygame.image.load('graphics/zombie/zoimbie1_hold.png').convert_alpha()
self.rect = self.image.get_rect(center = (x,y))
self.orig_image = pygame.image.load('graphics/Robot 1/robot1_gun.png').convert_alpha()
def draw(self, surface):
surface.blit(self.image, self.rect)
def update(self):
self.draw(screen)
#screen
clock = pygame.time.Clock()
FPS = 60
screen = pygame.display.set_mode((1200, 600))
#player
player_sprite = Player(600, 300)
player = pygame.sprite.GroupSingle()
player.add(player_sprite)
#bullet
bullet_group = pygame.sprite.Group()
#Zombie
zombie_sprite = Zombie(600, 300)
zombie = pygame.sprite.Group()
zombie.add(zombie_sprite)
#keys
keys = pygame.key.get_pressed()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
pos = player_sprite.rect.center
new_bullet = Bullet(pos, player_sprite.rotate_vel)
bullet_group.add(new_bullet)
if pygame.sprite.spritecollide(zombie_sprite,bullet_group , True):
Zombie(1,1).kill()
bullet_group.update(screen)
#screen
screen.fill('grey')
#player sprite funtions
player.update()
#buller group draw
bullet_group.draw(screen)
bullet_group.update(screen)
#Zombie update
zombie.update()
clock.tick(FPS)
pygame.display.update()
Try zombie_sprite.kill() instead of Zombie(1,1).kill()
You are instantiating a new object instead of destroying the original one.

add() argument after * must be an iterable, not int [duplicate]

Hello I am new to pygame and I am trying to write a shmup game.
However I am always having this error:
TypeError: add() argument after * must be an iterable, not int
self.add(*group)
This is the traceback of the error:
File "C:/Users/Pygame/game.py", line 195, in
player.shoot()
File "C:/Users/Pygame/game.py", line 78, in shoot
bullet = Bullets(self.rect.center,self.angle)
File "C:/Users/Pygame/game.py", line 124, in init
super(Bullets,self).init(pos,angle)
This is the code I have written so far, it works well however when the user wants to shoot the error is being raised.
import os
import pygame
import random
import math
WIDTH = 480
HEIGHT = 600
FPS = 60
#colors:
WHITE = (255,255,255)
BLACK = (0,0,0)
GREEN = (0,250,0)
RED = (255,0,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
#setup assets
game_folder = os.path.dirname("C:/Users/PygameP/")
img_folder = os.path.join(game_folder,"img")
#intialise pygame
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
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
#controls the speed
self.angle = 0
self.orig_image = self.image
#self.rect = self.image.get_rect(center=pos)
def update(self):
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.angle -= 5
self.rotate()
if keystate[pygame.K_RIGHT]:
self.angle += 5
self.rotate()
def rotate(self):
self.image = pygame.transform.rotozoom(self.orig_image, self.angle, 1)
self.rect = self.image.get_rect(center=self.rect.center)
def shoot(self):
bullet = Bullets(self.rect.center,self.angle)
all_sprites.add(bullet)
bullets.add(bullet)
class Mob(pygame.sprite.Sprite):
def __init__(self):
super(Mob,self).__init__()
self.image = pygame.Surface((30,40))
self.image = meteor_img
self.image = pygame.transform.scale(meteor_img,(50,38))
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = int(self.rect.width/2)
self.rect.x = random.randrange(0,WIDTH - self.rect.width)
self.rect.y = random.randrange(-100,-40)
self.speedy = random.randrange(1,8)
#updating the position of the sprite
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10:
self.rect.x = random.randrange(0,WIDTH - self.rect.width)
self.rect.y = random.randrange(-100,-40)
self.speedy = random.randrange(1,8)
class Bullets(pygame.sprite.Sprite):
def __init__(self,pos,angle):
super(Bullets,self).__init__(pos,angle)
# Rotate the image.
self.image = pygame.Surface((10,20))
self.image = bullet_img
self.image = pygame.transform.scale(bullet_img,(50,38))
self.image = pygame.transform.rotate(bullet_img, angle)
self.rect = self.image.get_rect()
speed = 5
self.velocity_x = math.cos(math.radians(-angle))*speed
self.velocity_y = math.sin(math.radians(-angle))*speed
#store the actual position
self.pos = list(pos)
def update(self):
self.pos[0] += self.velocity_x
self.pos[1] += self.velocity_y
self.rect.center = self.pos
if self.rect.bottom <0:
self.kill()
#load all game graphics
background = pygame.image.load(os.path.join(img_folder,"background.png")).convert()
background_rect = background.get_rect()
player_img = pygame.image.load(os.path.join(img_folder,"arrow.png")).convert()
bullet_img = pygame.image.load(os.path.join(img_folder,"bullet.png")).convert()
meteor_img = pygame.image.load(os.path.join(img_folder,"m.png")).convert()
#creating a group to store sprites to make it easier to deal with them
#every sprite we make goes to this group
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
#Update
all_sprites.update()
#checking if a bullet hits a mob
hits = pygame.sprite.groupcollide(mobs,bullets,True,True)
for hit in hits:
m = Mob()
all_sprites.add(m)
mobs.add(m)
hits = pygame.sprite.spritecollide(player,mobs, False,pygame.sprite.collide_circle)
#drawing the new sprites here
screen.fill(BLACK)
#show the background image
screen.blit(background,background_rect)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
Any comments?
You're passing the pos and the angle to the __init__ method of pygame.sprite.Sprite here,
super(Bullets,self).__init__(pos,angle)
but you can only pass sprite groups to which this sprite instance will be added. So just remove those arguments:
super(Bullets,self).__init__()

Can't display more than 1 sprites - PyGame

Problem
My problem is that I have a game that generates 8 obstacles at the start of the game. The issue is that when I loop through the obstacles list, and update the sprites group, it only generates 1 sprite.
What I Want To Happen
When the game loads, I want 8 squares to fly down from the top of the window at random speeds, and starting at random positions.
What Is Currently Happening
Currently, when the game loads, only one square is falling from the screen.
PYthon Code
OBSTICLES_AMOUNT = 8
class Obstacle(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 30))
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.velY = 6
def animate(self):
self.rect.y += self.velY
class Game(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
pygame.init()
pygame.mixer.init()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
self.running = True
self.clock = pygame.time.Clock()
self.obstaclesList = []
self.allSprites = pygame.sprite.Group()
self.obstacles = pygame.sprite.Group()
def new(self):
# create a new game
# add obstacles to list
for i in range(OBSTICLES_AMOUNT):
self.obstacle = Obstacle()
self.obstaclesList.append(self.obstacle)
# make new sprite using list
for i in self.obstaclesList:
self.allSprites.add(i)
self.obstacles.add(i)
self.gameLoop()
def gameLoop(self):
# main game loop
while self.running:
self.draw()
def draw(self):
self.screen.fill(WHITE)
self.allSprites.draw(self.screen)
for sprites in self.obstaclesList:
sprites.update()
self.allSprites.update()
Your code is fixed by
adding missing imports
adding missing constants
renaming animate to update in the Obstacle class
calling pygame.display.update after drawing
using a Clock to limit the framerate
adding event handling
adding code to create a Game instance
Some more improvements:
no need for obstaclesList if you already have obstacles
you can pass Groups directly to Sprite's __init__ function
remove a Sprite when it's no longer on the screen
Here's the code:
import pygame
import random
OBSTICLES_AMOUNT = 8
WIDTH, HEIGHT = 800,600
TITLE='some game of falling stuff'
BLUE = pygame.color.THECOLORS['blue']
WHITE = pygame.color.THECOLORS['white']
class Obstacle(pygame.sprite.Sprite):
def __init__(self, *args):
pygame.sprite.Sprite.__init__(self, *args)
self.image = pygame.Surface((30, 30))
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.velY = 6
def update(self):
self.rect.y += self.velY
if self.rect.y > HEIGHT:
self.kill()
class Game(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
pygame.init()
pygame.mixer.init()
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
self.running = True
self.clock = pygame.time.Clock()
self.allSprites = pygame.sprite.Group()
self.obstacles = pygame.sprite.Group()
def new(self):
# create a new game
# add obstacles to list
for i in range(OBSTICLES_AMOUNT):
Obstacle(self.allSprites, self.obstacles)
while self.running:
self.allSprites.update()
for e in pygame.event.get():
if e.type == pygame.QUIT:
self.running = False
self.draw()
self.clock.tick(60)
def draw(self):
self.screen.fill(WHITE)
self.allSprites.draw(self.screen)
for sprites in self.obstacles:
sprites.update()
pygame.display.update()
if __name__ == '__main__':
Game().new()

Trouble drawing to screen in pygame using group

I'm having a problem, whereby calling a variable all_sprites as a pygame.Group() does not return any values, and I cannot work out why.
class game:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode((screenwidth, screenheight))
pg.display.set_caption("Gammee")
self.clock = pg.time.Clock()
def run(self):
while True:
self.dt = self.clock.tick(FPS) / 1000
self.events()
self.update()
self.draw()
def new(self):
self.othersprites = pg.sprite.Group()
def draw(self):
self.screen.fill(BGCOLOR)
self.othersprites.draw(self.screen)
pg.display.flip()
def quit(self):
pg.quit()
sys.exit()
def update(self):
self.othersprites.update()
def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
g = game()
while True:
g.new()
g.run()
this is the code for the game
class Player(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.all_sprites
pg.sprite.Sprite.__init__(self, self.groups)
self.game = game
self.image = pg.Surface((30, 30), SRCALPHA)
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.vx, self.vy = 0, 0
self.x = x
self.y = y
def get_keys(self):
keys = pg.key.get_pressed()
if keys[pg.K_LEFT] or keys[pg.K_a]:
self.vx = -PLAYER_SPEED
if keys[pg.K_RIGHT] or keys[pg.K_d]:
self.vx = PLAYER_SPEED
if keys[pg.K_UP] or keys[pg.K_w]:
self.vy = -PLAYER_SPEED
if keys[pg.K_DOWN] or keys[pg.K_s]:
self.vy = PLAYER_SPEED
if len(keys) != 0:
self.vx *= 0.9
self.vy *= 0.9
def update(self):
self.get_keys()
self.x += self.vx * self.game.dt
self.y += self.vy * self.game.dt
self.rect.x = self.x
self.rect.y = self.y
however nothing is drawn to the scree. I have also tested by putting
for sprite in self.all_sprites:
print(sprite)
which used to output info on the sprite, but now does nothing,
any ideas as to what I'm doing wrong?
You have to create an instance of the Player in the new method of the game class. Also, the sprite group is called othersprites in the game class and all_sprites in the Player class, but the names have to match.
class game:
def new(self):
self.othersprites = pg.sprite.Group()
# This is how you create an instance/object.
self.player = Player(self, 200, 300)
class Player(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.othersprites
I think it would be nicer and simpler to add the self.player sprite to self.othersprites in the new method instead of passing the whole game instance to the player.
class game:
def new(self):
self.othersprites = pg.sprite.Group()
self.player = Player(200, 300)
self.othersprites.add(self.player)

TypeError: 'Alien' object is not iterable

I'm working on a space shooter and I've made the sprites and added some basic collision detection, but when I added in collision detection for whether or not an alien sprite collides with the player sprite, it gave me this error message:
Traceback (most recent call last):
File "main.py", line 93, in <module>
game.new()
File "main.py", line 33, in new
self.run()
File "main.py", line 45, in run
self.collision()
File "main.py", line 58, in collision
hits = pygame.sprite.spritecollide(self.player, self.alien, False)
File "C:\Users\sidna\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pygame\sprite.py", line 1525, in spritecollide
return [s for s in group if spritecollide(s.rect)]
TypeError: 'Alien' object is not iterable
Here's my code:
main.py
# IMPORTS
import pygame, random
from sprites import *
from config import *
# GAME
class Game():
def __init__(self):
# INIT PYGAME
pygame.init()
pygame.mixer.init()
pygame.display.set_caption(TITLE)
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
self.running = True
# NEW GAME
def new(self):
self.allSprites = pygame.sprite.Group()
self.allAliens = pygame.sprite.Group()
self.player = Player()
for i in range(ALIEN_AMOUNT):
self.alien = Alien()
self.allSprites.add(self.alien)
self.allAliens.add(self.alien)
self.allSprites.add(self.player)
self.run()
# RUN GAME
def run(self):
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
self.collision()
# DRAW
def draw(self):
self.screen.fill(BLACK)
self.allSprites.draw(self.screen)
self.allAliens.draw(self.screen)
pygame.display.update()
# DETECT COLLISION
def collision(self):
# alien collision with player
hits = pygame.sprite.spritecollide(self.player, self.alien, False)
if hits:
running = False
# CHECK FOR EVENTS
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
if self.playing:
self.playing = False
self.running = False
# UPDATE GAME
def update(self):
self.allSprites.update()
self.allAliens.update()
# GAME OVER
def gameOver(self):
pass
# START SCREEN
def startScreen(self):
pass
# END SCREEN
def endScreen(self):
pass
game = Game()
game.startScreen()
while game.running:
game.new()
game.gameOver()
pygame.quit()
quit()
sprites.py
import pygame, random
from config import *
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("assets/img/player.png").convert()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.velX = 0
def animate(self):
self.rect.x += self.velX
def collision(self):
# collision with walls
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
def control(self):
self.velX = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.velX = -5
if keystate[pygame.K_RIGHT]:
self.velX = 5
def update(self):
self.animate()
self.collision()
self.control()
class Alien(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("assets/img/alien.png").convert()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.velY = random.randrange(1, 4)
self.velX = random.randrange(-4, 4)
def animate(self):
self.rect.y += self.velY
self.rect.x += self.velX
def collision(self):
# collision with walls
if self.rect.top > HEIGHT + 10 or self.rect.left < -20 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.velY = random.randrange(1, 4)
self.velX = random.randrange(-4, 4)
def update(self):
self.animate()
self.collision()
config.py
# IMPORTS
import pygame
# ENTIRE GAME VARIABLES
TITLE = "Alien Invasion"
WIDTH = 360
HEIGHT = 570
FPS = 60
# ALIEN CONFIG
ALIEN_AMOUNT = 10
# COLORS
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
The problem is here:
hits = pygame.sprite.spritecollide(self.player, self.alien, False)
The spritecollide() function works like this (from the docs):
spritecollide(sprite, group, dokill, collided = None) -> Sprite_list
You put 'self.alien' as the second parameter, but spritecollide expects a group there. If you just want to collide two different sprites, you want to use collide_rect:
hits = pygame.sprite.collide_rect(self.player, self.alien)
You'll get back True/False whether the two sprites are colliding.
See here for details on all the various collision methods:
http://www.pygame.org/docs/ref/sprite.html

Categories

Resources