我正在用 C++ 编写一个简单的蛇游戏。但我有一个问题:我需要使用kbhit()
和getch()
读取用户输入的内容。我需要使用它,conio.h
但 Linux 上没有这个库。我试过用这个,但有一个问题:代码正在编译,但我不能使用程序,它只是停止。
那么我该如何使用kbhit()
andgetch()
呢?或者有什么替代方案吗?
我的代码:
#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();
}
}