跳到正文

休闲·娱乐

走迷宫2.1.1版本2正式1修改1

lvshanxing约 13 分钟
原文
文章信息与版本

文章信息

发布
2026年7月9日
收录
2026年7月13日
更新
2026年8月21日
篇幅
约 13 分钟

版本

  1. v1当前

·自动模式仍然闪烁

C++
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <queue>
#include <windows.h>
#include "Keyboard.h" 
using namespace std;
void colour(int x){SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), x);}
const int ROWS = 20;
const int COLS = 20;

void gotoxy(int x, int y) {
    COORD pos = {x, y};
    HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hOutput, pos);
}
// 地图数组
string map[ROWS][COLS];
// 访问标记,用于生成算法
bool visited[ROWS][COLS];

// 方向数组:上、右、下、左
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};

// 初始化地图为全墙壁
void initmap() {
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            map[i][j] = '#';
            visited[i][j] = false;
        }
    }
}

// 检查坐标是否合法且未访问
bool isValid(int x, int y) {
    return (x >= 1 && x < ROWS - 1 && y >= 1 && y < COLS - 1 && !visited[x][y]);
}

// 递归回溯法生成迷宫 (DFS)
// 注意:此算法通常用于奇数尺寸网格。对于20x20,我们主要生成内部连通性。
void generateDFS(int x, int y) {
    visited[x][y] = true;
    map[x][y] = ' '; // 标记为路

    // 创建方向索引 0-3
    int dirs[] = {0, 1, 2, 3};
    
    // 随机打乱方向顺序,确保每次生成的迷宫不同
    for (int i = 3; i > 0; --i) {
        int j = rand() % (i + 1);
        int temp = dirs[i];
        dirs[i] = dirs[j];
        dirs[j] = temp;
    }

    // 尝试四个方向
    for (int k = 0; k < 4; ++k) {
        int d = dirs[k];
        // 步长为2,以保留墙壁
        int nx = x + dx[d] * 2;
        int ny = y + dy[d] * 2;

        if (isValid(nx, ny)) {
            // 打通当前点与新点之间的墙壁
            int midX = x + dx[d];
            int midY = y + dy[d];
            map[midX][midY] = ' ';
            
            // 递归进入新点
            generateDFS(nx, ny);
        }
    }
}

// 由于20x20是偶数,DFS步长为2可能无法覆盖所有奇数坐标点,
// 且终点(18,19)是(偶,奇),DFS从(1,1)(奇,奇)出发无法直接到达(偶,奇)点。
// 因此需要后期修复,确保起点和终点连通。
void fixStartAndEnd() {
    // 1. 确保起点 (1,1) 是路
    map[1][1] = 'S';
    
    // 2. 确保终点 (18,19) 是路
    map[18][18] = 'T';
    
    // 3. 强制打通终点到最近的主干路径的连接
    // 终点(18,19)的邻居是 (17,19) 和 (18,18)。
    // (17,19) 是 (奇,奇),大概率已被DFS访问并打通。
    // 如果 (17,19) 是墙,说明该区域未被覆盖,我们需要手动连接。
    
    // 策略:从终点向起点方向“挖”一条路,直到碰到一个已经是路的格子。
    int cx = 18, cy = 18;
    while (true) {
        // 如果当前格子已经是路(且不是终点本身初始化的那个),说明连上了
        if (map[cx][cy] == " " && !(cx==18 && cy==18)) {
            break;
        }
        
        // 否则,将当前格子设为路
        map[cx][cy] = ' ';
        
        // 随机选择向上或向左移动(朝向起点的大致方向)
        // 避免越界
        bool canUp = (cx > 1);
        bool canLeft = (cy > 1);
        
        if (canUp && canLeft) {
            if (rand() % 2 == 0) cx--;
            else cy--;
        } else if (canUp) {
            cx--;
        } else if (canLeft) {
            cy--;
        } else {
            break; // 安全退出,防止死循环
        }
    }
}
int x=1,y=1,step;
struct node{
	int x,y;
};
int dir[4][2]{{1,0},{-1,0},{0,1},{0,-1}};
void BFS_map(){
	int vis[20][20];
	for(int i=0;i<20;i++) for(int j=0;j<20;j++) vis[i][j]=-1;
	queue<node> q;
	vis[x][y]=0;
	q.push({x,y});
	while(!q.empty()){
		for(int i=0;i<20;i++){
			for(int j=0;j<20;j++){
				if(vis[i][j]!=-1){
					colour(2);
					if(vis[i][j]<10) cout<<0<<vis[i][j];
					else{
						if(vis[i][j]<100) cout<<vis[i][j];
						else{
							colour(4);
							if(vis[i][j]-100<10){
								cout<<0<<vis[i][j]-100;
							}else cout<<vis[i][j]-100;
						}
					}
					colour(7);
				}else{
					cout<<map[i][j]<<map[i][j];
				}
			}
			cout<<endl;
		}
		auto now=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			int tx=now.x+dir[i][0];
			int ty=now.y+dir[i][1];
			if(map[tx][ty]!="#"&&vis[tx][ty]==-1){
				vis[tx][ty]=vis[now.x][now.y]+1;
				q.push({tx,ty});
			}
		}
		Sleep(50);
		system("cls"); 
	}
	for(int i=0;i<20;i++){
		for(int j=0;j<20;j++){
			if(vis[i][j]!=-1){
				colour(2);
				if(vis[i][j]<10) cout<<0<<vis[i][j];
				else{
					if(vis[i][j]<100) cout<<vis[i][j];
					else{
						colour(4);
						if(vis[i][j]-100<10){
							cout<<0<<vis[i][j]-100;
						}else cout<<vis[i][j]-100;
					}
				}
				colour(7);
			}else{
				cout<<map[i][j]<<map[i][j];
			}
		}
		cout<<endl;
	}
	cout<<"step : "<<vis[18][18];
}
int main() {
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cursorInfo;
    GetConsoleCursorInfo(hConsole, &cursorInfo);
    cursorInfo.bVisible = false; // true显示, false隐藏
    SetConsoleCursorInfo(hConsole, &cursorInfo);
    srand((unsigned)time(NULL));
	initmap();
	generateDFS(1, 1);
	for(int i=1; i<ROWS-1; i+=2) {
		for(int j=1; j<COLS-1; j+=2) {
		    if(!visited[i][j]) {
		        generateDFS(i, j);
		    }
		}
	}
	fixStartAndEnd();
	map[18][18] = 'T';
	while(1){
		x=1,y=1,step=0;
		system("cls");
		string mode;
		cout<<"mode : (1)程序自动 (2)手动 (3)退出\n >> ";
		cin>>mode;
		system("cls"); 
		//------------------------------------
		if(mode=="2"){
			srand((unsigned)time(NULL));
		    initmap();
		    generateDFS(1, 1);
		    for(int i=1; i<ROWS-1; i+=2) {
		        for(int j=1; j<COLS-1; j+=2) {
		            if(!visited[i][j]) {
		                generateDFS(i, j);
		            }
		        }
		    }
		    fixStartAndEnd();
		    map[18][18] = 'T';
			for(int i=0;i<20;i++){
				for(int j=0;j<20;j++){
					if(i==x&&j==y){
						cout<<"我";
					}else{
						if(map[i][j]=="#"){
							cout<<"墙"; 
						}else if(map[i][j]=="T"){
							cout<<"终";
						}else{
							cout<<"  ";
						}
					}
				}
				cout<<endl;
			}
			cout<<"步数 : "<<step<<endl;
			while(map[x][y]!="T"){
				string s=SI_direction_KR();
				if(s=="UP"&&s!="\0"){
					if(map[x-1][y]!="#"){
						gotoxy(y*2,x);
						cout<<"  ";
						x--;
						gotoxy(y*2,x);
						cout<<"我";
						gotoxy(7,20);
						cout<<++step;
					}
				}else if(s=="DOWN"&&s!="\0"){
					if(map[x+1][y]!="#"){
						gotoxy(y*2,x);
						cout<<"  ";
						x++;
						gotoxy(y*2,x);
						cout<<"我";
						gotoxy(7,20);
						cout<<++step;
					}
				}else if(s=="LEFT"&&s!="\0"){
					if(map[x][y-1]!="#"){
						gotoxy(y*2,x);
						cout<<"  ";
						y--;
						gotoxy(y*2,x);
						cout<<"我";
						gotoxy(7,20);
						cout<<++step;
					}
				}else if(s!="\0"){
					if(map[x][y+1]!="#"){
						gotoxy(y*2,x);
						cout<<"  ";
						y++;
						gotoxy(y*2,x);
						cout<<"我";
						gotoxy(7,20);
						cout<<++step;
					}
				}
				Sleep(100);
			}
			cout<<"你赢了!";
			system("pause"); 
		}else if(mode=="1"){
			BFS_map();
			system("pause"); 
		}else if(mode=="3"){
			colour(0);
			break;
		}else{
			cout<<"ERROR,这个模式未被定义";
			Sleep(1000);
		}
	}
    return 0;
}
原文