I am writing a snake game in C using the ncurses
library, where the screen updates itself every second. As those who have played the game will know, if the user enters various keys or holds down a key for long, there should be no 'buffered' key presses which get stored. In other words, if I hold down w
(the up key) and stdin
receives a sequence of 20 w
s, and subsequently enter a d
(the right key), I expect the snake to immediately move to the right, and ignore the buffered w
s.
I am trying to achieve this using the ncurses
function getch()
, but for some reason I am achieving the undesired effect which I have just described; namely that any long key presses are being stored and processed first, before considering the last key pressed, as this MWE will illustrate:
#include <stdio.h>
#include <unistd.h>
#include <ncurses.h>
int main(){
char c = 'a';
initscr();
cbreak();
noecho();
for(;;){
fflush(stdin);
timeout(500);
c = getch();
sleep(1);
printw("%c", c);
}
return 0;
}
Is there any way I can modify this code so that getch()
ignores any buffered text? The fflush()
right before doesn't seem to be helping.