0

I'm super new to C++ and was wanting to add arrow key functionality to my snake game. I've been scouring the Internet trying to find a way to do this without "conio.h" as I am using Linux. How would I go about doing this and can I get some example code?

Thank you!

AdrianRonquillo
  • 89
  • 1
  • 2
  • 7

2 Answers2

2

Try out:

#include <ncurses.h>

int main(){
    int ch;

    initscr();
    raw();
    keypad(stdscr, TRUE);
    noecho();


    while ((ch = getch()) != '#') {
        switch(ch) {
            case KEY_UP: printw("\nUp");
            break;

            case KEY_DOWN: printw("\nDown");
            break;

            case KEY_LEFT: printw("\nLeft");
            break;

            case KEY_RIGHT: printw("\nRight");
            break;

            default: printw("%c", ch);
        }
    }
    refresh();
    getch();
    endwin();
}
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
esantix
  • 323
  • 5
  • 26
  • 2
    Notes: This answer would benefit from a bit of explanation. Some embedded comments would do. You may have to use your friendly neighborhood package manager to download and install ncurses. – user4581301 May 16 '20 at 03:13
1

You'd be best off using ncurses - just google for some tutorials to get yourself started. It can do simple things like clear the screen, get the terminal dimensions, position the cursor at arbitrary coordinates, write text in arbitrary colours, and yes - read characters from the keyboard without waiting for enter to be pressed. Enjoy your project!

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252