0

我正在学习 python 和 pygame。在我的代码中找到问题时,我有点挣扎。当我按住一个键并同时按下另一个键,然后以我按下它们的相同顺序放开它们时,有时会使我的小角色朝相反的方向向后移动。

这是我正在努力解决的代码:

while running:
for event in pygame.event.get():
    if event.type == KEYDOWN:
        keystate = pygame.key.get_pressed()
    if event.type == pygame.QUIT: # if user clicked close
        running = False # flag done to exit this loop


# all game logic / controls should go below this comment
    elif event.type == KEYDOWN:
        if keystate[K_SPACE]:
            print ('pressed space')
            player.move_up = True
        elif keystate[K_RIGHT]:
            print ('pressed right')
            player.move_right = True
        elif keystate[K_LEFT]:
            print ('pressed left')
            player.move_left = True
    elif event.type == KEYUP:
        if keystate[K_SPACE]:
            print ('released space')
            player.move_up = False
        elif keystate[K_RIGHT]:
            print ('released right')
            player.move_right = False
        elif keystate[K_LEFT]:
            print ('released left')
            player.move_left = False


if player.move_up:
    player.pos[1] -= 3
if player.move_up == False:
    if player.pos[1] < ground_level:
        player.pos[1] +=3
if player.move_right:
    player.pos[0] += 5
if player.move_left:
    player.pos[0] -= 5`

到目前为止,我还没有任何实际的物理知识,他只是飞来飞去。但没关系,我只是想解决我已经遇到的问题。

4

1 回答 1

1

您永远不会更新事件keystate的价值KEYUPKEYDOWN因此,无论何时触发最后一个事件,它仍然具有任何值。

要解决此问题,请更改此...

if event.type == KEYDOWN:
    keystate = pygame.key.get_pressed()

对此:

if event.type in (KEYDOWN, KEYUP):
    keystate = pygame.key.get_pressed()
于 2013-01-07T06:53:46.073 回答