我不能讓我的精靈Ball類獲取KEYDOWN/KEYUP事件的值從主循環中的「else」語句更新自己。下面是主循環代碼和球類:如何讓這個精靈類與我的主循環(Pygame)
class Ball():
def __init__(self):
global ball
ball = pygame.sprite.Sprite()
ball.image = pygame.image.load('red_ball.png').convert()
ball.rect = ball.image.get_rect()
ball.image.set_colorkey((white))
def event_handle(self, event):
x,y = 285, 430
m_x, m_y = 0,0
if event.type == KEYDOWN:
if event.key == K_a:
m_x = -4
elif event.key == K_d:
m_x = +4
if event.type == KEYUP:
if event.key == K_a:
m_x = 0
elif event.key == K_d:
m_x = 0
x+= m_x
y+= m_y
if x > 640:
x = 0
if x < 0:
x = 640
def update(self):
screen.blit(ball.image,(x,y))
pygame.display.update()
def main():
m_x, m_y = 0,0
while True:
ball = Ball()
screen.blit(background, (0,0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
else:
ball.event_handle(event)
ball.update()
pygame.display.update()
..... * facepalm * – 15H 2012-01-11 13:20:59