[OC]C++迷宫游戏模板

展示


代码+注释

#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)。你可以根据需要调整迷宫的大小和结构。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值