展示
代码+注释
#include <bits/stdc++.h>
#include <conio.h>
using namespace std;
// 迷宫地图,0代表可通过的路,1代表墙壁
int maze[100][100] = {
{ 0, 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 0, 1 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 1, 0 },
{ 0, 1, 0, 0, 0, 0 }
};
// 迷宫大小
const int rows = 7;
const int cols = 6;
// 玩家当前位置
int playerRow = 0;
int playerCol = 0;
// 绘制迷宫地图
void drawMaze() {
for (int i = 0; i < cols+2; i++) {
cout << "#";
}
cout << endl;
for (int i = 0; i < rows; i++) {
cout << "#";
for (int j = 0; j < cols; j++) {
if (i == playerRow && j == playerCol) {
cout << "P"; // 绘制玩家位置
} else if (maze[i][j] == 0) {
cout << " "; // 绘制可通过的路
} else {
cout << "#"; // 绘制墙壁
}
}
cout << "#" << endl;
}
for (int i = 0; i < cols+2; i++) {
cout << "#";
}
cout << endl;
}
// 移动玩家
void movePlayer(char move) {
int newRow = playerRow;
int newCol = playerCol;
switch (move) {
case 'w': // 向上移动
newRow--;
break;
case 's': // 向下移动
newRow++;
break;
case 'a': // 向左移动
newCol--;
break;
case 'd': // 向右移动
newCol++;
break;
}
// 检查新位置是否合法
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && maze[newRow][newCol] == 0) {
playerRow = newRow;
playerCol = newCol;
}
}
int main() {
char move;
while (true) {
system("cls"); // 清屏
drawMaze();
if (playerRow == rows - 1 && playerCol == cols - 1) {
cout << "你赢了!" << endl;
break;
}
move = getch(); // 获取键盘输入
movePlayer(move);
}
return 0;
}
总结
这个迷宫游戏通过数组来表示迷宫的结构,玩家可以通过键盘输入w、a、s、d来移动,直到到达迷宫的终点。在该示例中,玩家的起始位置是(0, 0),终点位置是(6, 5)。你可以根据需要调整迷宫的大小和结构。