【发布时间】:2018-04-22 18:34:54
【问题描述】:
我是一个 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;
}
};
【问题讨论】:
-
你是如何确定测试评估为假的?你添加了日志吗?您说它似乎评估为假,但没有告诉我们您实际观察到的内容,只是您从中得出的(可能不正确的)结论。这就像告诉你的医生,“医生,我的可的松水平似乎很低”。如果你不告诉他是什么症状导致你这样想,他怎么能弄清楚你有什么问题?
-
另外,您的代码没有多大意义。你一直在清理屏幕——任何人都应该怎么看?
-
You
return 0;fromwhileloop inmain,这意味着它在程序结束前恰好运行了 1 次 -
@KillzoneKid 这听起来像是对我的回答
-
@Yann 我没有读过这个问题,只是格式化并注意到了。
标签: c++ if-statement getch kbhit