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:
我正在使用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)
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.
然而,代码似乎将按下的键视为一个que(所以当它用完箭头时蛇会停止),而我实际上希望它检索被按下的最后一个箭头键。
How can I retrieve the last arrow key that was pressed?
如何检索按下的最后一个箭头键?
1 个解决方案
#1
3
Set screen.nodelay(1)
:
设置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)
#1
3
Set screen.nodelay(1)
:
设置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)