如何使用curses按下最后一个箭头键?

发布于 2024-09-18 01:17:44 字数 572 浏览 7 评论 0原文

我正在编写一个 使用诅咒的 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(因此蛇在用完箭头按下时会停止),而我实际上希望它检索最后按下的箭头键。

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

I'm writing a Python snake game using curses, but am having some trouble controlling the snake, my current code for controlling the snake is placed inside the main loop and looks like this:

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)

However the code seems to treat the keys pressed as a que (so the snake will stop when it runs out of arrow-presses), whereas I actually want it to retrieve the last arrow key that was pressed.

How can I retrieve the last arrow key that was pressed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人生戏 2024-09-25 01:17:44

设置 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)

Set 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文