0

I am building a simple game using the ncurses library, and am using keyboard input to move my character. I am currently reading this with getch(), but this is sub-optimal for two reasons:

  • The key does not send continuously when pressed, only a short period afterwards.

  • When continuously sending, is isn't always recognised by the system.

Is there an alternative to getch() which I am able to use?

Sample code demonstrating the effect:

#include <stdio.h>
#include <windows.h>
#include "curses.h"

void setup_screen();

int main() {
    setup_screen();

    while (true) {
        fprintf(stderr, "%d\n", getch());

        Sleep(20);
    }

    endwin();
    return 0;
}

void setup_screen() {
    initscr();
    noecho();
    curs_set( 0 );
    timeout( 0 );
    keypad( stdscr, TRUE );
    clear();
}

Sample output:

...

260
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
260
260
-1
260
260
-1
260
-1
260
260
-1
Dimpl
  • 935
  • 1
  • 10
  • 24
  • 1
    the pause duration and the repetition rate for a keyboard key is part of the terminal driver, not part of 'curses' BTW: suggest you use `#include ` (notice the leading 'n') and notice that it is a system header file, not a user defined file, so use `<` and `>` not double quotes – user3629249 Apr 17 '16 at 07:04
  • the function: `fprintf()` takes a (relatively) long time to execute. Suggest changing the output to stdout and using: `putc_unlocked()` or even better, double buffer the input, say using buffer sizes of say 512 bytes. Because there is no way that writing to the terminal can keep up, integer by integer with the keyboard key repeat rate. – user3629249 Apr 17 '16 at 07:07
  • 1
    note: `-1` means the function: `getch()` returned EOF. so the code should be checking for the value and not trying to print it. – user3629249 Apr 17 '16 at 07:09
  • 1
    here is a key excerpt from the man page for `getch()` "The getch, wgetch, mvgetch and mvwgetch, routines read a character from the window. In no-delay mode, if no input is waiting, the value ERR is returned. In delay mode, the program waits until the system passes text through to the program. Depending on the setting of cbreak, this is after one character (cbreak mode), or after the first newline (nocbreak mode). In half-delay mode, the program waits until a character is typed or the specified timeout has been reached." Suggest setting the 'cbreak; mode and the 'half-delay' mode – user3629249 Apr 17 '16 at 07:14
  • Actually `getch()` returns `ERR` (which, like `EOF`, is usually `-1`). The rest of @user3629249's comments would comprise a useful answer. – Thomas Dickey Apr 17 '16 at 10:40

0 Answers0