views:

41

answers:

1

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?

+1  A: 

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)
Josh
I've discovered that `curses.halfdelay()` can cause some weird bugs, `screen.nodelay()` + `time.sleep()` seems to work better.
Josh