Search code examples
c++inputgetchkbhit

How can I use kbhit() and getch() on Linux? C++


I'm wrinig a simple snake game on C++. But I have a problem: I need to use kbhit() and getch() for read what the user enters. For use it I need conio.h but there're no this library on Linux. I tryed use this, but there're have a trouble: code is compiling but I can't use program, it just stoping.

So how can I use kbhit() and getch()? Or is there any alternative for it?

My code:

#include <iostream>
#include <conio.h>
using namespace std;

bool GameOver;
const int height = 20;
const int width = 20;
int x, y, fruit_x, fruit_y, score;
enum eDirection { STOP, RIGHT, LEFT, UP, DOWN };
eDirection dir;

void setup() {
    GameOver = false;
    dir = STOP;
    x = width / 2 - 1;
    y = height / 2 - 1;
    fruit_x = rand() % width;
    fruit_y = rand() % height;
    score = 0;
}

void draw() {
    system("clear");

    for (int i = 0; i < width; i++)
    {
        cout << "#";
    }
    cout << endl;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            if (j == 0 || j == width - 1)
        {
            cout << "#";
        }
        if (i == y && j == x)
        {
            cout << "0";
        }
        else if (i == fruit_y && j == fruit_x)
        {
            cout << "F";
        }
        else
        {
            cout << " ";
        }
    }
    cout << endl;
    }

    for (int i = 0; i < width; i++)
    {
        cout << "#";
    }
    cout << endl;
}

void input() {
    if (_kbhit)
    {
        switch(getch())
    {
        case 'a':
            dir = LEFT;
            break;
        case 'd':
            dir = RIGHT;
            break;
        case 'w':
            dir = UP;
            break;
        case 's':
            dir = DOWN;
            break;
        case 'x':
            GameOver = true;
            break;
        }
    }
}

void logic() {
    switch(dir)
    {
    case LEFT:
        x--;
        break;
    case RIGHT:
        x++;
        break;
    case UP:
        y--;
        break;
    case DOWN:
        y++;
        break;
    }
}


int main() {
    setup();
    while(!GameOver)
    {
        draw();
        input();
        logic();
    }

}

Solution

  • As zoelabbb said in this link,

    Step 1 : Open terminal sudo apt-get update

    sudo apt-get upgrade
    sudo apt-get install git
    git clone https://github.com/zoelabbb/conio.h.git
    cd conio.h
    

    Step 2 :

    sudo cp conio.h /usr/include/
    

    or (step 2)

    In GUI, using open-as-administrator pakage:

    Copy file conio.h --> !! copy file not folder !!
    Go to /usr/include/
    Right click on folder /usr/include/
    Choose Open as Administrator
    Paste file conio.h
    

    Finaly after step 1 and step 2 you can use #include <conio.h> in your code.