我是一个 C++ 菜鸟编码蛇游戏。整个程序完美地绘制了棋盘、水果和蛇头,但是我似乎无法使用键盘敲击功能来改变蛇头坐标。当通过输入函数获取蛇移动的键盘敲击时,运行程序时似乎 if(kbhit) 评估为假,我的错误是什么,我怎样才能让蛇头移动?
谢谢。
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <conio.h>
using namespace std;
int X, Y, fruitX, fruitY;
enum eDir { STOP = 1, UP = 2, DOWN = 3, RIGHT = 4, LEFT = 5 }; //declare variables
eDir direction;
const int height = 20;
const int width = 20;
int board[height][width];
bool gameOver;
void setup()
{
gameOver = false;
srand(time(NULL)); // initilize game set up
fruitX = (rand() % width);
fruitY = (rand() % height);
X = height / 2;
Y = width / 2;
direction = STOP;
int board[height][width];
};
void draw()
{
system("cls");
for (int i = 0; i < width + 2; i++)
cout << '#';
cout << endl;
for (int i = 0; i < height; i++) //loop through matrix to draw board
{
for (int j = 0; j < width; j++)
{
if (j == 0)
cout << '#';
if (i == Y && j == X) // draw snake head
cout << 'T';
else if (i == fruitY && j == fruitX) // draw fruit
cout << 'F';
else
cout << ' ';
if (j == width - 1)
cout << '#';
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
cout << '#';
cout << endl;
};
void input()
{
if (_kbhit())
{
switch (_getch())
{
case 'w':
direction = UP;
break;
case 's':
direction = DOWN;
break;
case 'a':
direction = LEFT;
break;
case 'd':
direction = RIGHT;
break;
default:
break;
}
}
};
void logic()
{
switch (direction)
{
case UP:
Y--;
break;
case DOWN:
Y++;
break;
case LEFT:
X--;
break;
case RIGHT:
X++;
break;
default:
break;
}
};
int main()
{
setup();
while (!gameOver)
{
draw();
input();
logic();
return 0;
}
};