0

I am writing code for a roguelike game, and this portion of the code uses getch() to take a user input to direct the character as to where to move next. It is my understanding that getch() will pause the program until it receives an input from the user, but my code doesn't pause when it reaches the line. Here is the code

uint32_t pc_next_pos(dungeon *d)
  {
    char comm;
    comm = getch();
    command_move(d, comm);
  }

The entire program compiles correctly, it is just that instead of pausing the program to let me move my character, it continues to go until the program terminates once all the monsters in the game die. That code is not included as it doesn't play a role in this method.

Am I doing something wrong in this method that doesn't allow getch() to pause the program, or am I misunderstanding what getch() does?

Zebs
  • 27
  • 1
  • 1
  • 10

2 Answers2

1

getch() can be blocking or non-blocking (or even blocking with a timeout), depending on input options. You want blocking; you're getting non-blocking. The problem isn't here, in this function, but somewhere in your curses initialization code (not shown) -- you're probably calling something like nodelay(stdscr, TRUE), or the aforementioned timeout(), shortly after initscr(). If not, you may need to add something like nodelay(stdscr, FALSE), although that should be the default behavior.

You should also read up on halfdelay() and cbreak() (normally on the same man page as nodelay() and timeout()).

William McBrine
  • 2,166
  • 11
  • 7
  • I feel silly. The problem came because I actually commented out initscr() for some reason. Thanks to your answer, I looked back and saw that was the issue. Now it all works just fine. Thank you! – Zebs Mar 07 '17 at 19:57
0

You can change the getch function behavior calling timeout:

for man 3 timeout:

The timeout and wtimeout routines set blocking or non-blocking read for a given window. If delay is negative, blocking read is used (i.e., waits indefinitely for input). If delay is zero, then non-blocking read is used (i.e., read returns ERR if no input is waiting). If delay is positive, then read blocks for delay milliseconds, and returns ERR if there is still no input. Hence, these routines provide the same functionality as nodelay, plus the additional capability of being able to block for only delay milliseconds (where delay is positive).

uint32_t pc_next_pos(dungeon *d)
  {
    char comm;
    /* set getch blocking */
    timeout(-1);
    comm = getch();
    command_move(d, comm);
    return ....
  }
Mathieu
  • 8,840
  • 7
  • 32
  • 45