1

I am trying to make a terminal snake game in C++ in macOSX. How do I detect which arrow key is pressed?

I tried to do this with getch() of ncurses.h but this is not solving the problem. No output is being detected.

#define KEY_UP    72
#define KEY_LEFT  75
#define KEY_RIGHT 77
#define KEY_DOWN  80

void Input()
{
    int c = 0;
    switch ((c = getch()))
    {
    case KEY_UP:
        cout << endl<< "Up" << endl; //key up
        break;
    case KEY_DOWN:
        cout << endl<< "Down" << endl; // key down
        break;
    case KEY_LEFT:
        cout << endl<< "Left" << endl; // key left
        break;
    case KEY_RIGHT:
        cout << endl<< "Right" << endl; // key right
        break;
    default:
        break;
    }
}
Saurav Pathak
  • 796
  • 11
  • 32
  • Does this solve your issue? https://stackoverflow.com/a/1586164/2602718 – scohe001 Sep 10 '19 at 16:36
  • No, It does not. – Saurav Pathak Sep 10 '19 at 16:56
  • How are you calling `Input()`? Is it in a loop that waits until there's some input to be read? Have you tried just `cout << getch()` to see if it's even reading your arrow press at all? – scohe001 Sep 10 '19 at 20:16
  • Okay! I am able to detect key press. But the program waits for press when used getch() . How can I keep executing the program and only take input when pressed instead of waiting for it? – Saurav Pathak Sep 24 '19 at 10:41
  • 1
    From [here](http://www.cs.ukzn.ac.za/~hughm/os/notes/ncurses.html): "*To disable the buffering of typed characters by the TTY driver and get a character-at-a-time input, you need to call* `cbreak();`" – scohe001 Sep 24 '19 at 11:44
  • Oops, looks like I actually meant this: "*Usually a call to* `getch()` *waits until a key is hit. If you have called* `nodelay(stdscr, TRUE)`, *then* `getch()` *will work in a non-blocking manner -- it will return* `ERR` *if the key input is not ready. This is usually useful for writing game-like programs, where the promptness of user response matters.*" That site also gives examples on all of this. I'd highly advise reading through it if you're new to ncurses! – scohe001 Sep 24 '19 at 15:11

0 Answers0