import pygame
negro = (0,0,0)
blanco = (255,255,255)
arriba,abajo,izq,der = False, False, False, False
exit = False
speed = 10
vx,vy = 0,0
class Balon(pygame.sprite.Sprite):
def __init__(self,imagen):
self.imagen = imagen
self.rect=self.imagen.get_rect()
self.rect.top = 300
self.rect.left = 320
def move(self,vx,vy):
self.rect.move_ip(vx,vy)
def update(self,superficie):
superficie.blit(self.imagen,self.rect)
def check_keys(event):
global vx
global vy
global abajo
global arriba
global izq
global der
global exit
if event.type == pygame.QUIT:
exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
arriba = True
vy-= speed
if event.key == pygame.K_DOWN:
abajo = True
vy+= speed
if event.key == pygame.K_RIGHT:
der = True
vx+= speed
if event.key == pygame.K_LEFT:
izq = True
vx-= speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
arriba = False
if abajo == True: vy+=speed
else: vy=0
if event.key == pygame.K_DOWN:
abajo = False
if arriba == True: vy-=speed
else: vy=0
if event.key == pygame.K_RIGHT:
der = False
if izq == True: vx-=speed
else: vx=0
if event.key == pygame.K_LEFT:
izq = False
if der == True: vx+=speed
else: vx=0
def main():
pygame.init()
screen = pygame.display.set_mode((640,480))
reloj = pygame.time.Clock()
pygame.display.set_caption("Ejemplo")
imgBalon = pygame.image.load("balon.png").convert_alpha()
fondo = pygame.image.load("fondo.png").convert_alpha()
balon = Balon(imgBalon)
while exit!= True:
for event in pygame.event.get():
check_keys(event)
screen.blit(fondo,(0,0))
balon.move(vx,vy)
balon.update(screen)
pygame.display.update()
reloj.tick(20)
pygame.quit()
main()
El código se ordeno en varias funciones, se le coloco un titulo a la ventana, se creo una clase especifica para crear el sprite y se agrego una imagen de fondo, en lugar de color sólido. La ventaja de manejar sprites, es que tenemos el rectángulo de la imagen lo que facilita mas adelante la detección de colisiones, y ademas, el movimiento se hace mas sencillo moviendo el rectángulo con move_ip().
Fuentes: ChelinTutorials, Pygame Doc

No hay comentarios:
Publicar un comentario