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

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.

Related

Unable to close pygame window when try again button clicked

I am making a spaceship game where you control a spaceship and fire bullets to destroy enemy spaceships. When you click the try again button when you lose, you should be able to both replay and close the game. However, even though I was able to play multiply times, I wasn't able to close the window. I think this has something to do with the if statement that checks if the try again button is clicked. Or maybe it has something to do with something else. How can I fix it so I can close the window at all times?
This is my current code:
import pygame
from pygame.locals import *
from random import randint, choice
from tools import *
pygame.init()
pygame.font.init()
SCREEN_X = 800
SCREEN_Y = 500
CENTER_POS = (400, 225)
screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y))
class Spaceship(pygame.sprite.Sprite):
"""A spaceship object. Used for the player."""
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x, self.y = x, y
self.image = pygame.image.load("spaceship.png")
self.image = pygame.transform.scale(self.image, (175, 175))
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
"""Updates the spaceship rect"""
self.rect.center = (self.x, self.y)
class Bullet(pygame.sprite.Sprite):
"""A bullet object. Appears when the player clicks."""
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x, self.y = x, y
self.image = pygame.image.load("bullet.png")
self.image = pygame.transform.scale(self.image, (100, 100))
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
"""Let's the bullet move upward."""
self.y -= 5
self.rect.center = (self.x, self.y)
if self.y < 0:
self.kill()
class Enemy(pygame.sprite.Sprite):
"""An enemy object. The player's job is to destroy enemies."""
def __init__(self, s, x, y, t):
pygame.sprite.Sprite.__init__(self)
self.type = t
self.screen, self.x, self.y = s, x, y
self.image = pygame.image.load(get_enemy_image()[self.type])
# There is an if statement because the
# N1 Galaxy Fighter and M7 Comet Glider need different sizes
if self.type == "N1 Galaxy Fighter":
self.image = pygame.transform.scale(self.image, (235, 215))
elif self.type == "M7 Comet Glider":
self.image = pygame.transform.scale(self.image, (155, 215))
self.rect = self.image.get_rect()
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
self.score_given = get_enemy_given_score()[self.type]
def update(self):
if self.y < 0:
self.kill()
self.y += 3
self.rect.center = (self.x, self.y)
class GameOverBackground(pygame.sprite.Sprite):
"""The game over background object."""
def __init__(self, s, x, y, size=(100, 100)):
pygame.sprite.Sprite.__init__(self)
self.screen, self.x, self.y = s, x, y
self.size = size
self.image = pygame.image.load("Game_Over.jpg")
self.image = pygame.transform.scale(self.image, self.size)
self.rect = self.image.get_rect()
def blitme(self):
"""Blits the game over image on the screen"""
self.screen.blit(self.image, self.rect)
class Coin(pygame.sprite.Sprite):
"""A coin object."""
def __init__(self, pos=(0, 0), size=(100, 100)):
pygame.sprite.Sprite.__init__(self)
self.x, self.y = pos[0], pos[1]
self.size = size
self.image = pygame.image.load("coin.png")
self.image = pygame.transform.scale(self.image, self.size)
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
"""Updates the coin rect"""
self.rect.center = (self.x, self.y)
class StartButton(pygame.sprite.Sprite):
def __init__(self, s, x, y, size=None):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x = x
self.y = y
self.image = pygame.image.load("start_button.png")
if size is not None:
self.image = pygame.transform.scale(self.image, size)
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def blitme(self):
self.screen.blit(self.image, self.rect)
class TryAgainButton(pygame.sprite.Sprite):
def __init__(self, s, x, y, size=None):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x = x
self.y = y
self.image = pygame.image.load("try_again.png")
if size is not None:
self.image = pygame.transform.scale(self.image, size)
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def blitme(self):
self.screen.blit(self.image, self.rect)
def main():
bg = GameOverBackground(screen, 0, 0, size=(800, 500))
spaceship = Spaceship(screen, 400, 400)
start_button = StartButton(screen, CENTER_POS[0], CENTER_POS[1], size=(300, 195))
button_rect = start_button.image.get_rect(topleft=(start_button.x, start_button.y))
game_started = False
try_again_button = TryAgainButton(screen, CENTER_POS[0], CENTER_POS[1]+215, size=(300, 195))
button_rect_2 = try_again_button.image.get_rect(topleft=(try_again_button.x, try_again_button.y))
try_again = False
bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()
coins = pygame.sprite.Group()
clock = pygame.time.Clock()
enemy_interval = 2000
enemy_event = pygame.USEREVENT + 1
pygame.time.set_timer(enemy_event, enemy_interval)
coin_interval = 3500
coin_event = pygame.USEREVENT + 1
pygame.time.set_timer(coin_event, coin_interval)
score = 0
lives = 3
with open("high_score.txt", "r") as file:
highscore = file.read()
font = pygame.font.SysFont("Arial", 30)
score_text_surface = font.render("Score: {:,}".format(score), True, (0, 0, 0))
lives_text_surface = font.render("HP: %s" % lives, True, (0, 0, 0))
high_score_text_surface = font.render("High Score: %s" % highscore, True, (0, 0, 0))
spaceship_collided = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == MOUSEBUTTONDOWN:
if not game_started:
if button_rect.collidepoint(event.pos):
game_started = True
if game_started is True and button_rect_2.collidepoint(event.pos):
try_again = True
if game_started and event.type == MOUSEBUTTONDOWN:
bullet = Bullet(screen, spaceship.x, spaceship.y - 20)
bullets.add(bullet)
if game_started and event.type == enemy_event and not lives <= 0:
enemy = Enemy(screen, randint(-100, 725), 0, choice(["N1 Galaxy Fighter", "M7 Comet Glider"]))
enemies.add(enemy)
if game_started and event.type == coin_event and not lives <= 0:
if len(coins) < 100:
coins.add(Coin((randint(-125, 750), randint(-200, 400))))
screen.fill((255, 255, 255)) # DO NOT DRAW ANYTHING IN FRONT OF THIS LINE, I'M WARNING YOU
if not game_started:
start_button.blitme()
if try_again:
main()
if game_started:
bullets.update()
key = pygame.key.get_pressed()
amount = 5
if key[pygame.K_a]:
spaceship.x -= amount
elif key[pygame.K_d]:
spaceship.x += amount
elif key[pygame.K_w]:
spaceship.y -= amount
elif key[pygame.K_s]:
spaceship.y += amount
spaceship.update()
if not lives <= 0:
screen.blit(spaceship.image, spaceship.rect)
if not lives <= 0:
bullets.draw(screen)
enemies.draw(screen)
coins.update()
coins.draw(screen)
for i in enemies:
i.update()
if pygame.sprite.spritecollide(i, bullets, True):
score += i.score_given
i.kill()
if spaceship_collided and lives <= 0:
bg.blitme()
if score > int(highscore):
with open("high_score.txt", "w") as file:
file.write(str(score))
if score >= 99999:
score = 99999
if not lives <= 0:
score_text_surface = font.render("Score: {:,}".format(score), True, (0, 0, 0))
screen.blit(score_text_surface, (590, 0))
lives_text_surface = font.render("HP: %s" % lives, True, (0, 0, 0))
screen.blit(lives_text_surface, (260, 0))
high_score_text_surface = font.render("High Score: %s" % highscore, True, (0, 0, 0))
screen.blit(high_score_text_surface, (360, 0))
if pygame.sprite.spritecollide(spaceship, enemies, dokill=True):
lives -= 1
spaceship_collided = True
if pygame.sprite.spritecollide(spaceship, coins, dokill=True):
score += 10
if lives <= 0:
try_again_button.blitme()
pygame.display.update()
clock.tick(60)
if __name__ == "__main__":
main()
You can't do it like that. Never run the main application loop recursively. The issue is
if try_again:
main()
What you are actually doing is starting a new game within the game in progress. If you want to close the game, you will need to close all games that you have started before. Hence, you have to press close several times.
Instead of calling main recursively, you either have to reset all game states or call main in a loop.
In your particular situation, the later solution is easier to implement. Remove the recursive call but set running = False, return try_again from main and call main while it returns True:
def main():
# [...]
try_again = False
running = True
while running:
# [...]
if try_again:
# main() <---- DELETE
running = False
# [...]
return try_again
if __name__ == "__main__":
keep_running = True
while keep_running:
keep_running = main()

Pygame: player sprite colliding incorrectly and clipping into wall

I am creating a 4-way movement, tile based rpg. The code I have written for collision detection is relatively simple but I have a minor graphical error.
The player moves directly between evenly spaced tiles. To control the speed the player moves at there is a walk buffer of 200 seconds. When the player collides with a wall, they should be pushed back in the same direction they hit the wall. This works, however, very briefly the player sprite will flicker in the wall.
I suspect it's to do with the player update function and how that's ordered but I've messed around with it to no avail.
import sys
vec = pg.math.Vector2
WHITE = ( 255, 255, 255)
BLACK = ( 0, 0, 0)
RED = ( 255, 0, 0)
YELLOW = ( 255, 255, 0)
BLUE = ( 0, 0, 255)
WIDTH = 512 # 32 by 24 tiles
HEIGHT = 384
FPS = 60
TILESIZE = 32
PLAYER_SPEED = 3 * TILESIZE
MAP = ["1111111111111111",
"1P.............1",
"1..............1",
"1..1111........1",
"1..1..1........1",
"1..1111.111111.1",
"1............1.1",
"1........111.1.1",
"1........1...1.1",
"1........11111.1",
"1..............1",
"1111111111111111"]
def collide_hit_rect(one, two):
return one.hit_rect.colliderect(two.rect)
def player_collisions(sprite, group):
hits_walls = pg.sprite.spritecollide(sprite, group, False, collide_hit_rect)
if hits_walls:
sprite.pos -= sprite.vel * TILESIZE
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.walk_buffer = 200
self.vel = vec(0, 0)
self.pos = vec(x, y) *TILESIZE
self.current_frame = 0
self.last_update = 0
self.walking = False
self.walking_sprite = pg.Surface((TILESIZE, TILESIZE))
self.walking_sprite.fill(YELLOW)
self.image = self.walking_sprite
self.rect = self.image.get_rect()
self.hit_rect = self.rect
self.hit_rect.bottom = self.rect.bottom
def update(self):
self.get_keys()
self.rect = self.image.get_rect()
self.rect.topleft = self.pos
self.pos += self.vel * TILESIZE
self.hit_rect.topleft = self.pos
player_collisions(self, self.game.walls)
self.rect.midbottom = self.hit_rect.midbottom
def get_keys(self):
self.vel = vec(0,0)
now = pg.time.get_ticks()
keys = pg.key.get_pressed()
if now - self.last_update > self.walk_buffer:
self.vel = vec(0,0)
self.last_update = now
if keys[pg.K_LEFT] or keys[pg.K_a]:
self.vel.x = -1
elif keys[pg.K_RIGHT] or keys[pg.K_d]:
self.vel.x = 1
elif keys[pg.K_UP] or keys[pg.K_w]:
self.vel.y = -1
elif keys[pg.K_DOWN] or keys[pg.K_s]:
self.vel.y = 1
class Obstacle(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.walls
pg.sprite.Sprite.__init__(self, self.groups)
self.x = x * TILESIZE
self.y = y * TILESIZE
self.w = TILESIZE
self.h = TILESIZE
self.game = game
self.image = pg.Surface((self.w,self.h))
self.image.fill(BLACK)
self.rect = self.image.get_rect()
self.hit_rect = self.rect
self.rect.x = self.x
self.rect.y = self.y
class Game:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("Hello Stack Overflow")
self.clock = pg.time.Clock()
pg.key.set_repeat(500, 100)
def new(self):
self.all_sprites = pg.sprite.Group()
self.walls = pg.sprite.Group()
for row, tiles in enumerate(MAP):
for col, tile in enumerate(tiles):
if tile == "1":
Obstacle(self, col, row)
elif tile == "P":
print("banana!")
self.player = Player(self, col, row)
def quit(self):
pg.quit()
sys.exit()
def run(self):
# game loop - set self.playing = False to end the game
self.playing = True
while self.playing:
self.dt = self.clock.tick(FPS) / 1000
self.events()
self.update()
self.draw()
def events(self):
# catch all events here
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
def update(self):
self.player.update()
def draw(self):
self.screen.fill(WHITE)
for wall in self.walls:
self.screen.blit(wall.image, wall.rect)
for sprite in self.all_sprites:
self.screen.blit(sprite.image, sprite.rect)
pg.display.flip()
# create the game object
g = Game()
while True:
g.new()
g.run()
pg.quit()```
You're setting the rect before checking for collision but not resetting it after the collision check.
Here is the updated code (in Player class, update method):
self.hit_rect.topleft = self.pos
player_collisions(self, self.game.walls) # may change postion
self.hit_rect.topleft = self.pos # reset rectangle

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__()

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)

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

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

Categories

Resources