为什么我的键盘命中是评估错误的
Why my keyboard hit is evaluating false
我是C 编码蛇游戏的noob编码。整个程序都完美地吸引了板,水果和蛇头,但是我似乎无法使用键盘命中功能使蛇头坐标更改。当通过输入函数以获得蛇运动的键盘笔触时,似乎IF(KBHIT(在运行程序时会评估false,我的错误是什么,我该如何使蛇头移动?
谢谢。
#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;
}
};
对于一件事,您在游戏循环中进行 return 0;
,它仅在一次迭代后杀死程序,我认为您不打算。
我使用类似的方法制作了蛇,我的看起来像这样:
bool play = true;
while(play) {
while (_kbhit) {
switch (_getch) {
case 'w':
//code
break;
case 's':
//code
break;
case 'a':
//code
break;
case 'd':
//code
break;
}
}
}
该方法对我有用,我认为唯一的区别是我使用了一段时间循环,而不是if。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- MSVC 在不知道类型的情况下评估上下文(和错误)
- 为什么我的键盘命中是评估错误的
- 表达式未评估为常数两个级别的constexpr函数(编译器错误?)
- 中毒的无效引用和短路表达评估错误或UB
- VS 中的 C++ 17 会导致 C++14 中不存在的变量(重新)评估错误
- gcc 在这个概念定义中是否错误地评估了 std::d eclval ?
- 通过指向成员的指针对嵌套访问进行编译时评估期间出现 GCC 错误
- 未评估上下文中的默认模板参数和 lambda:错误还是功能?
- 为什么我会因Valgrind遇到内存错误?(C ,抽象语法树评估)
- std :: initializer_list:错误c2064:项未评估为0参数的函数
- 测验程序总是评估答案是错误的
- 死亡测试时函数调用的评估错误
- 镶嵌评估着色器链接错误
- 编写C++模板以评估表达式指针错误
- "Cannot call member function ... without object"在未评估的上下文中 - GCC 错误?
- 使用堆栈评估后缀表达式时出现分段错误
- 带有指针的map:错误的值评估
- Clang vs. GCC:未评估上下文中的错误会中断 SFINAE