How to update the positional coordinates of my rect? - python

I'm creating a memory card game, but having difficulty updating each boxes' rect starting positions. First for loop loads each image and the second get's the starting position for each one. When I do a collision test, it only answers to <0,125,0,175> as my rect position's aren't updating. How can I update this?
import pygame, sys
from pygame.locals import *
screen_height = 800
screen_width = 800
card_x_size = 125
card_y_size = 175
marginx = 45
marginy = 25
class Box():
def __init__(self,image):
self.image = image
self.rect = image.get_rect()
def draw(self,screen):
screen.blit(self.image, self.rect)
def play_game():
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
back_images = ['back.jpg']*16
back_image_list = []
for back_image in back_images:
back_pic = pygame.image.load(back_image)
back_pic = pygame.transform.scale(back_pic, (card_x_size,card_y_size))
back_image_list.append(back_pic)
rect = back_pic.get_rect()
boxes = [Box(img) for img in back_image_list]
for j, box in enumerate(boxes):
pos_x = marginx + j % 4 * available_spacex
pos_y = marginy + j // 4 * available_spacey
box.rect.topleft = (pos_x, pos_y)
print(pos_x,pos_y)
while True:
mouse_clicked = False
clicked_card = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP:
mouse_clicked = True
print(mousex, mousey)
if rect.collidepoint(mousex,mousey):
clicked_card = True
print("hit")
for b in boxes:
b.draw(screen)
pygame.display.update()
play_game()

You have to evaluate whether the mouse click is on one of the box objects:
for box in boxes:
if box.rect.collidepoint(mousex, mousey):
clicked_card = True
print("hit")
function play_game:
def play_game():
# [...]
while True:
mouse_clicked = False
clicked_card = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
mouse_clicked = True
print(mousex, mousey)
for box in boxes:
if box.rect.collidepoint(mousex, mousey):
clicked_card = True
print("hit")
for b in boxes:
b.draw(screen)
pygame.display.update()

Related

How do I make a changing background while the game is running in Pygame?

I want to have my background alternate between night and day (sprites) every 15 seconds or so, but I want this to happen only while the game is running (True), I've placed it in every place in my while loop, can't seem to get it going. The code we're looking at is the following:
if event.type == BACKCHANGE:
screen.blit(back_change,(0,0))
else:
screen.blit(bg_image,(0,0))
Here's how it fits into my game:
import pygame, sys, time, random
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((500, 800))
pygame.display.set_caption('FALLING MAN')
#Game elements
gravity = 0.15
mov_of_man_x = 0
mov_of_man_y = 0
right_mov = 50
left_mov = 50
game_active = True
#day background
bg_image = pygame.image.load("/Users/apple/Downloads/Python Projects/Climbing_Game/bckwall.jpg").convert()
bg_image = pygame.transform.scale(bg_image,(500, 900))
#night background
bg_image2 = pygame.image.load("/Users/apple/Downloads/Python Projects/Climbing_Game/bckwall2.jpg").convert()
bg_image2 = pygame.transform.scale(bg_image2,(500, 900))
#background swap
back_changer = [bg_image, bg_image2]
back_change = random.choice(back_changer)
#the player
man = pygame.image.load("/Users/apple/Downloads/Python Projects/Climbing_Game/man.png").convert_alpha()
man = pygame.transform.scale(man, (51, 70))
man_rec = man.get_rect(center = (250, -500))
#the platforms player moves on
platform = pygame.image.load("/Users/apple/Downloads/Python Projects/Climbing_Game/platform.png").convert_alpha()
platform = pygame.transform.scale(platform,(300,60))
platform_rec = platform.get_rect(center = (250,730))
#game over screen
game_over_screen = pygame.image.load("/Users/apple/Downloads/Python Projects/Climbing_Game/End_screen.png").convert_alpha()
game_over_screen = pygame.transform.scale(game_over_screen,(500,800))
#moving platforms
def create_plat():
random_plat_pos = random.choice(plat_pos)
new_plat = platform.get_rect(center = (random_plat_pos, 800))
return new_plat
def mov_plat(plats):
for plat in plats:
plat.centery -= 4
return plats
def draw_plat(plats):
for plat in plats:
screen.blit(platform, plat)
#collison detection
def detect_plat(plats):
for plat in plats:
if man_rec.colliderect(plat):
global mov_of_man_y
mov_of_man_y = -4
return
def detect_man(mans):
for man in mans:
if man_rec.top <= -700 or man_rec.bottom >= 900:
return False
if man_rec.left <= -100 or man_rec.right >= 500:
return False
else:
return True
#score
def display_score():
pass
#moving platforms
plat_list = []
PLATMOV = pygame.USEREVENT
pygame.time.set_timer(PLATMOV, 1200)
plat_pos = [100,200,300,400]
#back change
BACKCHANGE = pygame.USEREVENT
pygame.time.set_timer(BACKCHANGE, 1200)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
mov_of_man_x += right_mov
man_rec.centerx += mov_of_man_x
mov_of_man_x -= 50
if event.key == pygame.K_LEFT:
mov_of_man_x += left_mov
man_rec.centerx -= mov_of_man_x
mov_of_man_x -= 50
if event.type == PLATMOV:
plat_list.append(create_plat())
#surfaces
screen.blit(bg_image,(0,0))
if game_active == True:
#gravity
mov_of_man_y += gravity
man_rec.centery += mov_of_man_y
#plats
plat_list = mov_plat(plat_list)
draw_plat(plat_list)
detect_plat(plat_list)
game_active = detect_man(man_rec)
#character
screen.blit(man, man_rec)
"""
if event.type == BACKCHANGE:
screen.blit(back_change,(0,0))
else:
screen.blit(bg_image,(0,0))
"""
else:
screen.blit(game_over_screen, (0,0))
pygame.display.update()
clock.tick(120)
Add a variable that indicates which background to draw:
bg_images = [bg_image, bg_image2]
bg_index = 0
Change the background index when the BACKCHANGE event occurs:
for event in pygame.event.get():
if event.type == BACKCHANGE:
bg_index += 1
if bg_index >= len(bg_images):
bg_index = 0
blit the current background in the application loop:
while True:
# [...]
screen.blit(bg_images[bg_index], (0,0))
# [...]
Application loop:
bg_images = [bg_image, bg_image2]
bg_index = 0
# [...]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# [...]
if event.type == pygame.KEYDOWN:
# [...]
if event.type == PLATMOV:
# [...]
if event.type == BACKCHANGE:
bg_index += 1
if bg_index >= len(bg_images):
bg_index = 0
if game_active == True:
screen.blit(bg_images[bg_index], (0,0))
# [...]
else:
screen.blit(game_over_screen, (0,0))
pygame.display.update()
clock.tick(120)

How to fix collisions in pygame

I'm attempting to detect a collision between two objects (both images).
I have rect's for both the objects, but cannot get the collision to be detected.
I've attempted to use rect's, comparing x and y positions.
import sys
import pygame
from pygame.locals import *
#init pygame
pygame.init()
window_width = 840
window_height = 650
size = (window_width, window_height)
screen = pygame.display.set_mode(size)
bg_img = pygame.image.load("img.png").convert_alpha()
crash = False
bot1x = 150
bot1y = 100
x = (window_width * 0.45)
y = (450)
clock = pygame.time.Clock()
fr = clock.tick(30)
x_speed = 0
car_img = pygame.image.load("car.png").convert_alpha()
car_img = pygame.transform.scale(car_img, (125, 175))
bot_img = pygame.image.load("bot.png").convert_alpha()
bot_img = pygame.transform.scale(bot_img, (175, 200))
def car(x, y):
screen.blit(car_img, (x,y))
def bot(x, y):
screen.blit(bot_img, (x,y))
car_rect = pygame.Rect(x, y, 125, 175)
bot_rect = pygame.Rect(bot1x, bot1y, 175, 200)
#game loop
while(crash==False):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_LEFT:
x_speed = -.9
print("Moving Left")
if event.key == K_RIGHT:
x_speed = .9
print("Moving Right")
if event.type == pygame.KEYUP:
if event.key == K_LEFT:
x_speed = 0
if event.key == K_RIGHT:
x_speed= 0
if event.type == pygame.QUIT:
crash = True
bot1y += .5
# Move car
x += x_speed
if car_rect.colliderect(bot_rect):
print("collision deceted")
#blit images to screen
screen.blit(bg_img, [0, 0])
#spawn car
car(x,y)
bot(bot1x, bot1y)
#flip game display
pygame.display.flip()
#end game
pygame.quit()
quit()
I expect the game to output "Collision detected" when the two objects touch eachother.
Thanks,
Lachlan

Pygame obstacles not being generated more than once

So right now I am learning pygame and I'm using sentdex's tutorials. On I believe his 6th pygame tutorial he showed us how to generate more than just one block. I added the code, but it didin't work. I don't understand why it didn't work? Could you please tell me what I'm doing wrong and how to fix it?
Here's the code:
import pygame
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
window_width = 800
window_height = 600
gameDisplay = pygame.display.set_mode((window_width,window_height))
pygame.display.set_caption('MyFirstGame')
carImg = pygame.image.load("racecar.png")
clock = pygame.time.Clock()
def blocks(block_x, block_y, block_width, block_height, color):
pygame.draw.rect(gameDisplay, color, [block_x, block_y, block_width, block_height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit
quit()
gameExit = True
if event.key == pygame.K_c:
gameLoop()
print("User has decided to play again")
def gameLoop():
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# Defining variables to draw blocks
block_x = random.randrange(0, window_width)
block_y = -600
block_speed = 7
block_width = 100
block_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car_x_change += -5
if event.key == pygame.K_RIGHT:
car_x_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
car_x += car_x_change
gameDisplay.fill(white)
# blocks((block_x,block_y,[block_width,block_height,black))
blocks(block_x, block_y, block_width, block_height, black)
block_y += block_speed
gameDisplay.blit(carImg, (car_x,car_y))
if car_x >= window_width:
gameExit = True
crash()
if car_x <= 0:
gameExit = True
crash()
if car_y > window_height:
block_y = 0 - block_height
block_x = random.randrange(0,window_width-block_width)
pygame.display.update()
clock.tick(30)
gameLoop()
pygame.quit
quit()
One pair block_x, block_y can't be use to draw many blocks.
You have to create list with pairs (x,y) for all blocks which you want to draw. You have to use for loops to create blocks (pairs (x,y)), to move them, and to draw them.
BTW: running gameloop() inside crash() create recursion which is not prefered method.
My version with more information in comments # changed
import pygame
import random
# changed: better organized code
# --- constants --- (UPPERCASE_NAMES)
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# --- functions --- (lowercase_names)
def blocks(points, width, height, color):
# changed: use `for` to draw all blocks
for x, y in points:
pygame.draw.rect(display, color, [x, y, width, height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
# changed: return `True/False` insted of executing gameloop()
# because it was not good idea
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
return True # True = quit
if event.key == pygame.K_c:
print("User has decided to play again")
return False # false = continue
def gameloop():
# --- objects ---
car_image = pygame.image.load("racecar.png")
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# BTW: you could use `pygame.Rect` to keep position and size
# car_rect = car_image.get_rect(x=350, y=450)
# Defining variables to draw blocks
block_speed = 7
block_width = 100
block_height = 100
# changed: create list with points x,y
pairs = []
for _ in range(10):
x = random.randrange(0, WINDOW_WIDTH)
y = -block_height
pairs.append( (x, y) )
# --- mainloop ---
clock = pygame.time.Clock()
gameExit = False
while not gameExit:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car_x_change -= 5
elif event.key == pygame.K_RIGHT:
car_x_change += 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
car_x_change += 5 # changed: wrong variable, use +=
elif event.key == pygame.K_RIGHT:
car_x_change -= 5 # changed: wrong variable, use -=
# --- updates ---
# changed: all moves before draws
# move car
car_x += car_x_change
# changed: one `if` for both crashes (`car_x`)
if car_x < 0 or car_x >= WINDOW_WIDTH:
# changed: use value from crash to set gameExit
# and to move car to start position
gameExit = crash()
if not gameExit:
car_x = 350
car_y = 400
# changed: use `for` to move all points
# and to check if they need new random place
# move blocks
moved_pairs = []
for x, y in pairs:
y += block_speed
if y > WINDOW_HEIGHT:
y = -block_height
x = random.randrange(0, WINDOW_WIDTH - block_width)
moved_pairs.append( (x, y) )
pairs = moved_pairs
# --- draws ---
# changed: all draws after moves
display.fill(WHITE)
blocks(pairs, block_width, block_height, BLACK)
display.blit(car_image, (car_x, car_y))
pygame.display.update()
# --- FPS ---
clock.tick(30)
# --- main ---
pygame.init()
display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('MyFirstGame')
gameloop()
pygame.quit() # changed: forgot ()

How to get coordinates of image in pygame

I just started learning Pygame and I'm doing a little game (school project), where using mouse I can click on the image and drag it. There are a lot of images, so my question is how I can identify what image is chosen. Thank you!
Here are some code:
def Transformation(element):
element = pygame.transform.scale(element,(50,75))
fire = pygame.image.load("ElementIcon/fire.png").convert_alpha()
Transformation(fire)
fire.set_colorkey(BLACK)
fire_rect = fire.get_rect()
earth = pygame.image.load("ElementIcon/earth.png").convert_alpha()
Transformation(earth)
earth.set_colorkey(BLACK)
earth_rect = earth.get_rect()
while not done:
screen.fill(WHITE)
#Update the screen with drawings
screen.blit(fire,(408,450))
screen.blit(earth,(419, 350))
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
print("User quits the game :(")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
print("Game stopped early by user :( ")
if event.type == pygame.MOUSEBUTTONDOWN:
print mouse_pos
print fire_rect
if fire_rect.collidepoint(mouse_pos):
print "over fire"
if earth_rect.collidepoint(mouse_pos):
print "mama"
When I try to print fire_rect I get <0,0,62,75>
Have a play with this code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
clock = pygame.time.Clock()
FPS = 60
class MovableImage(pygame.Surface):
def __init__(self, image, xpos=0, ypos=0):
self.image = image
self.xpos = xpos
self.ypos = ypos
self.width = image.get_width()
self.height = image.get_height()
self.selected = False
self.rect = pygame.Rect(xpos, ypos, image.get_width(), image.get_height())
def move(self, move):
self.xpos += move[0]
self.ypos += move[1]
self.rect = pygame.Rect(self.xpos, self.ypos, self.width, self.height)
def Transformation(element):
element = pygame.transform.scale(element,(50,75))
def init():
global ImageList
fire = pygame.Surface((50,50))
fire.fill((255,0,0))
#fire = pygame.image.load("ElementIcon/fire.png").convert_alpha()
#Transformation(fire)
#fire.set_colorkey(BLACK)
#fire_rect = fire.get_rect()
earth = pygame.Surface((50,50))
earth.fill((255,255,0))
#earth = pygame.image.load("ElementIcon/earth.png").convert_alpha()
#Transformation(earth)
#earth.set_colorkey(BLACK)
#earth_rect = earth.get_rect()
fire_obj = MovableImage(fire, 408, 450)
earth_obj = MovableImage(earth, 419,350)
ImageList =[]
ImageList.append(fire_obj)
ImageList.append(earth_obj)
def run():
global done
done = False
while not done:
check_events()
update()
clock.tick(60)
def check_events():
global done
global ImageList
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
print("User quits the game :(")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
print("Game stopped early by user :( ")
if event.type == pygame.MOUSEBUTTONDOWN:
for im in ImageList:
if im.rect.collidepoint(mouse_pos):
im.selected = not im.selected
if event.type == pygame.MOUSEBUTTONUP:
for im in ImageList:
if im.rect.collidepoint(mouse_pos):
im.selected = False
if event.type == pygame.MOUSEMOTION:
for im in ImageList:
if im.rect.collidepoint(mouse_pos) and im.selected:
xmv = event.rel[0]
ymv = event.rel[1]
if event.buttons[0]:
if xmv < 0:
if im.xpos > 0:
im.move((xmv,0))
elif event.rel[0] > 0:
if im.xpos < screen.get_width():
im.move((xmv,0))
elif event.rel[1] < 0:
if im.ypos > 0:
im.move((0,ymv))
elif event.rel[1] > 0:
if im.ypos < screen.get_height():
im.move((0,ymv))
def update():
global ImageList
screen.fill((255, 255, 255)) #WHITE)
#Update the screen with drawings
for im in ImageList:
screen.blit(im.image, (im.xpos, im.ypos))
pygame.display.update()
if __name__=="__main__":
init()
run()
You can get the mouse pos and the image rect and check for collision:
pos = pygame.mouse.get_pos()
if image.rect.collidepoint(pos)
# move it
If you want to move the image with the mouse you can get the relative x/y movement with pygame.mouse.get_rel() and use that to change the image location.

Pygame animation using mutiple images overlapping/not working

import pygame
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("TEST2")
black=(0,0,0)
white=(255,255,255)
moveX,moveY=0,0
clock = pygame.time.Clock()
class Sprite:
def __init__(self,x,y):
self.x=x
self.y=y
self.width=100
self.height=110
self.i100 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite0.PNG")
self.i1 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite1.PNG")
self.i2 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite2.PNG")
self.i3 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite3.PNG")
self.i4 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite4.PNG")
self.i5 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite5.PNG")
self.i6 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite6.PNG")
self.i7 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite7.PNG")
self.i8 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite8.PNG")
self.i9 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite9.PNG")
self.i10 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite10.PNG")
self.i11 = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite11.PNG")
self.timeTarget=10
self.timeNum=0
self.currentImage=0
def update(self):
self.timeNum+=1
if(self.timeNum==self.timeTarget):
if (self.currentImage==0):
self.currentImage+=1
else:
self.currentImage=0
self.timeNum=0
self.render()
def render(self):
if (self.currentImage==0):
window.blit(self.i100, (self.x,self.y))
else:
window.blit(self.i1, (self.x,self.y))
window.blit(self.i2, (self.x,self.y))
window.blit(self.i3, (self.x,self.y))
player=Sprite(110,100)
gameLoop = True
while gameLoop:
for event in pygame.event.get():
if event.type==pygame.QUIT:
gameLoop = False
if (event.type==pygame.KEYDOWN):
if (event.key==pygame.K_LEFT):
moveX = -3
if (event.key==pygame.K_RIGHT):
moveX = 3
if (event.key==pygame.K_UP):
moveY = -3
if (event.key==pygame.K_DOWN):
moveY = 3
if (event.type==pygame.KEYUP):
if (event.key==pygame.K_LEFT):
moveX=0
if (event.key==pygame.K_RIGHT):
moveX=0
if (event.key==pygame.K_UP):
moveY=0
if (event.key==pygame.K_DOWN):
moveY=0
window.fill(black)
player.x+=moveX
player.x+=moveY
player.update()
clock.tick(50)
pygame.display.flip()
pygame.quit()
What im doing is trying to animate 11 photos into an animation with pygame. this code works but when I run it the pictures seem to almost overlap. I did window.blit for the first few images and put them under else? I feel like I rendered them wrong. also I must add im really bad at picking up what people are trying to say and best learn from examples. Thanks!
BTW: your code could look like this:
I use my images in example but there are still lines with your images.
I use timer to change images.
You can press space to pause and escape to exit.
etc.
import pygame
#----------------------------------------------------------------------
class Sprite:
def __init__(self, x, y, curren_time):
self.rect = pygame.Rect(x, y, 100, 110)
self.images = []
#for x in range(12):
for x in range(1,4):
img = pygame.image.load("ball" + str(x) +".png")
#img = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST2.0/Sprite" + str(x) +".PNG")
self.images.append( img )
self.current_image = 0
self.time_num = 100 # miliseconds
self.time_target = curren_time + self.time_num
def update(self, curren_time):
if curren_time >= self.time_target:
self.time_target = curren_time + self.time_num
self.current_image += 1
if self.current_image == len(self.images):
self.current_image = 0
def render(self, window):
window.blit(self.images[self.current_image], self.rect)
#----------------------------------------------------------------------
# CONSTANS - uppercase
BLACK = (0 ,0 ,0 )
WHITE = (255,255,255)
#----------------------------------------------------------------------
# MAIN
def main():
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("TEST2")
move_x, move_y = 0, 0
clock = pygame.time.Clock()
curren_time = pygame.time.get_ticks()
player = Sprite(110,100, curren_time)
font = pygame.font.SysFont(None, 150)
pause_text = font.render("PAUSE", 1, WHITE)
pause_rect = pause_text.get_rect( center = window.get_rect().center ) # center text on screen
# mainloop
state_game = True
state_pause = False
while state_game:
curren_time = pygame.time.get_ticks()
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
state_game = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
state_game = False
elif event.key == pygame.K_SPACE:
state_pause = not state_pause
if event.key == pygame.K_LEFT:
move_x = -3
elif event.key == pygame.K_RIGHT:
move_x = 3
elif event.key == pygame.K_UP:
move_y = -3
elif event.key == pygame.K_DOWN:
move_y = 3
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
move_x = 0
elif event.key in (pygame.K_UP, pygame.K_DOWN):
move_y = 0
# moves
if not state_pause:
player.rect.x += move_x
player.rect.y += move_y
player.update(curren_time)
# draws
window.fill(BLACK)
player.render(window)
if state_pause:
window.blit(pause_text, pause_rect)
pygame.display.flip()
# FPS
clock.tick(50)
# the end
pygame.quit()
#----------------------------------------------------------------------
if __name__ == '__main__':
main()
ball1.png
ball2.png
ball3.png
By putting all those window.blit(...) calls one after another, you are drawing those three frames on top of each other. Even if your computer lagged for a second between each call, you still wouldn't see them individually because they all can't appear until pygame.display.flip() is called.
You should store the images in a list, and keep a counter like currentFrame that loops from 0 to number_of_frames-1 (or len(frames)-1). Then each frame of the game you do something like this:
class Player:
...
def draw(window):
window.blit(self.frames[self.currentFrame])

Categories

Resources