Animación Pygame

Si creamos un personaje para nuestro vídeo juego podemos darle movilidad creando los fotogramas en bucle.

Para ello, debemos cargar una lista de imágenes.

import pygame
pygame.init()

walkRight = [pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/RP1.png'),
             pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/RP2.png'),
             pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/RP3.png'),
             pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/RP4.png'),
             pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/RP5.png'),
             pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/RP6.png')]

walkLeft = [pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/LP1.png'),
            pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/LP2.png'),
            pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/LP3.png'),
            pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/LP4.png'),
            pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/LP5.png'),
            pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/LP6.png')]
char = pygame.image.load('E:/NUEVO 2020/PYTHON/pygame/Anima2/STATIC.png')

A continuación seguimos como siempre abriendo una ventana, definiendo posición inicial de variables, activando un sonido de fondo y abriendo las variables.

#Ventana y título
ventana = pygame.display.set_mode((1200,700)) 
pygame.display.set_caption('Multifruta')
fondo =pygame.image.load("E:/NUEVO 2020/PYTHON/pygame/fondonubes.png").convert()
clock=pygame.time.Clock()

#------------Listas--------------
x = 200
y = 500
vel = 7

isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0

soundBg = pygame.mixer.music.load("E:/NUEVO 2020/PYTHON/pygame/main.mid")
pygame.mixer.music.play()

#/////////////////Bucle del juego/////////////////
gameOver=False
while not gameOver:
    
    clock.tick(18)
    pygame.time.delay(20)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameOver=True

Ahora damos valores a las variables cuando pulsamos el teclado.

#Ventana y título
ventana = pygame.display.set_mode((1200,700)) 
pygame.display.set_caption('Multifruta')
fondo =pygame.image.load("E:/NUEVO 2020/PYTHON/pygame/fondonubes.png").convert()
clock=pygame.time.Clock()

#------------Listas--------------
x = 200
y = 500
vel = 7

isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0

soundBg = pygame.mixer.music.load("E:/NUEVO 2020/PYTHON/pygame/main.mid")
pygame.mixer.music.play()

#/////////////////Bucle del juego/////////////////
gameOver=False
while not gameOver:
    
    clock.tick(18)
    pygame.time.delay(20)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameOver=True

Si pulsamos izquierda la variable left es TRUE y la variable vel=-7 para desplazar a la izquierda.

Limitamos el movimiento en la lógica

    #------------ LOGICA -------------------
    x += vel 
    
    if x < 0:
        x=0
    if x>1140:
        x=1140

Y ahora viene lo realmente novedoso: cuando left es TRUE vamos a imprimir por pantalla la lista de imágenes walkLeft en bucle mientras la tecla esté pulsada.

    #-------------FONDO---------------------
    ventana.blit(fondo, [0,0])

    #------------ DIBUJO ------------------
    if walkCount + 1 >= 18: 
        walkCount = 0
    if left:  
        ventana.blit(walkLeft[walkCount // 3], (x, y)) 

        walkCount += 1
    elif right: 
        ventana.blit(walkRight[walkCount // 3], (x, y)) 
        walkCount += 1
    else: 
        ventana.blit(char, (x, y))

    pygame.display.flip()
 
pygame.quit()

Cierro el juego aplicando condicionales a derecha y parado.

Juande Marín

Profesor de Marketing digital, divulgador de inteligencia artificial y neuroeducación. Especializado en posicionamiento en buscadores y diseño web. Autor de varios libros relacionados con el comercio electrónico y el marketing digital (McGraw Hill, Paraninfo,…) Juande2marin

Material didáctico

Descubre un material moderno y adaptado a ciclos formativos.