反复按键时,蛇移动得更快

2024-04-27 00:49:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python和诅咒库创建了蛇游戏。但是我在程序中发现了错误。当反复按这个键时,蛇移动得更快。这是代码的一部分

# standard initialization
s = curses.initscr()

curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)

curses.noecho()
curses.curs_set(0)
sh, sw = 30, 60
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
w.nodelay(1)

#Snake moving loop

while True:

next_key = w.getch()

#Check if user is pressing the key or not, or pressing the opposite direction key
if (next_key == -1):
    key = key
elif (key == curses.KEY_DOWN and next_key == curses.KEY_UP) or (key == curses.KEY_UP and next_key == curses.KEY_DOWN):
    key = key
elif (key == curses.KEY_LEFT and next_key == curses.KEY_RIGHT) or (key == curses.KEY_RIGHT and next_key == curses.KEY_LEFT):
    key = key
else:
    key = next_key

#Current location of the head
new_head = [snake[0][0], snake[0][1]]

 #moving up, down,left,right according to the key
if key == curses.KEY_DOWN:
    new_head[0] += 1
if key == curses.KEY_UP:
    new_head[0] -= 1
if key == curses.KEY_LEFT:
    new_head[1] -= 1
if key == curses.KEY_RIGHT:
    new_head[1] += 1

snake.insert(0, new_head)

我认为这是因为getch()在按下键时被多次调用,并且在不等待超时的情况下进入移动循环。你知道吗

我试过了诅咒.napms(100),诅咒.cbreak(1),诅咒。半延迟(1) 什么都没用。你知道吗


Tags: orandthekeyrightnewifleft
1条回答
网友
1楼 · 发布于 2024-04-27 00:49:39

调用s.nodelay(0)将nodelay mode设置为0(这意味着false,因此存在延迟),并且它位于错误的窗口对象(s而不是w

您在w窗口实例上调用getch,因此我认为您必须调用w.nodelay(1)(以启用节点模式)。你知道吗

您还必须修改输入循环,以识别如果getch()返回-1,则表示没有按下任何键。(这将是通常的结果,因为按一个键需要相当一小部分的秒,但是这个循环现在每秒将运行数百次甚至数千次。)

编辑:

我想我对你的问题有点误解了。上面的代码很好,但并不能解决核心问题。您可能希望在输入循环中添加一个恒定的延迟,以便更多的按键不允许更多的操作。你知道吗

也许是这样的:

while True:
    keypress = w.getch()
    if keypress != -1:
        # process keypress
    sleep(100 milliseconds)

相关问题 更多 >