我正在为本教程用 C++ 编写一条小“蛇”。面临这样的问题,我需要使用kbhit()和getch()阅读用户输入。这些功能在库conio.h中,而 Linux 中没有。另外,我试过这个,但它没有帮助,程序刚刚停止,当你输入时什么也没发生。
我想知道如何在 Linux 上实现它,或者这个库有什么替代品吗?
编码:
#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();
}
}
从用户javad m得到关于英语 StackOverflow 的答案