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?
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)