我的代码不起作用,我不明白为什么,我正在使用模块PYGAME,我想在按下键时动画(三张图像)" 取值&#34 ;.我的代码是这样的:
import pygame, sys
from pygame.locals import *
from time import *
pygame.init()
ventana = pygame.display.set_mode((400,300))
pygame.display.set_caption("Hi!")
imgA = pygame.image.load("IMG/fan_azul.png")
imgB = pygame.image.load("IMG/fan_naranja.png")
imgC = pygame.image.load("IMG/fan_rojo.png")
listaImg = [imgA,imgB,imgC]
POS,aux,e = 0,1,0
picture = listaImg[POS]
posX,posY,fondo = 200,100,(50,50,50)
while True:
ventana.fill(fondo)
#ventana.blit(picture,(posX,posY))
for evento in pygame.event.get():
if evento.type == QUIT:
pygame.quit()
sys.exit()
elif evento.type == KEYDOWN:
if evento.key == K_s:
for e in range(0,3):
POS = e
picture = listaImg[POS]
ventana.blit(picture,(posX,posY))
print "TIEMPO MEDIDO: "+str(POS)
pygame.time.wait(1000)
pygame.display.update()
答案 0 :(得分:0)
重要的是要避免将内部循环挂起来处理事件和其他绘图到框架。请记住,您通常会尝试每秒30到60帧,而您的K_s处理程序自身需要3秒。保持句柄事件,更新状态和绘制屏幕部分。要做动画,我通常会这样做。
import pygame, sys
from pygame.locals import *
import time
pygame.init()
ventana = pygame.display.set_mode((400,300))
pygame.display.set_caption("Hi!")
FONDO = (50,50,50)
class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, position, filenames):
pygame.sprite.Sprite.__init__(self)
self.images = [pygame.image.load(filename) for filename in filenames]
self.delay = 0
self.start = 0
self.rect = pygame.Rect(position, (0, 0))
self._set_image(0)
def _set_image(self, image_num):
self.image_num = image_num
self.image = self.images[self.image_num]
self.rect.size = self.image.get_rect().size
def show(self, group, delay=1.0):
group.add(self)
self.delay = delay
self._set_image(0)
self.start = time.time()
def update(self):
if self.alive() and time.time() - self.start > self.delay:
if self.image_num + 1 < len(self.images):
self._set_image(self.image_num + 1)
else:
self.kill()
fan = AnimatedSprite((200, 10), ["IMG/fan_azul.png",
"IMG/fan_naranja.png",
"IMG/fan_rojo.png"])
animation = pygame.sprite.Group()
while True:
# Handle Events
for evento in pygame.event.get():
if evento.type == QUIT:
pygame.quit()
sys.exit()
elif evento.type == KEYDOWN:
if evento.key == K_s:
fan.show(animation)
# Update State
animation.update()
# Draw
ventana.fill(FONDO)
animation.draw(ventana)
pygame.display.update()