题目描述:你需要设计一个控制台地图游戏,玩
家需要通过控制台输入来移动自己的角色,并在地图上寻找宝藏。玩家可以通过键盘控制小球向上、向下、向左或向右移动。当小球移动到宝藏处时,游戏结束,输出恭喜信息。
要求:
以下内容引用自GPT:
好的,请参考下面的代码,这是基于C++语言实现。
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0)); // 初始化随机数种子
int rows, cols;
cout << "请输入地图的行数:";
cin >> rows;
cout << "请输入地图的列数:";
cin >> cols;
// 初始化地图
char map[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
map[i][j] = ' ';
}
}
// 随机生成宝藏位置和角色起始位置
int treasureRow = rand() % rows;
int treasureCol = rand() % cols;
int playerRow = rand() % rows;
int playerCol = rand() % cols;
while (treasureRow == playerRow && treasureCol == playerCol) {
playerRow = rand() % rows;
playerCol = rand() % cols;
}
// 在地图上标出宝藏位置和角色起始位置
map[treasureRow][treasureCol] = 'x';
map[playerRow][playerCol] = 'O';
// 游戏主循环
while (true) {
// 输出当前地图
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << setw(2) << map[i][j] << ' ';
}
cout << endl;
}
// 判断游戏是否结束
if (playerRow == treasureRow && playerCol == treasureCol) {
cout << "恭喜你,你找到了宝藏!" << endl;
break;
}
// 获取玩家输入
char input;
cout << "请输入你的下一步操作(w、s、a、d):";
cin >> input;
// 根据玩家输入更新玩家位置
switch (input) {
case 'w': playerRow--; break;
case 's': playerRow++; break;
case 'a': playerCol--; break;
case 'd': playerCol++; break;
}
// 判断玩家移动是否越界
if (playerRow < 0) playerRow = 0;
if (playerRow >= rows) playerRow = rows - 1;
if (playerCol < 0) playerCol = 0;
if (playerCol >= cols) playerCol = cols - 1;
// 更新地图
map[playerRow][playerCol] = 'O';
// 清屏
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
// 游戏结束,输出最终地图
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << setw(2) << map[i][j] << ' ';
}
cout << endl;
}
return 0;
}
在此代码中,通过输入行数和列数来自定义地图的大小。然后通过srand
函数来初始化随机数种子,并通过rand
函数来随机生成宝藏位置和角色起始位置,并避免宝藏和角色重叠。游戏进行时,玩家输入通过判断来移动角色,并通过屏幕清洗来达到不断输出地图的效果。