8

我正在使用 curses 编写 Python 蛇游戏,但在控制蛇时遇到了一些麻烦,我当前用于控制蛇的代码放在主循环内,如下所示:

while True:
    char = screen.getch()
    if char == 113: exit()  # q
    elif char == curses.KEY_RIGHT: snake.update(RIGHT)
    elif char == curses.KEY_LEFT: snake.update(LEFT)
    elif char == curses.KEY_UP: snake.update(UP)
    elif char == curses.KEY_DOWN: snake.update(DOWN)
    else snake.update()
    time.sleep(0.1)

然而,代码似乎将按下的键视为一个 que(所以当它用完箭头按下时蛇会停止),而我实际上希望它检索最后按下的箭头键。

如何检索最后按下的箭头键?

4

1 回答 1

3

设置screen.nodelay(1)

screen.nodelay(1)
while True:
    char = screen.getch()
    if char == 113: break  # q
    elif char == curses.KEY_RIGHT: snake.update(RIGHT)
    elif char == curses.KEY_LEFT: snake.update(LEFT)
    elif char == curses.KEY_UP: snake.update(UP)
    elif char == curses.KEY_DOWN: snake.update(DOWN)
    else: snake.update()
    time.sleep(0.1)
于 2010-09-06T21:18:45.557 回答