I am currently making a Guitar Hero like game in python and I am trying to blit a note multiple times, but I can't seem to get it to work (the note is called Red)!
#Sprite Class
class Sprite(pygame.sprite.Sprite):
# What has to be passed when you create a sprite.
# image_file: The filename of the image.
# lacation: The initial location of where to draw the image.
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self) # Call Sprite initializer
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.xSpeed = 15 # The default xSpeed
self.ySpeed = 15 # The default ySpeed
self.name = "Not Assigned"
self.speed = 10
self.direction = 0
def setSpeed(self, speed):
self.speed = speed
self.calcXYSpeeds()
def setDirection(self, direction):
self.direction = direction
self.calcXYSpeeds()
def calcXYSpeeds(self):
angleRadians = math.radians(self.direction) # Convert the direction to radians.
self.xSpeed= self.speed*math.cos(angleRadians)
self.ySpeed = self.speed*math.sin(angleRadians)
def move(self):
self.rect = self.rect.move(self.xSpeed,self.ySpeed)
def setDirectionTowards(self, (x,y)):
self.direction = math.degrees(math.atan2((self.rect.x - x), (self.rect.y - y)))
self.direction = 270 - self.direction
self.calcXYSpeeds()
#Object Variables
Red = Sprite("Red.png", (100,25))
note1 = Sprite("note1.jpg", (50,650))
#add sprite to group
notes = pygame.sprite.Group()
notes.add(Red)
# Create an clock to keep track time
clock = pygame.time.Clock()
#Scoring Variables
font=pygame.font.Font(None,50)
score=0
score_text=font.render(str(score),1,(225,225,225))
#other Variables
Red1=0
ySpeed = 10
running = 1
while (running==1):
# Sets the frame rate to 30 frames/second.
clock.tick(30)
# Gets any events like keyboard or mouse.
event = pygame.event.poll()
key=pygame.key.get_pressed()
#object random spawn
time = pygame.time.get_ticks()
if (time==30*(random.randint(0,1000))):
screen.blit(Red.image, Red.rect)
pygame.display.update()
#Object Movement
Red.rect.y = Red.rect.y + ySpeed
#Keys to complete notes
if key[pygame.K_a]and Red1==0 and pygame.sprite.collide_rect(Red, note1) == True:
font=pygame.font.Font(None,50)
score = score+1
score_text=font.render(str(score),1,(225,225,225))
Red1=1
#where i currently working to fix the problem
notes.Group.clear(screen, background)
notes.Group.update()
notes.draw(screen)
# Sets the exit flag if the X was clicked on the run window.
if event.type == pygame.QUIT:
running = 0
# Color the whole screen with a solid color.
screen.fill((0, 255, 255))
#prints objects
screen.blit(note1.image, note1.rect)
screen.blit(Red.image, Red.rect)
screen.blit(score_text,(500,50))
# Update the window.
pygame.display.update()
You are cleaning and updating the screen multiple times in the same cycle.
Clean the screen in every cycle is a correct approach, but you need to clean only once otherwise you are erasing everything you blitted before.
Also, for notes to persist between cycles you need to keep them in a collection, like notes, that way you blit every note in every cycle.
Keep in mind this order in your main loop:
Control FPS (clock.tick())
Check events
Update state (ie: add/remove notes collection, etc)
Clear screen
Draw current state (notes, static elements, etc)
Update display
Another important thing, don't use the same Sprite() nor the same Rectangle in different locations. If you want to draw another copy of the same image in a new location make a copy of the rectangle, then create a new Sprite() object.
Related
I am creating tetris using pygame. i want to use collision detection so that when the shape in play comes into contact with any other previously played shapes, i can stop the shape, as per the logic of tetris. i came across pixel perfect collision using masks. i have followed some tutorials online, however the pixel detection returns true every time a new shape comes into play, not when any shapes collide. sorry in advance for the long code, its the bare minimum for the code to actually and still containing the game element of it. i think there is something wrong with my approach which is causing this error. I basically have a function that everytime the shape in play comes into contact with the 'floor' that shape is held in that position and a new shape is created. i think ive overcomplicated it, in turn creating this error. thanks in advance
import pygame
import sys
import shapelogic
pygame.init()
screensize = width, height = 800, 595
screen = pygame.display.set_mode(screensize)
background_image =pygame.image.load("/Users/marceason/PycharmProjects/Tetris/Wooden_background.jpg").convert_alpha()
myshape = 0
stop_movement = 0
blit_count = 0
stored_shapes = pygame.sprite.Group()
stored_shapes_with_coords = []
extra_blit_required = False
index = 0
count = 0
listofshapes = []
class shapemanager():
def __init__(self):
self.listofshapes = []
def create_another_instance(self):
global count
count += 1
string = "Shape_{0},".format(count)
another_shape = Shape(string)
self.listofshapes.append(another_shape)
global index
object = self.listofshapes[index]
index += 1
return object
def load_shape(self):
shape = self.create_another_instance()
shape.load_shapes()
class Shape(pygame.sprite.Sprite):
def __init__(self, name):
pygame.sprite.Sprite.__init__(self)
self.name = name
self.x = 50
self.y = 100
self.move_event = pygame.USEREVENT + 1
self.reached_bottom_event = pygame.USEREVENT + 2
self.one_sec_timer = 1000
self.half_sec_timer = 500
self.reachbottomflag = False
self.movement_possible = True
self.image = pygame.image.load(
"/Users/marceason/PycharmProjects/Tetris/Tetris_Shapes/Green_Shape_1_Position_1.png")
self.mask = pygame.mask.from_surface(self.image)
self.rect = self.image.get_rect()
def move_shape(self):
if self.movement_possible:
key_input = pygame.key.get_pressed()
if key_input[pygame.K_LEFT]:
self.x -= 16
if key_input[pygame.K_RIGHT]:
self.x += 16
if not self.reachbottomflag:
if key_input[pygame.K_DOWN]:
self.y += 16
def reachbottom(self):
if self.y >= 560:
self.reachbottomflag = True
def no_movement_possible(self):
self.movement_possible = False
def assign_shape():
global myshape
global stop_movement
myshape = sl.create_another_instance()
pygame.time.set_timer(myshape.move_event, myshape.one_sec_timer)
stop_movement = pygame.time.set_timer(myshape.reached_bottom_event, myshape.half_sec_timer)
def blit_used_shapes():
global screen
global blit_count
blit_count = len(stored_shapes_with_coords)
local_count = 0
while local_count < blit_count:
screen.blit(stored_shapes_with_coords[local_count][0], (stored_shapes_with_coords[local_count][1], stored_shapes_with_coords[local_count][2]))
local_count += 1
sl = shapemanager()
##### HERE IS THE PIXEL DETECTION #####
result = pygame.sprite.spritecollide(myshape, stored_shapes, False, pygame.sprite.collide_mask)
## Main loop ##
assign_shape()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
screen.blit(background_image, (0, 0))
screen.blit(myshape.image, (myshape.x, myshape.y))
myshape.move_shape()
key_input = pygame.key.get_pressed()
if key_input[pygame.K_SPACE]:
myshape.rotate_shape()
myshape.reachbottom()
if myshape.reachbottomflag:
if event.type == myshape.reached_bottom_event:
myshape.no_movement_possible()
stored_shape_tuple = [myshape.image, myshape.x, myshape.y]
stored_shapes_with_coords.append(stored_shape_tuple)
stored_shapes.add(myshape)
extra_blit_required = True
assign_shape()
####### PIXEL DETECTION IS HERE IN FOR LOOP ####
if result:
print("this should only execute when two shapes touch!!")
if extra_blit_required:
blit_used_shapes()
pygame.display.update()
The issue is that you are not updating the sprites rect attribute. The sprites rects all have position (0, 0) (since you do not set it in the call to self.image.get_rect()) and as a result the masks will all overlap and collide.
If you read the docs for pygame.sprite.collide_mask you will note that it says that your sprites need to have mask and rect attributes. You have a rect in your sprite and you set it in the __init__(), but you do not keep it updated when you move the sprite. You just change the x and y attributes without adjusting the rect position. The reason that the collide_mask wants a rect is that it uses that to determine the offset parameter for the pygame.mask.Mask.overlap() call that it uses. The important thing to realize is that masks themselves do not have a position, they need the rects to determine the relative positions of the masks.
This is similar to images/surfaces not having a position and needing a rect to track that for them.
On a separate issue, the way you are blit'ing the sprites to the screen makes no sense. You are not using the abilities of the sprite groups to draw and worse you are keeping the image, x and y of the sprite in a separate list and not containing it in the sprite itself. You should go look at some examples of pygame sprite based code. There are lots of examples out there.
I have this classic example of a pygame program:
import pygame
import random
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 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 x and y position. """
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# 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 = 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.'
block_list = pygame.sprite.Group()
# 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(100):
# 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)
# Create a RED player block
player = Block(RED, 20, 15)
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
# Clear the screen
screen.fill(WHITE)
# Get the current mouse position. This returns the position
# as a list of two numbers.
pos = pygame.mouse.get_pos()
# Fetch the x and y out of the list,
# just like we'd fetch letters out of a string.
# Set the player object to the mouse location
player.rect.x = pos[0]
player.rect.y = pos[1]
# See if the player block has collided with anything.
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
# Check the list of collisions.
for block in blocks_hit_list:
score += 1
print(score)
# Draw all the spites
for block in all_sprites_list:
if block.rect.y + 1 > screen_height:
block.rect.y = 0
block.rect.y = block.rect.y + 1
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(120)
pygame.quit()
Well, I notice that when I move the mouse, the rest of the blocks are moving slower(like freezing for a fraction of the second) but when it is in one place everything is moving smooth. The player sprite is in the list of all sprites and there is no calculation of the position of the player - only getting mouse's coordinates. And in my opinion there shouldn't be difference between getting (100,100) all the time and getting something else for coordinates of the mouse.
Could someone please explain why motion of the mouse (player's sprite) affects the rest of the sprites?
Thanks!
The problem is probably that you've been running Python for too long a while without restarting, and a fair bit of data has accumulated in memory without being deallocated during previous runs. As noted in the comments, rebooting will usually solve it.
I'm learning Object Orientated Python and understand the main principals of classes and creating objects from classes however I need something explained Re: the pygame code below. I'm struggling to get my head around what's happening when sprite lists are being created and the two lines of code under the code which creates the ball object (allsprites.add etc). In other words what are sprites and why are lists of them created? Why isn't the ball object just created from the class on its own? Why does it need to be added to a sprite list?? What's going on? Any explanation would be greatly appreciated.
"""
Sample Breakout Game
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
"""
# --- Import libraries used for this program
import math
import pygame
# Define some colors
black = (0, 0, 0)
white = (255, 255, 255)
blue = (0, 0, 255)
# Size of break-out blocks
block_width = 23
block_height = 15
class Block(pygame.sprite.Sprite):
"""This class represents each block that will get knocked out by the ball
It derives from the "Sprite" class in Pygame """
def __init__(self, color, x, y):
""" Constructor. Pass in the color of the block,
and its x and y position. """
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create the image of the block of appropriate size
# The width and height are sent as a list for the first parameter.
self.image = pygame.Surface([block_width, block_height])
# Fill the image with the appropriate color
self.image.fill(color)
# Fetch the rectangle object that has the dimensions of the image
self.rect = self.image.get_rect()
# Move the top left of the rectangle to x,y.
# This is where our block will appear..
self.rect.x = x
self.rect.y = y
class Ball(pygame.sprite.Sprite):
""" This class represents the ball
It derives from the "Sprite" class in Pygame """
# Speed in pixels per cycle
speed = 10.0
# Floating point representation of where the ball is
x = 0.0
y = 180.0
# Direction of ball (in degrees)
direction = 200
width = 10
height = 10
# Constructor. Pass in the color of the block, and its x and y position
def __init__(self):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create the image of the ball
self.image = pygame.Surface([self.width, self.height])
# Color the ball
self.image.fill(white)
# Get a rectangle object that shows where our image is
self.rect = self.image.get_rect()
# Get attributes for the height/width of the screen
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()
def bounce(self, diff):
""" This function will bounce the ball
off a horizontal surface (not a vertical one) """
self.direction = (180 - self.direction) % 360
self.direction -= diff
def update(self):
""" Update the position of the ball. """
# Sine and Cosine work in degrees, so we have to convert them
direction_radians = math.radians(self.direction)
# Change the position (x and y) according to the speed and direction
self.x += self.speed * math.sin(direction_radians)
self.y -= self.speed * math.cos(direction_radians)
# Move the image to where our x and y are
self.rect.x = self.x
self.rect.y = self.y
# Do we bounce off the top of the screen?
if self.y <= 0:
self.bounce(0)
self.y = 1
# Do we bounce off the left of the screen?
if self.x <= 0:
self.direction = (360 - self.direction) % 360
self.x = 1
# Do we bounce of the right side of the screen?
if self.x > self.screenwidth - self.width:
self.direction = (360 - self.direction) % 360
self.x = self.screenwidth - self.width - 1
# Did we fall off the bottom edge of the screen?
if self.y > 600:
return True
else:
return False
class Player(pygame.sprite.Sprite):
""" This class represents the bar at the bottom that the player controls. """
def __init__(self):
""" Constructor for Player. """
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
self.width = 75
self.height = 15
self.image = pygame.Surface([self.width, self.height])
self.image.fill((white))
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()
self.rect.x = 0
self.rect.y = self.screenheight-self.height
def update(self):
""" Update the player position. """
# Get where the mouse is
pos = pygame.mouse.get_pos()
# Set the left side of the player bar to the mouse position
self.rect.x = pos[0]
# Make sure we don't push the player paddle
# off the right side of the screen
if self.rect.x > self.screenwidth - self.width:
self.rect.x = self.screenwidth - self.width
# Call this function so the Pygame library can initialize itself
pygame.init()
# Create an 800x600 sized screen
screen = pygame.display.set_mode([800, 600])
# Set the title of the window
pygame.display.set_caption('Breakout')
# Enable this to make the mouse disappear when over our window
pygame.mouse.set_visible(0)
# This is a font we use to draw text on the screen (size 36)
font = pygame.font.Font(None, 36)
# Create a surface we can draw on
background = pygame.Surface(screen.get_size())
# Create sprite lists
blocks = pygame.sprite.Group()
balls = pygame.sprite.Group()
allsprites = pygame.sprite.Group()
# Create the player paddle object
player = Player()
allsprites.add(player)
# Create the ball
ball = Ball()
allsprites.add(ball)
balls.add(ball)
# The top of the block (y position)
top = 80
# Number of blocks to create
blockcount = 32
# --- Create blocks
# Five rows of blocks
for row in range(5):
# 32 columns of blocks
for column in range(0, blockcount):
# Create a block (color,x,y)
block = Block(blue, column * (block_width + 2) + 1, top)
blocks.add(block)
allsprites.add(block)
# Move the top of the next row down
top += block_height + 2
# Clock to limit speed
clock = pygame.time.Clock()
# Is the game over?
game_over = False
# Exit the program?
exit_program = False
# Main program loop
while exit_program != True:
# Limit to 30 fps
clock.tick(30)
# Clear the screen
screen.fill(black)
# Process the events in the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_program = True
# Update the ball and player position as long
# as the game is not over.
if not game_over:
# Update the player and ball positions
player.update()
game_over = ball.update()
# If we are done, print game over
if game_over:
text = font.render("Game Over", True, white)
textpos = text.get_rect(centerx=background.get_width()/2)
textpos.top = 300
screen.blit(text, textpos)
# See if the ball hits the player paddle
if pygame.sprite.spritecollide(player, balls, False):
# The 'diff' lets you try to bounce the ball left or right
# depending where on the paddle you hit it
diff = (player.rect.x + player.width/2) - (ball.rect.x+ball.width/2)
# Set the ball's y position in case
# we hit the ball on the edge of the paddle
ball.rect.y = screen.get_height() - player.rect.height - ball.rect.height - 1
ball.bounce(diff)
# Check for collisions between the ball and the blocks
deadblocks = pygame.sprite.spritecollide(ball, blocks, True)
# If we actually hit a block, bounce the ball
if len(deadblocks) > 0:
ball.bounce(0)
# Game ends if all the blocks are gone
if len(blocks) == 0:
game_over = True
# Draw Everything
allsprites.draw(screen)
# Flip the screen and show what we've drawn
pygame.display.flip()
pygame.quit()
You don't need to add the balls and blocks to sprite lists - it's just a matter of convenience. You could manually check each ball for a collision, but it's easier to just tell pygame to check them all for you
# See if the ball hits the player paddle
if pygame.sprite.spritecollide(player, balls, False):
# The 'diff' lets you try to bounce the ball left or right
# depending where on the paddle you hit it
diff = (player.rect.x + player.width/2) - (ball.rect.x+ball.width/2)
# Set the ball's y position in case
# we hit the ball on the edge of the paddle
ball.rect.y = screen.get_height() - player.rect.height - ball.rect.height - 1
ball.bounce(diff)
You could draw each thing to the screen separately on each frame, but it's easier just to tell pygame to do it for you:
# Draw Everything
allsprites.draw(screen)
Things can be in more than one list as required, for example a ball is added to the balls list so that you can easily check for collisions, but also added to the allsprites list so that you can easily draw everything on the screen
# Create the ball
ball = Ball()
allsprites.add(ball)
balls.add(ball)
Edit:
An important distinction is that allsprites is actually a sprite.Group. It has a list of sprites inside it, but it also has other methods like draw.
To address your question of "what is a Sprite", it's simply a thing that gets drawn on screen. pygame methods like sprite.Group.draw expect a list of things with certain attributes - such as update. The easiest way to make sure that you provide all of those attributes with the right names is to subclass Sprite, however this is also a (strongly recommended) convenience thing - for instance, this is from the pygame source code:
While it is possible to design sprite and group classes that don't
derive from the Sprite and AbstractGroup classes below, it is strongly
recommended that you extend those when you add a Sprite or Group
class.
So what specifically does subclassing Sprite get you? Let's take a look at the source. Here's how to find the source code for a python module:
>>> import pygame.sprite
>>> pygame.sprite.__file__
'c:\\Python27\\lib\\site-packages\\pygame\\sprite.py'
>>>
Every python module has a __file__ attribute that tells you where the source is located (well not quite every). If you open it up in your editor, and scroll down, you see the class definition for Sprite:
class Sprite(object):
"""simple base class for visible game objects
pygame.sprite.Sprite(*groups): return Sprite
The base class for visible game objects. Derived classes will want to
override the Sprite.update() and assign a Sprite.image and
Sprite.rect attributes. The initializer can accept any number of
Group instances to be added to.
When subclassing the Sprite, be sure to call the base initializer before
adding the Sprite to Groups.
"""
def __init__(self, *groups):
self.__g = {} # The groups the sprite is in
if groups: self.add(groups)
def add(self, *groups):
"""add the sprite to groups
Sprite.add(*groups): return None
Any number of Group instances can be passed as arguments. The
Sprite will be added to the Groups it is not already a member of.
"""
has = self.__g.__contains__
for group in groups:
if hasattr(group, '_spritegroup'):
if not has(group):
group.add_internal(self)
self.add_internal(group)
else: self.add(*group)
def remove(self, *groups):
"""remove the sprite from groups
Sprite.remove(*groups): return None
Any number of Group instances can be passed as arguments. The Sprite will
be removed from the Groups it is currently a member of.
"""
has = self.__g.__contains__
for group in groups:
if hasattr(group, '_spritegroup'):
if has(group):
group.remove_internal(self)
self.remove_internal(group)
else: self.remove(*group)
def add_internal(self, group):
self.__g[group] = 0
def remove_internal(self, group):
del self.__g[group]
def update(self, *args):
"""method to control sprite behavior
Sprite.update(*args):
The default implementation of this method does nothing; it's just a
convenient "hook" that you can override. This method is called by
Group.update() with whatever arguments you give it.
There is no need to use this method if not using the convenience
method by the same name in the Group class.
"""
pass
def kill(self):
"""remove the Sprite from all Groups
Sprite.kill(): return None
The Sprite is removed from all the Groups that contain it. This won't
change anything about the state of the Sprite. It is possible to continue
to use the Sprite after this method has been called, including adding it
to Groups.
"""
for c in self.__g.keys():
c.remove_internal(self)
self.__g.clear()
def groups(self):
"""list of Groups that contain this Sprite
Sprite.groups(): return group_list
Return a list of all the Groups that contain this Sprite.
"""
return self.__g.keys()
def alive(self):
"""does the sprite belong to any groups
Sprite.alive(): return bool
Returns True when the Sprite belongs to one or more Groups.
"""
return (len(self.__g) != 0)
def __repr__(self):
return "<%s sprite(in %d groups)>" % (self.__class__.__name__, len(self.__g))
So in summary, you don't have to subclass Sprite - you could just provide all of these methods on your own - but it's easier if you do ;)
the background of my game is being weird. it doesn't work and the sprites show up, then it works but on top of the sprites!
import pygame
import random
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
lives = 10
# Call this function so the Pygame library can initialize itself
pygame.init()
screen = pygame.display.set_mode([700, 600])
clock = pygame.time.Clock()
# Set positions of graphics
background_position = [0,0]
# Make mouse invisible
pygame.mouse.set_visible(False)
pygame.font.init()
font= pygame.font.Font(None, 50)
# This class represents the ball
# It derives from the "Sprite" class in Pygame
class Background(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the block.
# This could also be an image loaded from the disk.
self.image = pygame.image.load("Grass2.fw.png").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()
# Reset position to the right of the screen, at an x location.
# Called by update() or the main program loop if there is a collision.
def reset_pos(self):
self.rect.y =(0)
self.rect.x =(0)
# Called each frame
def update(self):
# Move block left some pixels
self.rect.x -= 1
# If block is too far left, reset to right of screen.
if self.rect.x < -700:
self.reset_pos()
class Block(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, color, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# 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.image.load("Enemy small.fw.png").convert()
self.image.set_colorkey(white)
# 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()
# 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.
def reset_pos(self):
self.rect.y = random.randrange(0, 600)
self.rect.x = random.randrange(700, 800)
# Called each frame
def update(self):
# Move block right one pixel
self.rect.x -= 1
# If block is too far left, reset to top of screen.
if self.rect.x < -100:
self.reset_pos()
class Player(Block):
def __init__(self, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the block.
# This could also be an image loaded from the disk.
self.image = pygame.image.load("ship.fw.png").convert()
self.image.set_colorkey(white)
# 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()
def update(self):
# Get the current mouse position. This returns the position
# as a list of two numbers.
pos = pygame.mouse.get_pos()
# Fetch the x and y out of the list,
# just like we'd fetch letters out of a string.
# Set the player object to the mouse location
self.rect.x=pos[0]
self.rect.y=pos[1]
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width=700
screen_height=600
screen=pygame.display.set_mode([screen_width,screen_height])
pygame.display.set_caption('Razazone')
clock.tick(70)
#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()
# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
background_list = pygame.sprite.Group()
# This represents a background
background = Background(20,15)
# Set a location for the block
background.rect.x = (screen_width)
background.rect.y = (screen_height)
background_list.add(background)
# Add the block to the list of objects
all_sprites_list.add(background)
for i in range(1):
# 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)
# Create a red player block
player = Player(350, 300)
all_sprites_list.add(player)
done=False
I know there is something wrong about the order of my updates but I can't figure out exactly what I need to do to fix the problem.
# -------- 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#
# Calls update() method on every sprite in the list
all_sprites_list.update()
# See if the player block has collided with anything.
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, False)
# Check the list of collisions.
for block in blocks_hit_list:
lives -=1
print (lives)
# Reset block to the top of the screen to fall again.
block.reset_pos()
# Reset block to the right of the screen to fall again.
#background.reset_pos()
if lives<=1:
lives=1
screen.fill(black)
background.update()
background_list.draw(screen)
# Draw all the spites
all_sprites_list.draw(screen)
lives_text=font.render("%d lives" % lives, True, white)
screen.blit(lives_text, [100,100])
#background.update()
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
You add background to background_list and all_sprite_list and then you draw background_list and all_sprite_list so your background is drawn twice.
Remove all_sprites_list.add(background)
I am trying to make walking animations for images returned from a sprite sheet.
I am using .set_clip to return a portion of the sprite sheet. Everything looks like it should work
But the .set_clip is returning the first Rect value in the list that I provide, rather than the item in the list that I call for.
My Code
import pygame, sys
from pygame.locals import *
xList = (6, 27,48,69)
yList = (24,24,24,24)
wList = (21,21,21,21)
hList = (32,32,32,32)
ani_pos = list(zip(xList, yList, wList, hList))
sprite_num = 0
class Player:
def __init__(self):
playerSheet = pygame.image.load('MainChar1.png').convert() # load sprite sheet
playerSheet.set_clip(pygame.Rect(ani_pos[sprite_num]))
self.player = playerSheet.subsurface(playerSheet.get_clip())
self.x = 320
self.y = 240
def draw(self, DISPLAYSURF):
DISPLAYSURF.blit(self.player, (self.x, self.y))
self.player.set_colorkey(255, 0, 255)# set sprite background invisible
class Background:
def __init__(self):
dirtTile = pygame.image.load('DirtBackground.png').convert()
dirtTile.set_clip(pygame.Rect(0, 0, 863, 1103))
self.background = dirtTile.subsurface(dirtTile.get_clip())
self.x = -111
self.y = -311
def draw(self, DISPLAYSURF):
DISPLAYSURF.blit(self.background, (self.x, self.y))
pygame.init()
FPS = 30
FPSCLOCK = pygame.time.Clock()
# set up the window
WINDOWWIDTH = 640 # size of windows' width in pixels
WINDOWHEIGHT = 480 # size of windows' height in pixels
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('farm game')
player = Player()
background = Background()
pygame.key.set_repeat(1,0) # (mSec to begin repeat, mSec between repeats)
running = True
while running: # the main game loop
DISPLAYSURF.fill (255,255,255)
background.draw(DISPLAYSURF)
player.draw(DISPLAYSURF)
pygame.display.flip()
FPSCLOCK.tick(FPS)
for event in pygame.event.get(): # event handling loop
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
running = False
elif event.type == KEYDOWN:
if event.key == K_d:
background.x -= 4
sprite_num = 2
I am using .set_clip to return a portion of the sprite sheet.
No, you don't. You use subsurface to return a portion of the sprite sheet.
I don't know what you think what set_clip does, but it's probably not what it actually does:
This is a rectangle that represents the only pixels on the Surface that can be modified.
Better explained at the SDL docs:
Sets the clipping rectangle for a surface. When this surface is the destination of a blit, only the area within the clip rectangle will be drawn into.
But the .set_clip is returning the first Rect value in the list that I provide, rather than the item in the list that I call for.
set_clip does not return any Rect value of any list at all.
When you call pygame.Rect(ani_pos[sprite_num]), you're creating a Rect with the values in the list ani_pos at index sprite_num, and sprite_num is 0 when the __init__ method is called.
You store your Surface that you create in the __init__ method in the player field, but you never actually change it. If you want to create some kind of animation, you should change it every n frames. You change sprite_num to 2, but that does not do anything since you never use that value again.