酷代码 AI
菜单
服务商
DeepSeek字节豆包
更多选项

简单 C++ 射击小游戏代码实现

以下是一个简单的 C++ 射击小游戏示例,在这个游戏中,玩家控制一个射击者在一个一维的地图上移动并射击目标。 ```cpp #include <iostream> #include <cstdlib> #include <ctime> // 定义地图大小 const int MAP_SIZE = 20; // 打印地图 void printMap(int shooterPos, int targetPos) { for (int i = 0; i < MAP_SIZE; ++i) { if (i == shooterPos) { std::cout << 'S'; } else if (i == targetPos) { std::cout << 'T'; } else { std::cout << '.'; } } std::cout << std::endl; } // 移动射击者 int moveShooter(int shooterPos, char direction) { if (direction == 'a' && shooterPos > 0) { --shooterPos; } else if (direction == 'd' && shooterPos < MAP_SIZE - 1) { ++shooterPos; } return shooterPos; } // 射击操作 bool shoot(int shooterPos, int targetPos) { return shooterPos == targetPos; } int main() { srand(static_cast<unsigned int>(time(nullptr))); // 随机初始化目标位置 int targetPos = rand() % MAP_SIZE; // 初始化射击者位置 int shooterPos = 0; char input; bool gameOver = false; while (!gameOver) { // 打印地图 printMap(shooterPos, targetPos); // 获取用户输入 std::cout << "输入 'a' 向左移动,'d' 向右移动,'s' 射击:"; std::cin >> input; if (input == 'a' || input == 'd') { // 移动射击者 shooterPos = moveShooter(shooterPos, input); } else if (input == 's') { // 射击 if (shoot(shooterPos, targetPos)) { std::cout << "击中目标!游戏结束。" << std::endl; gameOver = true; } else { std::cout << "未击中目标,请继续。" << std::endl; } } } return 0; } ``` ### 代码说明: 1. **地图定义**:`MAP_SIZE` 定义了地图的大小,在这个游戏中是一维的。 2. **打印地图**:`printMap` 函数用于打印当前地图的状态,`S` 表示射击者,`T` 表示目标,`.` 表示空白位置。 3. **移动射击者**:`moveShooter` 函数根据用户输入的方向(`a` 向左,`d` 向右)移动射击者的位置。 4. **射击操作**:`shoot` 函数判断射击者是否击中目标。 5. **主函数**:在 `main` 函数中,初始化目标和射击者的位置,然后进入游戏循环,根据用户输入进行移动或射击操作,直到击中目标游戏结束。 ######[AI问答 | 759点数解答 | 2026-07-04 13:22:28]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]