Collision Detection With 'jump/not smooth'' movement - python

My problem with the code is that I created a sprite that is able to move a tile each time when an arrow key is pressed, the problem is when the sprite moves onto a tile that has a wall on it, it still goes onto the tile instead of staying on the tile that it is on. I can't seem to get the right collision detection code.
import pygame
import random
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
red = ( 255, 0, 0)
GREEN = ( 0, 255, 0)
wall = ( 66, 66, 66)
# This class represents the ball
# It derives from the "Sprite" class in Pygame
class Main(pygame.sprite.Sprite):
walls = None
def __init__(self, filename):
# Calls the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Creates the 'block' that will contain the image
self.image = pygame.image.load(filename).convert()
# Set background colour so its transparent
self.image.set_colorkey(black)
# Sets parameters so you can adjust the x and y values
self.rect = self.image.get_rect()
def update (self,):
# Moving left or right
self.rect.x += self.change_y
# Did something collide into wall ?
wall_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for wall in wall_hit_list:
# If we are moving right, set our right side to the left side of the item we hit
if self.change_y > 0:
self.rect.right = wall.rect.left
else:
# Otherwise if we are moving left, do the opposite
self.rect.left = wall.rect.right
# Move up/down
self.rect.y += self.change_x
# Check and see if we hit anything
wall_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for wall in wall_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_x > 0:
self.rect.bottom = wall.rect.top
else:
self.rect.top = wall.rect.bottom
class Wall(pygame.sprite.Sprite):
# Wall that the player can run into.
def __init__(self, filename):
# Constructor
pygame.sprite.Sprite.__init__(self)
# Make a wall
self.image = pygame.image.load(filename).convert()
# Sets parameters so you adjust the x and y values
self.rect = self.image.get_rect()
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
# List of all the sprites
all_sprites_list = pygame.sprite.Group ()
# List of the main sprite ( squirtle )
main_sprite = pygame.sprite.Group ()
# List of Walls
wall_list = pygame.sprite.Group ()
wall = Wall("wall2.png",)
wall.rect.x = 100
wall.rect.y = 150
wall_list.add(wall)
all_sprites_list.add(wall)
# Sets player to the class 'Main' which thanks to the parameter, is squirtle
Hero = Main ("Character.png")
player = Main ("Character.png")
# Spawns squirtle in a random position
Hero.rect.x = 4
Hero.rect.y = 1
# Adds squirtle to the lists that we made
main_sprite.add(Hero)
all_sprites_list.add(Hero)
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while done == False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Hero.rect.x -= 50
elif event.key == pygame.K_RIGHT:
Hero.rect.x += 50
elif event.key == pygame.K_UP:
Hero.rect.y -= 50
elif event.key == pygame.K_DOWN:
Hero.rect.y += 50
# Clear the screen
screen.fill(white)
# Drawing Code
y_offset = 0
x_offset = 0
while x_offset < 750:
pygame.draw.line(screen,GREEN, [0+x_offset,0], [0+x_offset,500],1)
x_offset = x_offset + 50
while y_offset < 550:
pygame.draw.line(screen, GREEN, [0,0+y_offset], [700,0+y_offset],1)
y_offset = y_offset + 50
# Draw all the sprites
all_sprites_list.draw(screen)
pygame.display.flip ()
clock.tick (60)
pygame.quit ()`

First of all, you never call the update method of your sprites, so your collision check is never performed.
If you would call it, it would fail, because you try to read self.change_y, which you never set.
If you would, it would still fail, because you try to check the collision against the sprites in self.walls, but you never set it thus self.walls is always None.

Related

Pygame returns an error when you click a sprite with another sprite that isn't listed

I'm just making a title screen for a future project, and when I run it the "PLAY" and "QUIT" buttons work fine enough but when you click the surrounding background or the title image, the game freezes up and returns the error, "AttributeError: 'list' object has no attribute 'sprites'" I tried adding a blank audio file seperate from the "if play == 0:" in case it was just confused when it had nothing to do, but the problem stayed.
import pygame
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255,255,0)
score = 0
play = 0
class Sprite(pygame.sprite.Sprite):
def __init__(self,filename):
super().__init__()
self.image = pygame.image.load(filename).convert()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
class Player(Sprite):
def update(self):
""" Method called when updating a sprite. """
# Get the current mouse position. This returns the position
# as a list of two numbers.
pos = pygame.mouse.get_pos()
# Now see how the mouse position is different from the current
# player position. (How far did we move?)
diff_x = self.rect.x - pos[0]
diff_y = self.rect.y - pos[1]
# Loop through each block that we are carrying and adjust
# it by the amount we moved.
# Now wet the player object to the mouse location
self.rect.x = pos[0]
self.rect.y = pos[1]
class Block(pygame.sprite.Sprite):
def __init__(self, color, width, height):
# Call the parent class (Sprite) constructor
super().__init__()
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
self.image = pygame.Surface([width, height])
self.image.fill(color)
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width = 750
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])
pygame.display.set_caption("LARP")
# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()
quit_block = pygame.sprite.Group()
start_block = pygame.sprite.Group()
title_image = pygame.image.load("title.png").convert_alpha()
quit_image = pygame.image.load("quit.png").convert_alpha()
logo_image = pygame.image.load("logo.png").convert_alpha()
player_image = pygame.image.load("player.png").convert_alpha()
background_image = pygame.image.load("title_screen.png").convert_alpha()
bomp = pygame.mixer.Sound("bump.wav")
# This is a list of every sprite.
# All blocks and the player block as well.
player_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
#for i in range(50):
#This represents a block
#block = Block(BLACK, 20, 15)
#Set a random location for the block
#block.rect.x = random.randrange(screen_width)
#block.rect.y = random.randrange(screen_height)
#Add the block to the list of objects
#block_list.add(block)
#all_sprites_list.add(block)
title = Sprite("title.png")
title.rect.x = 340
title.rect.y = 230
all_sprites_list.add(title)
start_block.add(title)
quitg = Sprite("quit.png")
quitg.rect.x = 340
quitg.rect.y = 350
all_sprites_list.add(quitg)
quit_block.add(quitg)
logo = Sprite("logo.png")
logo.rect.y = 90
logo.rect.x = 310
all_sprites_list.add(logo)
block_list.add(logo)
player = Player("player.png")
player_list.add(player)
all_sprites_list.add(player)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Hide the mouse cursor
pygame.mouse.set_visible(False)
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# When the mouse button is pressed, see if we are in contact with
# other sprites:
if play == 0:
start_block = pygame.sprite.spritecollide(player, start_block, True)
if len(start_block) >= 1:
play += 1
quit_block = pygame.sprite.spritecollide(player, quit_block, True)
if len(quit_block) >= 1:
done = True
#print(score)
#blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
#if len(blocks_hit_list) >= 1:
#score +=1
# Set the list of blocks we are in contact with as the list of
# blocks being carried.
#player.carry_block_list = blocks_hit_list
elif event.type == pygame.MOUSEBUTTONUP:
# When we let up on the mouse, set the list of blocks we are
# carrying as empty.
player.carry_block_list = []
all_sprites_list.update()
# Clear the screen
screen.fill(WHITE)
# Draw all the spites
if play == 0:
screen.blit(background_image, [0,0])
all_sprites_list.draw(screen)
screen.blit(player_image, [player.rect.x, player.rect.y])
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
start_block and quit_block are pygame.sprite.Group(). However, pygame.sprite.spritecollide(). Therefore an instruction like:
start_block = pygame.sprite.spritecollide(player, start_block, True)
makes no sense because the group start_block is overwritten with the list start_block
Change the name of the variable the gets the return value. e.g.:
start_block_hit = pygame.sprite.spritecollide(player, start_block, False)
Note, you don't need to store the return values at all. The doKill argument must be False, otherwise your button will be destroyed when you click it:
if pygame.sprite.spritecollide(player, start_block, False):
play += 1
if pygame.sprite.spritecollide(player, quit_block, False):
done = True

How do I assign an image to each sprite?

I want an image to be in the place of the rectangle.
The class Block is used to make a 'food' square, enemy square, and player square. I need help reformatting Block to also accept an image in the color attributes place.
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0,0,255)
GREEN = (0,255,0)
class Block(pygame.sprite.Sprite):
"""
This class represents the ball.
It derives from the "Sprite" class in Pygame.
"""
def __init__(self, color, width, height):
""" Constructor. Pass in the color of the block,
and its size. """
# Call the parent class (Sprite) constructor
super().__init__()
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
self.image = pygame.Surface([width, height])
self.image.fill(color)
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
class Player(pygame.sprite.Sprite):
""" The class is the player-controlled sprite. """
# -- Methods
def __init__(self, x, y):
"""Constructor function"""
# Call the parent's constructor
super().__init__()
# Set height, width
self.image = pygame.Surface([15, 15])
self.image.fill(BLUE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# -- Attributes
# Set speed vector
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
""" Change the speed of the player"""
self.change_x += x
self.change_y += y
def update(self):
""" Find a new position for the player"""
if self.rect.x < 0:
self.rect.x += 3
wall.play()
if self.rect.x > 685:
self.rect.x-=3
wall.play()
if self.rect.y < 0:
self.rect.y += 3
wall.play()
if self.rect.y > 384:
self.rect.y -= 3
wall.play()
else:
self.rect.x += self.change_x
self.rect.y += self.change_y
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
good_block_list = pygame.sprite.Group()
bad_block_list = pygame.sprite.Group()
collision_sound_good = pygame.mixer.Sound("good_block.wav")
collision_sound_bad = pygame.mixer.Sound("bad_block.wav")
wall = pygame.mixer.Sound("bump.wav")
# This is a list of every sprite.
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
for i in range(50):
# This represents a block
block = Block(GREEN, 20, 15)
# Set a random location for the block
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(screen_height)
# Add the block to the list of objects
good_block_list.add(block)
all_sprites_list.add(block)
for i in range(50):
# This represents a block
block = Block(RED, 20, 15)
# Set a random location for the block
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(screen_height)
# Add the block to the list of objects
bad_block_list.add(block)
all_sprites_list.add(block)
# Create a RED player block
player = Player(100,50)
all_sprites_list.add(player)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
score = 0
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Set the speed based on the key pressed
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.changespeed(-3, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(3, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, -3)
elif event.key == pygame.K_DOWN:
player.changespeed(0, 3)
# Reset speed when key goes up
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.changespeed(3, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(-3, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, 3)
elif event.key == pygame.K_DOWN:
player.changespeed(0, -3)
# Game Logic
# This calls update on all the sprites
all_sprites_list.update()
# Clear the screen
screen.fill(WHITE)
good_blocks_hit_list = pygame.sprite.spritecollide(player, good_block_list, True)
bad_blocks_hit_list = pygame.sprite.spritecollide(player, bad_block_list, True)
# Check the list of collisions.
for block in good_blocks_hit_list:
collision_sound_good.play()
score += 1
print(score)
for block in bad_blocks_hit_list:
collision_sound_bad.play()
score -= 1
print(score)
font = pygame.font.SysFont(None, 45)
text = font.render(str(score), True, BLACK)
screen.blit(text, (54, 350))
# Draw all the spites
all_sprites_list.draw(screen)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(60)
pygame.quit()
There are 3 different kinds of blocks that need a separate image.
The blocks are added to sprite group, so I don't think it is possible to Blit the image in the loop.
Question Answered
I would modify the Block constructor such that the color parameter was just a parameter representing the appearance of the sprite. It might be a string filename, or a colour-tuple. This can be tested at run-time.
def __init__(self, appearance, width, height):
""" Create a new sprite sized <width> by <height>.
The sprite is, either a coloured block where <appearance> is a
RGB colour-tuple, OR an image loaded from a file """
# Call the parent class (Sprite) constructor
super().__init__()
# appearance is either an RGB tuple, or a filename str
if ( type( appearance ) is tuple ):
# Create an image of the block, and fill it with a color
self.image = pygame.Surface([width, height])
self.image.fill( appearance )
else:
# The parameter <appearance> holds an image filename
bitmap = pygame.image.load( appearance ).convert()
self.image = pygame.transform.smoothscale( bitmap, ( width, height ) )
# Fetch the rectangle object that has the dimensions of the image image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
I'm not really sure this is the best approach of doing this sort of thing. I guess maybe it could allow for a debug-fallback if the image resources are not found or suchlike.
This allows the code to:
new_sprite = Block( ( 182, 128, 0 ), 64, 64 )
[...]
new_sprite = Block( "sandstone.png", 64, 64 )
Soo I may have an answer for my own question...
class Block(pygame.sprite.Sprite):
"""
This class represents the ball.
It derives from the "Sprite" class in Pygame.
"""
def __init__(self, imageFile, width, height):
""" Constructor. Pass in the color of the block,
and its size. """
# Call the parent class (Sprite) constructor
super().__init__()
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
#self.image = pygame.Surface([width, height])
#self.image.fill(color)
self.image = pygame.image.load(imageFile).convert()
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()

Pygame mouse click detection on moving sprites

I'm making a "duck hunt" game in pygame. I have everything working, my sprites move and respawn when needed, cursor is a crosshair with sound when clicked etc. The issue I'm having is trying to add points when the mouse is click on a duck. Any idea how I would do this? Posted all of the code, its a bit of a mess until I get thank working, check the main loop specifically. Thanks.
import pygame
import random
import duck_code
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
DUCK_BACK = (59, 202, 255)
class Player(pygame.sprite.Sprite):
""" The class is the player-controlled sprite. """
# -- Methods
def __init__(self, x, y, filename):
"""Constructor function"""
# Call the parent's constructor
super().__init__()
# Set height, width
self.image = pygame.Surface([15, 15])
self.image.fill(BLACK)
self.image = pygame.image.load(filename).convert()
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# -- Attributes
# Set speed vector
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
""" Change the speed of the player"""
self.change_x += x
self.change_y += y
def update(self):
""" Find a new position for the player"""
self.rect.x += self.change_x
self.rect.y += self.change_y
# boarders for walls, reset player, play bump sound
if self.rect.x in range(1060, 1085):
self.rect.x -= 25
if self.rect.x in range(-5, 0):
self.rect.x += 25
if self.rect.y in range(-5, 0):
self.rect.y += 25
if self.rect.y in range(480, 505):
self.rect.y -= 25
# Initialize Pygame
# Loading sounds
pygame.init()
game_background = pygame.image.load("game_background.jpg")
duck_hit = pygame.mixer.Sound("duck_hit.wav")
player_click = pygame.mixer.Sound("shot_gun.ogg")
# Set the height and width of the screen
screen_width = 1280
screen_height = 1024
screen = pygame.display.set_mode([screen_width, screen_height])
# Starting score and font settings
font = pygame.font.Font(None, 36)
score = 0
# This is a list of every sprite.
all_sprites_list = pygame.sprite.Group()
duck_list = pygame.sprite.Group()
duck_hit_list = pygame.sprite.Group()
"""DUCKS"""
for i in range(5):
# This represents a block
ducks = duck_code.Duck("duck1.png")
ducks.rect.x = random.randrange(screen_width)
ducks.rect.y = random.randrange(50, 350)
# Add the block to the list of objects
duck_list.add(ducks)
all_sprites_list.add(ducks)
"""PLAYER"""
player_image = pygame.image.load("crosshair.png")
player_image.set_colorkey(WHITE)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
score = 0
# Hide the mouse cursor
pygame.mouse.set_visible(0)
# -------- Main Program Loop -----------
while not done:
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
blocks_hit_list = pygame.sprite.spritecollide(mouse, duck_list, True)
score += 100
print(score)
player_click.play()
# --- Game logic should go here
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
screen.blit(game_background, [0, 0])
player_position = pygame.mouse.get_pos()
x = player_position[0]
y = player_position[1]
screen.blit(player_image, [x, y])
pos = pygame.mouse.get_pos()
pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
# Check if the rect collided with the mouse pos
# and if the left mouse button was pressed.
all_sprites_list.draw(screen)
duck_list.update()
# Showing scoreboard
text = font.render("Score: " + str(score), True, WHITE)
screen.blit(text, [10, 10])
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(60)
pygame.quit()
pygame.sprite.spritecollide only works with a sprite as the first argument and a sprite group as the second argument. To check if the mouse collides with a duck, you can iterate over the duck_list with a for loop and call the collidepoint method of the current duck's rect:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for duck in duck_list:
if duck.rect.collidepoint(event.pos): # event.pos is the mouse position.
score += 100

PyGame collision working but sprite being reset - motion not continuing.

Having trouble with my PyGame experimental game - I'm learning how to work with sprites.
I have been trying to code 'collision' detection between sprites (ball and paddle) and have managed to get the collision detection working but my ball sprite seems to reset its position instead of carrying on. Could anyone take a look and see where my error is?
Here is my code:
import pygame
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#variables, constants, functions
x = 1
y = 1
x_vel = 10
y_vel = 10
bat_x = 1
bat_y = 1
bat_x_vel = 0
bat_y_vel = 0
score = 0
class Ball(pygame.sprite.Sprite):
"""
This class represents the ball.
It derives from the "Sprite" class in Pygame.
"""
def __init__(self, width, height):
""" Constructor. Pass in the color of the block,
and its x and y position. """
# Call the parent class (Sprite) constructor
super().__init__()
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# Draw the ellipse
pygame.draw.ellipse(self.image, (255,0,0), [0,0,width,height], 10)
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
# Instance variables that control the edges of where we bounce
self.left_boundary = 0
self.right_boundary = 0
self.top_boundary = 0
self.bottom_boundary = 0
# Instance variables for our current speed and direction
self.vel_x = 5
self.vel_y = 5
def update(self):
""" Called each frame. """
self.rect.x += self.vel_x
self.rect.y += self.vel_y
if self.rect.right >= self.right_boundary or self.rect.left <= self.left_boundary:
self.vel_x *= -1
if self.rect.bottom >= self.bottom_boundary or self.rect.top <= self.top_boundary:
self.vel_y *= -1
class Paddle(pygame.sprite.Sprite):
"""
This class represents the ball.
It derives from the "Sprite" class in Pygame.
"""
def __init__(self, width, height):
""" Constructor. Pass in the color of the block,
and its x and y position. """
# Call the parent class (Sprite) constructor
super().__init__()
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# Draw the rectangle
pygame.draw.rect(self.image, (0, 255, 0), [0, 0, width, height], 0)
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
# Instance variables for our current speed and direction
self.x_vel = 0
self.y_vel = 0
def update(self):
# Get the current mouse position. This returns the position
# as a list of two numbers.
self.rect.x = self.rect.x + self.x_vel
self.rect.y = self.rect.y + self.y_vel
#initialise ball and paddle
paddle = Paddle(20, 100)
ball = Ball(100,100)
# This is a list of every sprite.
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
all_sprites_list.add(ball)
all_sprites_list.add(paddle)
ball_sprites_list = pygame.sprite.Group()
ball_sprites_list.add(ball)
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Loop until the user clicks the close button.
done = False
# -------- Main Program Loop -----------
while not done:
# --- Events code goes here (mouse clicks, key hits etc)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
paddle.y_vel = -3
if event.key == pygame.K_DOWN:
paddle.y_vel = 3
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
paddle.y_vel = 0
if event.key == pygame.K_DOWN:
paddle.y_vel = 0
# --- Game logic should go here
# Calls update() method on every sprite in the list
all_sprites_list.update()
# collision check
ball_hit_list = pygame.sprite.spritecollide(paddle, ball_sprites_list, False)
# Check the list of collisions.
for ball in ball_hit_list:
score +=1
print(score)
# --- Clear the screen
screen.fill((255,255,255))
# --- Draw all the objects
all_sprites_list.draw(screen)
# render text
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render(str(score), 1, (0,0,0))
screen.blit(label, (100, 100))
# --- Update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
pygame.quit()
Sorry,
Have found the error.
Didn't set the boundaries of the window properly.
# Instance variables that control the edges of where we bounce
self.left_boundary = 0
self.right_boundary = 700
self.top_boundary = 0
self.bottom_boundary = 400

Multiple bullets not showing up when added to Pygame sprite group and updated

I'm working on my first project in Python / Pygame, which is a shooter-style game. However, when I create multiple instances of my Bullet sprite and add them to the sprite group, only the most recent instance is shown on the screen. That is, only one bullet is showing at any given time.
I think Lines 175-180 or within the Bullet class are causing the problem.
My code:
import pygame, random , sys , time
from pygame.locals import *
# Screen dimensions
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
# Global constants
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
LIGHTBLUE = ( 0, 0, 155)
FPS = 60
class Player(pygame.sprite.Sprite):
# set speed vector of the player
change_x = 0
change_y = 0
moverate = 5
# Constructor. Pass in x and y position
def __init__(self, x, y):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create player image
self.image = pygame.image.load('player.png')
self.image.set_colorkey(WHITE)
# Set a referance to the image rect.
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.y = y
def changespeed(self, x, y):
""" Change the speed of the player"""
self.change_x += x
self.change_y += y
def update(self):
""" Move the player. """
# Move left/right
self.rect.x += self.change_x
# Move up/down
self.rect.y += self.change_y
def stop(self):
""" Called when the user lets off the keyboard."""
self.change_x = 0
self.change_y = 0
self.image = pygame.image.load('player.png')
self.image.set_colorkey(WHITE)
class Enemy(pygame.sprite.Sprite):
""" This class represents the enemy sprites."""
minmoverate = 1
maxmoverate = 8
def __init__(self):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('enemyShip.png')
self.image = pygame.transform.scale(self.image, (50, 50))
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
def reset_pos(self):
""" Reset position to the top of the screen, at a random x location.
Called by update() or the main program loop if there is a collision."""
self.rect.y = - ( SCREEN_HEIGHT / 4)
self.rect.x = random.randrange(SCREEN_WIDTH)
def update(self):
""" Move the enemies. """
# Move down, at some speed
self.rect.y += 2
# Move left and right, at some speed
self.rect.x += 0
# If enemy is too far down, reset to top of screen
if self.rect.y > SCREEN_HEIGHT:
self.reset_pos()
class Bullet(pygame.sprite.Sprite):
""" This class represents the bullet. """
def __init__(self):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([8, 20])
self.image.fill(LIGHTBLUE)
self.rect = self.image.get_rect()
def update(self):
""" Move the bullet. """
self.rect.y -= 10
class Game(object):
""" This class represents an instance of the game. If we need to
rest the game we'd just need to create a new instance of this class."""
# --- Class attributes.
# Sprite lists
enemy_list = None
bullet_list = None
all_sprites_list = None
# --- Class methods
# Set up the game
def __init__(self):
self.score = 0
self.game_over = False
# Create sprite lists
self.enemy_list = pygame.sprite.Group()
self.bullet_list = pygame.sprite.Group()
self.all_sprites_list = pygame.sprite.Group()
# Create the starting enemy ships
for i in range(15):
enemy = Enemy()
enemy.rect.x = random.randrange(SCREEN_WIDTH)
enemy.rect.y = random.randrange(-300, 20)
self.enemy_list.add(enemy)
self.all_sprites_list.add(enemy)
# Create the player
self.player = Player(SCREEN_WIDTH / 2, SCREEN_HEIGHT - (SCREEN_HEIGHT / 6))
self.all_sprites_list.add(self.player)
def process_events(self):
""" Process all of the events. Return "True" if we need to close the window."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
return True
elif event.key == K_RETURN:
if self.game_over:
self.__init__()
elif event.key in (K_RIGHT ,K_d):
self.player.changespeed( self.moverate ,0)
elif event.key in (K_LEFT ,K_a):
self.player.changespeed( -self.moverate ,0)
elif event.key in (K_UP , K_w):
self.player.changespeed(0, -self.moverate)
elif event.key in (K_DOWN , K_s):
self.player.changespeed(0, self.moverate)
elif event.key == K_SPACE: # Fire bullet
bullet = Bullet(0
# Set bullet so it is where the player is
bullet.rect.centerx = self.player.rect.centerx
bullet.rect.y = self.player.rect.y
# Add bullet to lists
self.all_sprites_list.add(bullet)
self.bullet_list.add(bullet)
elif event.type == KEYUP:
if event.key in (K_RIGHT ,K_d):
self.player.changespeed( -self.moverate ,0)
elif event.key in (K_LEFT ,K_a):
self.player.changespeed( self.moverate ,0)
elif event.key in (K_UP , K_w):
self.player.changespeed(0, self.moverate)
elif event.key in (K_DOWN , K_s):
self.player.changespeed(0, -self.moverate)
def run_logic(self):
""" This method is run each time through the frame.
It updates positions and checks for collisions."""
enemy = Enemy()
if not self.game_over:
# Move all the sprites
self.all_sprites_list.update()
if len(self.all_sprites_list) < 17:
self.enemy_list.add(enemy)
self.all_sprites_list.add(enemy)
enemy.rect.x = random.randrange(SCREEN_WIDTH)
enemy.rect.y = random.randrange(-100, -50)
# Bullet Mechanics
for bullet in self.bullet_list:
# See if the bullets has collided with anything.
self.enemy_hit_list = pygame.sprite.spritecollide(bullet, self.enemy_list, True)
# For each enemy hit, remove bullet and enemy and add to score
for enemy in self.enemy_hit_list:
self.bullet_list.remove(bullet)
self.all_sprites_list.remove(bullet)
self.score += 1
# Remove the bullet if it flies up off the screen
if bullet.rect.y < -10:
self.bullet_list.remove(bullet)
self.all_sprites_list.remove(bullet)
# Player Mechanics
for enemy in self.enemy_list:
# See if player has collided with anything.
self.player_hit_list = pygame.sprite.spritecollide(self.player, self.enemy_list, True)
if len(self.player_hit_list) == 1:
# If player is hit, show game over.
self.game_over = True
def display_frame(self, screen):
""" Display everything to the screen for the game. """
screen.fill(BLACK)
if self.game_over:
# font = pygame.font.Font("Serif:, 25)
font = pygame.font.SysFont("serif", 25)
text = font.render("Game Over! You scored " + str(self.score) +" points, press Enter to restart", True, WHITE)
center_x = (SCREEN_WIDTH // 2) - (text.get_width() // 2)
center_y = (SCREEN_HEIGHT // 2) - (text.get_height() // 2)
screen.blit(text, [center_x, center_y])
if not self.game_over:
self.all_sprites_list.draw(screen)
pygame.display.flip()
def main():
""" Main program function. """
# Initialize Pygame and set up the window
pygame.init()
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
screen_rect = screen.get_rect()
pygame.display.set_caption("My Game")
pygame.mouse.set_visible(False)
# Create our objects and set the data
done = False
clock = pygame.time.Clock()
# Create an instance of the Game class
game = Game()
# Main game loop
while not done:
# Process events (keystrokes, mouse clicks, etc)
done = game.process_events()
# Update object positions, check for collisions
game.run_logic()
# Draw the current frame
game.display_frame(screen)
# Pause for the next frame
clock.tick(FPS)
# Close window and exit
pygame.quit()
# Call the main function, start up the game
if __name__ == "__main__":
main()
The problem is that you're only ever creating a single Bullet instance, which you're storing in the Game.bullet class variable. Whenever you shoot, the code moves that single bullet to the player's position, and it updates from there.
You probably want to create a new bullet for every shot. Use something like this in process_events:
elif event.key == K_SPACE: # Fire bullet
bullet = Bullet()
bullet.rect.centerx = self.player.rect.centerx
bullet.rect.y = self.player.rect.y
# Add bullet to lists
all_sprites_list.add(self.bullet)
bullet_list.add(self.bullet)
That creates a new bullet every time the space bar is pressed. If your game design specifies a limit to the number of bullets that can be "active" at once, you may need some more complex logic (or if the performance cost of creating and destroying lots of instances is too much you could write some object caching code), but this should get you on the right track.
Now, the code above doesn't do anything to remove the bullets later, so you'll probably need to handle that too or your game will bog down from the calculations involving off-screen bullets. I'd suggest putting some logic in Bullet.update() that calls self.kill() if the bullet is off the screen (or whenever makes sense for your game). The instance will be garbage collected automatically when there are no more references to it.
I'd also suggest getting rid of all of the class variables of you Game class, which are either unnecessary (they get shadowed by instance variables that are created in __init__), or broken (like bullet).

Categories