gpt4 book ai didi

python curses while循环和超时

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:32 25 4
gpt4 key购买 nike

我很难理解 window.timeout() 函数。更具体地说,我正在玩 python 中的“贪吃蛇”游戏:

s = curses.initscr()
curses.curs_set(0)
w = curses.newwin()
w.timeout(100)

while True:
move snake until it hits the wall

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

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函数设置名为 _delay 的窗口属性,该属性在 getch function 内起作用, 最终 passed to a timed-wait function如果有数据要读取,它会提前返回。

关于python curses while循环和超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48360550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com