External Exam Download Resources Web Applications Games Recycle Bin

Running sprite animation

dude.py

import pygame
pygame.init()
from player_class import objPlayer
dude = objPlayer()
white = (255, 255, 255) #RGB
screen = pygame.display.set_mode((400, 300))
clock = pygame.time.Clock() #allows us to throttle frame rate
done = False

while not done:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      done = True
      
  keys = pygame.key.get_pressed()
  if keys[pygame.K_LEFT]:
    dude.left()
  if keys[pygame.K_RIGHT]:
    dude.right()
    
  screen.fill(white)
  sprite = pygame.image.load(dude.draw_sprite()) #("image.png")
  screen.blit(sprite, dude.draw_location()) #sprite, (x, y)   
  pygame.display.flip()
  clock.tick(60) #caps at 60fps
  
pygame.quit()

player_classs.py

class objPlayer:
  def __init__(player, x=0, y=0, speed=2): #create event
    player.x = x
    player.y = y
    player.speed = speed
    player.sprites = ["run1.png","run2.png","run3.png","run4.png",
                      "run5.png","run6.png","run7.png"]
    player.sprite_counter = 0
    
  def draw_location(player):
    return(player.x, player.y) #for screen.blit()

  def draw_sprite(player):
    current_sprite = player.sprites[player.sprite_counter]
    return(current_sprite) #for pygame.image.load()
    
  def left(player):
    player.x = player.x - player.speed
    player.sprite_counter += 1
    player.sprite_counter = player.sprite_counter % len(player.sprites)

  def right(player):
    player.x = player.x + player.speed
    player.sprite_counter += 1
    player.sprite_counter = player.sprite_counter % len(player.sprites)

save running sprites below to same project folder as python file, and launch dude.py:




run.zip
(all sprites in a single file download)
run1.png run2.png run3.png run4.png run5.png run6.png run7.png