Как я могу использовать kbhit () и getch () на Linux? C ++ - PullRequest
0 голосов
/ 28 апреля 2020

Я пишу простую игру со змеями на C ++. Но у меня есть проблема: мне нужно использовать kbhit() и getch() для чтения того, что вводит пользователь. Для его использования мне нужно conio.h, но на Linux этой библиотеки нет. Я попытался использовать this , но есть проблема: код компилируется, но я не могу использовать программу, он просто останавливается.

Так как же я могу использовать kbhit() и getch()? Или есть альтернатива?

Мой код:

#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();
    }

}
...