0

I'm writing a game currently in ncurses and I have a ship that is controlled by the user and an 'automated' that moves slowly down the lines to kill you. However, I'm using a while loop containing everything and each time I use getch() the loop pauses and waits for input, meaning that the enemy only moves after input from the user.

        c=getch(); //causes a pause until a button is pressed before the next action

        if(c==97) //if a is pressed, move position of '*' left
        {
            dir=-1;

        }

        if(c==100) //if d is pressed, move position of '*' right
        {
            dir=1;

        }
Jamstain
  • 1
  • 1
  • 1
  • Possible duplicate of [Non-blocking console input C++](http://stackoverflow.com/questions/6171132/non-blocking-console-input-c) – d9ngle May 18 '17 at 15:46
  • The traditional name for this function is kbhit(). Non-blacking detection of keyboard hits, usually for video games purposes. – Malcolm McLean May 18 '17 at 15:53
  • @d9ngle: Not really as that is about how to do nonblocking input *without* using curses. With curses, it is much easier. – Chris Dodd May 18 '17 at 16:04

2 Answers2

2

Since you're using curses, just call nodelay or halfdelay or timeout to make getch non-blocking, or have it return after a short wait if no key has been pressed. See the inopts(3ncurses) man page.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
0

Use poll on the input file descriptor (0, aka STDIN_FILENO) to determine whether there's input pending before you call getch. Normally you would poll with a nonzero timeout and then the call doubles as the timing for your game's loop so it runs at a fixed tick rate you control rather than as many iterations per second as the cpu/system load allow.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • If you're using `poll()` or `select()`, then you should also be using non-blocking I/O... – Attie May 18 '17 at 16:08
  • @Attie: Not necessarily, and almost certainly not with curses. – R.. GitHub STOP HELPING ICE May 19 '17 at 02:11
  • @R interesting, could you explain? If you `read()` in the wrong place or one too many times then wouldn't your application still block when using curses? Or do you propose to never read more than one byte per `read()`, and never `read()` more than once per `poll()`/`select()`? – Attie May 19 '17 at 09:28
  • Having re-read the manpage, I suspect that @Chris's answer is more appropriate (`getch()` appears to be window-aware), and `no-delay` mode should be employed to prevent blocking. – Attie May 19 '17 at 09:32