Pygame keyboard animation not working correctly - python

import pygame
class Sprite:
def __init__(self, x, y, curren_time):
self.rect = pygame.Rect(x, y, 100, 110)
self.images = []
#Tells pygame the image list that you want to stitch together
for x in range(10):
img = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST6/Cernunnos" + str(x) +".PNG")
#Append the image to each other to create the animation effect
self.images.append( img )
self.current_image = 0
self.time_num = 100
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)
#Colors
black = (0,0,0)
white = (255,255,255)
def main():
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Sprites")
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 )
#Adding how many places the image moves when using the key function
state_game = True
state_pause = False
#So while True
while state_game:
curren_time = pygame.time.get_ticks()
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_y = 3
elif event.key == pygame.K_UP:
move_x = -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
if not state_pause:
player.rect.x += move_x
player.rect.y += move_y
player.update(curren_time)
#Fills the window with a color
window.fill(black)
player.render(window)
if state_pause:
window.blit(pause_text,pause_rect)
pygame.display.flip()
clock.tick(50)
pygame.quit()
if __name__ == '__main__':
main()
#Code constructed by furas
So the problem is whenever I hit the right key the animation slides off the screen on the left. the animation does not stop when you take your finger off the key. I have searched for the problem myself and am unable to find any problems. Please if you see something that may be causing the problem let me know. Thanks! (Up key = Down, Down key = Down, Right key = Left, Left key = Left)

Your problem is that you have move_x and move_y swapped for K_RIGHT and K_UP.
elif event.key == pygame.K_RIGHT:
move_y = 3
elif event.key == pygame.K_UP:
move_x = -3
Should be:
elif event.key == pygame.K_RIGHT:
move_x = 3
elif event.key == pygame.K_UP:
move_y = -3

Related

How to make enemies fall at random on pygame?

I want enemies to randomly fall from the sky on my game and I do not know how to do this.
I was using this youtube video: Falling Objects in Pygame.
import pygame, random
pygame.init()
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
time = pygame.time.Clock()
bg_color1 = (135, 142, 142) # MAIN BG COLOR
bg_color2 = (255, 0, 0) # red
bg_color3 = (255, 255, 0) # yellow
UFO = pygame.image.load('ufo.png')
bg_pic = pygame.image.load('Letsgo.jpg')
clock = pygame.time.Clock()
playerImg = pygame.image.load('enemy.png')
playerX = random.randrange(0, screen_width)
playerY = -50
playerX_change = 0
player_speed = 5
def player(x, y):
window.blit(playerImg, (playerX, playerY))
crashed = False
rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)
menu = True
playerY = playerY + player_speed
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
def ufo(x, y):
window.blit(UFO, (x, y))
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu = False
window.fill((0, 0, 0))
time.tick(30)
window.blit(bg_pic, (0, 0))
pygame.display.update()
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0
while not crashed:
x += x_change
if x < 0:
x = 0
elif x > screen_width - UFO.get_width():
x = screen_width - UFO.get_width()
y += y_change
if y < 0:
y = 0
elif y > screen_height - UFO.get_height():
y = screen_height - UFO.get_height()
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
##
x += x_change
y += y_change
##
window.fill(bg_color1)
ufo(x, y)
player(playerX, playerY)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
So the code that was supposed to make the image fall was this
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
Move the following code:
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
To here so it can be within the game loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10

Player movement

I wrote this simple code that draws and then lets you move a rectangle, but even after I change the coordinates of the rectangle by calling the move_player_x_ function, it doesn't move at all. I don't understand why. I came here looking for clarification and a detailed solution to my problem.
Here's the code:
import pygame
white = (255, 255, 255)
black = (0, 0, 0)
class Game():
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
def __init__(self):
pass
def fill_screen(self, color):
self.color = color
self.screen.fill(self.color)
def update_method(self):
pygame.display.update()
game = Game()
class Player(pygame.sprite.Sprite):
lead_x = game.width/2
lead_y = game.height/2
lead_x_change = 0
lead_y_change = 0
velocity = 0.2
block_size = 10
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def move_player_x_left(self):
self.lead_x_change += -self.velocity
def move_player_x_right(self):
self.lead_x_change += self.velocity
def move_player_y_up(self):
self.lead_y_change += -self.velocity
def move_player_y_down(self):
self.lead_y_change += self.velocity
def draw_player(self):
pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])
def key_up_x_stop(self):
self.lead_x = 0
def key_up_y_stop(self):
self.lead_y = 0
def constant_x_movement(self):
self.lead_x += self.lead_x_change
def constant_y_movement(self):
self.lead_y += self.lead_y_change
player = Player()
exitGame = False
while not exitGame:
game.fill_screen(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.move_player_y_up()
if event.key == pygame.K_s:
player.move_player_y_down()
if event.key == pygame.K_a:
player.move_player_x_left()
if event.key == pygame.K_d:
player.move_player_x_right()
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
player.key_up_y_stop()
if event.key == pygame.K_a or event.key == pygame.K_d:
player.key_up_x_stop()
player.constant_x_movement()
player.constant_y_movement()
player.draw_player()
game.update_method()
pygame.quit()
quit()
The code in the event loop is not indented correctly. Here's a corrected version:
while not exitGame:
game.fill_screen(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.move_player_y_up()
if event.key == pygame.K_s:
player.move_player_y_down()
if event.key == pygame.K_a:
player.move_player_x_left()
if event.key == pygame.K_d:
player.move_player_x_right()
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
player.key_up_y_stop()
if event.key == pygame.K_a or event.key == pygame.K_d:
player.key_up_x_stop()
Also, in the ...stop methods, you have to set lead_x_change and lead_y_change to 0 not lead_x and lead_y.
def key_up_x_stop(self):
self.lead_x_change = 0
def key_up_y_stop(self):
self.lead_y_change = 0
I edited your code, i added a function in the player object move_player with local booleans bUp,bDown,bLeft,bRight. If python had enumerations, it would be so much better. Any how, on event KEY DOWN and KEY UP, they toggle these booleans in the player. after the input is calculated and these booleans are toggled/set, it called move_player() in player object that checks its booleans and sets a while loop while one is true and adds velocity in the respected location and redraws player.
Here the source i got for you...
import pygame
white = (255, 255, 255)
black = (0, 0, 0)
class Game():
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
def __init__(self):
pass
def fill_screen(self, color):
self.color = color
self.screen.fill(self.color)
def update_method(self):
pygame.display.update()
class Player(pygame.sprite.Sprite):
lead_x = 800/2
lead_y = 600/2
velocity = 0.002
block_size = 10
bUp = false
bDown = false
bLeft = false
bRight = false
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def draw_player(self):
pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])
def move_player(self):
while bLeft:
self.lead_x += -self.velocity
self.draw_player()
while bRight:
self.lead_x += self.velocity
self.draw_player()
while bUp:
self.lead_y += -self.velocity
self.draw_player()
while bDown:
self.lead_y += self.velocity
self.draw_player()
game = Game()
player = Player()
exitGame = False
while not exitGame:
game.fill_screen(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.bUp = true
if event.key == pygame.K_s:
player.bDown = true
if event.key == pygame.K_d:
player.bRight = true
if event.key == pygame.K_a:
player.bLeft = true
elif event.type == pygame.KEYUP:
if event.key == pygame.K_w:
player.bUp = false
if event.key == pygame.K_s:
player.bDown = false
if event.key == pygame.K_d:
player.bRight = false
if event.key == pygame.K_a:
player.bLeft = false
player.move_player()
game.update_method()
pygame.quit()
quit()

Python sprite not moving when key is held down

I'm working on the basics of a game right now, but for some reason I cannot get my sprite to move. I know that it's registering when I'm pressing the key down, but the sprite for some reason just stays still.
import pygame
import sys
from pygame.locals import *
import time
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("RADICAL")
screen.fill(black)
imga = pygame.image.load('coina.png')
imgb = pygame.image.load('coinb.png')
sound = pygame.mixer.Sound('coin.mp3')
FPS = 80
imgx = 10
imgy = 10
pixMove = 10
steps = 0
x1 = 0
y1 = 0
keystate = pygame.key.get_pressed()
GameOver = False
while not GameOver:
screen.fill(white)
points = (steps)
font = pygame.font.SysFont(None, 30)
text = font.render('Score: '+str(points), True, black)
screen.blit(text, (0,0))
if steps % 2 == 0:
screen.blit(imga, (imgx, imgy))
else:
screen.blit(imgb, (imgx, imgy))
for event in pygame.event.get():
print event
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if keystate[pygame.K_UP]:
y1 -= pixMove
elif keystate[pygame.K_DOWN]:
y1 += pixMove
elif keystate[pygame.K_LEFT]:
x1 -= pixMove
elif keystate[pygame.K_RIGHT]:
x1 += pixMove
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x1 = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y1 = 0
steps +=1
if event.type == K_SPACE:
sound.play()
time.sleep(1)
sound.stop()
pygame.display.update()
fpsTime.tick(FPS)
Generally you blit() images on to the screen (pygame.display.set_mode()), for the changes to to reflect on the screen we call pygame.display.update(), In your case the game never comes the statement, which is out of while loop.

Increasing Pygame Image size after collision?

So I'm just learning how to work with classes and getting them to work between each different class. I'm trying to design a game where the user moves around and picks up food and each time the user picks up a piece of food the size of the character increases. I've done something similar before but now that there are classes involved I seem to have a hard time finding which class this should be part of. I added within the sprite update method that if it collides with a cherry then the size of the player should increase by 5 pixels each time. using the code :
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
Each time the game runs the player size doesn't change and for some reason the game no longer ends after the player has eaten a certain amount of cherries so I was just wondering if I was using a wrong method of changing the size of the player perhaps there may be an easier way to do so? Heres the rest of the code incase it helps at all.
import pygame, glob, random, time
from pygame.locals import *
from LabelClass import *
# CONSTANTS
WIDTH = 400 # Window width
HEIGHT = 400 # Window height
BLACK = (0,0,0) # Colors
WHITE = (255,255,255)
BACKGR = BLACK # Background Color
FOREGR = WHITE # Foreground Color
FPS = 40 # Frames per second
pwidth = 40
pheight = 40
class Food:
def __init__(self,screen,centerx,centery):
self.screen = screen
self.surface = pygame.image.load('cherry.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
class Player:
def __init__(self, screen, centerx,
centery, speed, backcolor):
self.surface = pygame.image.load('player.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
self.speed = speed
self.screen = screen
self.backcolor = backcolor
self.dir = ''
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
def move(self):
if self.dir != '':
if self.dir == 'd' and self.rect.bottom < HEIGHT:
self.rect.top += self.speed
if self.dir == 'u' and self.rect.top > 0:
self.rect.top -= self.speed
if self.dir == 'l' and self.rect.left > 0:
self.rect.left -= self.speed
if self.dir == 'r' and self.rect.right < WIDTH:
self.rect.right += self.speed
def jump(self,top,left):
self.rect.top = top
self.rect.left = left
class SpritesGame:
def __init__(self,screen):
self.screen = screen
screen.fill(BLACK)
pygame.display.update()
music_file = getRandomMusic()
pygame.mixer.music.load(music_file)
pygame.mixer.music.play(-1,0.0)
self.music = True
self.Foods = [ ]
self.Eaten = 0
for i in range(20):
self.Foods.append(
Food(self.screen,
WIDTH*random.randint(1,9)//10,
HEIGHT*random.randint(1,9)//10))
for f in self.Foods:
f.draw()
self.Player = Player(screen,WIDTH//2,HEIGHT//2,6,BLACK)
self.PickUpSound = pygame.mixer.Sound('pickup.wav')
self.PlaySound = True
self.startTime = time.clock()
self.endTime = -1
self.Won = False
def update(self):
self.screen.fill(BLACK)
pickedUp = False
for f in self.Foods[:]:
if self.Player.rect.colliderect(f.rect):
self.Foods.remove(f)
self.Foods.append(Food(self.screen,WIDTH*random.randint(1,9)//10,HEIGHT*random.randint(1,9)//10))
pickedUp = True
self.Eaten += 1
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
#self.rect.center = center
print self.Eaten
if pickedUp and self.PlaySound:
self.PickUpSound.play()
for f in self.Foods:
f.draw()
if self.Eaten == 40:
self.Won = True
self.endTime = time.clock()
self.Player.move()
self.Player.draw()
pygame.display.update()
def toggleMusic(self):
self.music = not self.music
if self.music:
pygame.mixer.music.play(-1,0.0)
else:
pygame.mixer.music.stop()
def run(self):
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYDOWN: # Keeps moving as long as key down
if event.key == K_LEFT or event.key == ord('a'):
self.Player.dir = 'l'
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = 'r'
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = 'u'
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = 'd'
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
if event.key == K_ESCAPE:
stop = True
if event.key == K_LEFT or event.key == ord('a'): # End repetition.
self.Player.dir = ''
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = ''
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = ''
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = ''
if event.key == ord('x'):
top = random.randint(0,
HEIGHT - self.Player.rect.height)
left = random.randint(0,
WIDTH - self.Player.rect.width)
self.Player.jump(top,left)
if event.key == ord('m'):
self.toggleMusic()
if event.key == ord('p'):
self.PlaySound = not self.PlaySound
mainClock.tick(FPS)
self.update()
if self.Won:
stop = True # END OF WHILE
if self.Won:
self.screen.fill(BLACK)
pygame.display.update()
msg = (str((int(self.endTime)
-int(self.startTime)))
+" seconds to finish. Hit Q.")
L2 = Label(display,WIDTH//2,HEIGHT*7//8,26,msg,WHITE,BLACK)
L2.draw()
stop = False
while not stop:
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
pygame.event.get()
pygame.mixer.music.stop()
def getRandomMusic():
mfiles = glob.glob("*.wav")
mfiles.append(glob.glob("*.mid"))
r = random.randint(0,len(mfiles)-1)
return mfiles[r]
def OpeningScreen(screen):
screen.fill(BLACK)
pygame.display.update()
L1 = Label(display,WIDTH//2,HEIGHT*7//8,26,"Hit Q to Quit, P to Play.",WHITE, BLACK)
L1.draw()
# Properly initiate pygame
pygame.init()
# pygame.key.set_repeat(INT,INT)
# Set the clock up
mainClock = pygame.time.Clock()
# Initialize Display
display = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Sprites and Sounds V06')
OpeningScreen(display)
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYUP:
if event.key == ord('p'):
game = SpritesGame(display)
game.run()
OpeningScreen(display)
if event.key == ord('q'):
stop = True
pygame.quit()
Surface.get_rect() will always return a rect starting at (0,0), and you also are modifying SpritesGame.rect. I think you should change
self.rect = self.Player.surface.get_rect()
to
self.Player.rect.inflate_ip(5, 5)

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