c++ - 移动在 C++ 控制台游戏中不起作用(使用 _kbhit 和 _getch)
问题描述
我使用二维数组作为坐标。为目标创建和显示带有随机坐标的板正在工作。但是,运动不起作用(它是 w、a、s、d)。我使用功能_kbhit
和_getch
运动。
#include <iostream>
#include <conio.h>
#include <ctime>
using namespace std;
bool gameOver = false;
char board[10][10];
int goalX, goalY, playerX, playerY, score;
enum eDirection
{
STOP = 0, LEFT, RIGHT, UP, DOWN
};
eDirection direction;
void Setup();
void Show(int playerX, int playerY, int goalX, int goalY, enum eDirection);
void Input(int playerX, int playerY, int goalX, int goalY, enum eDirection);
void Logic(int playerX,
int playerY,
int goalX,
int goalY,
enum eDirection,
int score);
int main()
{
Setup();
while (!gameOver)
{
system("cls");
Show(playerX, playerY, goalX, goalY, direction);
Input(playerX, playerY, goalX, goalY, direction);
Logic(playerX, playerY, goalX, goalY, direction, score);
}
}
void Setup()
{
direction = STOP;
score = 0;
playerX = 5;
playerY = 5;
srand(time(NULL));
goalX = rand() % 10;
goalY = rand() % 10;
}
void Show(int playerX, int playerY, int goalX, int goalY, enum eDirection)
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
board[i][j] = '*';
board[playerX][playerY] = 'P';
board[goalX][goalY] = 'G';
cout << board[i][j];
}
cout << endl;
}
}
void Input(int playerX, int playerY, int goalX, int goalY, enum eDirection)
{
if (_kbhit())
{
switch (_getch())
{
case 'w':
direction = UP;
break;
case 'a':
direction = LEFT;
break;
case 's':
direction = DOWN;
break;
case 'd':
direction = RIGHT;
break;
}
}
}
void Logic(int playerX,
int playerY,
int goalX,
int goalY,
enum eDirection,
int score)
{
switch (direction)
{
case UP:
playerY++;
break;
case LEFT:
playerX--;
break;
case DOWN:
playerY--;
break;
case RIGHT:
playerX++;
break;
}
if (playerX == goalX && playerY == goalY)
{
score += 10;
goalX = rand() % 10;
goalY = rand() % 10;
}
}
解决方案
推荐阅读
- ios - 使用 VIPER 架构时 UI 视图控制器未更新
- javascript - 将 Discord 机器人推送到 Heroku 时出错:推送被拒绝,无法编译 Node.js 应用程序
- selenium - 抓取数据时如何在 selenium 中使用代理来避免 IP 限制?
- python - 将一个列表的元素除以另一个列表的元素
- excel - Email scraper from a list of urls
- react-native - 在反应本机中使用导航抽屉反应备忘录
- matplotlib - Matplotlib 的线宽问题
- amazon-web-services - 更新存储在 AWS S3 中的数据的架构/数据的策略
- javascript - 单击页面时更改导航中的文本颜色不起作用
- html - CSS 网格自动展开