C++ WASD 控制方块移动小游戏实现 - 简单易懂代码示例
#include
void clearScreen() { std::cout << "\033[2J\033[1;1H"; }
int main() { const int width = 10; const int height = 10;
int playerX = width / 2;
int playerY = height / 2;
bool gameOver = false;
while (!gameOver) {
// 清空屏幕
clearScreen();
// 绘制地图
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x == playerX && y == playerY) {
std::cout << "O";
} else {
std::cout << ".";
}
}
std::cout << std::endl;
}
// 获取玩家输入
char input = _getch();
// 处理玩家输入
switch (input) {
case 'w':
playerY--;
break;
case 'a':
playerX--;
break;
case 's':
playerY++;
break;
case 'd':
playerX++;
break;
case 'q':
gameOver = true;
break;
}
}
return 0;
}
在这个示例中,游戏地图的大小为 10x10,使用字符 O 表示玩家位置,使用字符 . 表示其他位置。玩家可以通过按下 wasd 键移动方块的位置。按下 q 键可以退出游戏。
原文地址: https://www.cveoy.top/t/topic/pKcb 著作权归作者所有。请勿转载和采集!