python 诅咒 while 循环和超时

python curses while loop and timeout

我很难理解 window.timeout() 函数。更具体地说,我正在 python:

玩 "snake" 游戏
s = curses.initscr()
curses.curs_set(0)
w = curses.newwin()
w.timeout(100)

while True:
    move snake until it hits the wall

据我所知,在这种情况下,timeout(100) 决定蛇 "moves" 的速度,即在屏幕上打印出新字符。但是,当我想修改代码以便它等到有人按下 "start" 时,我被卡住了。我写了类似的东西:

w.timeout(100)

while True:
    if w.getch() is not start: 
        stay at the initial screen
    else:
        while True:
            move the snake until it hits the wall

但是,在这种情况下,timeout(100) 似乎决定程序每次等待 w.getch() 的时间,而不是每次蛇移动之间等待的时间。另外,我注意到在第一个示例中,超时是在 while 循环之外的顶部声明的。这对我来说看起来很奇怪,因为通常如果我想暂停 while 循环,我会把 sleep() 放在 while 循环的底部。

如果你想在蛇移动之间暂停,你可以使用 napms 等待给定的毫秒数(与 sleep 不同,它不会干扰屏幕更新)。将 w.timeout 设置为 100(毫秒)可能太长了。如果您不关心读取功能键,您可以使用 nodelayw.getch 设置为非阻塞,依靠 napms 来减慢循环。

关于后续评论:在 ncurses 中,如果有数据要读取,wtimeout function sets a property of the window named _delay, which acts within the getch function, ultimately passed to a timed-wait function 会提前 return。