Search code examples
pythonwhile-looptimeoutcurses

python curses while loop and timeout


I am having a hard time understanding the window.timeout() function. To be more specific, I am toying with a "snake" game in python:

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

while True:
    move snake until it hits the wall

I understand that in this case, timeout(100) determines how fast the snake "moves", i.e. printing out new characters on the screen. However, I got stuck when I want to amend the code so that it waits until someone press "start". I wrote something like:

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

However, in this case, the timeout(100) seems to govern how long each time the program waits for w.getch(), not how long to wait between each time the snake moves. Also, I notice that in the first example, the timeout is declared at the top, outside the while loop. This looks weird to me because normally if I want to pause a while loop, I would put sleep() at the bottom inside the while loop.


Solution

  • If you want to pause between snake moves, you could use napms to wait a given number of milliseconds (and unlike sleep, does not interfere with screen updates). Setting w.timeout to 100 (milliseconds) is probably too long. If you're not concerned with reading function-keys, you could use nodelay to set the w.getch to non-blocking, relying on the napms to slow down the loop.

    Regarding the followup comment: in ncurses, the wtimeout function sets a property of the window named _delay, which acts within the getch function, ultimately passed to a timed-wait function that would return early if there's data to be read.