{算法·随机生成迷宫}

这是一个使用C#编写的随机生成迷宫的算法,通过从起点开始,随机选择方向移动并保证路径不相交,最终生成迷宫。算法包括初始化矩阵、设置边界、建立出口、搜索路径等步骤,并提供了Debugs方法进行输出和Render方法进行渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚在网上看到这个的算法的分析,然后写了一个C#版的。算法分析地址:http://www.j2megame.org/index.php/content/view/2120/125.html

 

算法原理:从起点开始,随机选择一个方向移动,一直移动到终点,则移动的路径便是迷宫的路径。移动过程中要保证路径不要相交,不要超出边界,生成效果

 

 

public partial class MainForm : Form
    {
        private Bitmap bitmap;
        private const int SIZE=10;
        private const int MAXMAZE=50;
        private int[,] maze_matrix;
        public MainForm()
        {
            InitializeComponent();
            maze_matrix=new int[MAXMAZE+2,MAXMAZE+2];
        }
        
        void BtnCreateClick(object sender, EventArgs e)
        {
            
            makeMaze(10);
            Debugs(10);
            Render(10);
        }
        
        
        void Maze_panelMouseDown(object sender, MouseEventArgs e)
        {
            
        }
        
        void Maze_panelPaint(object sender, PaintEventArgs e)
        {
            
        }
        
        private void makeMaze(int size){
            for (int i = 0; i < size*2+2; ++i) {
                for (int j = 0; j < size*2+2; ++j) {
                    maze_matrix[i,j]=1;
                }
            }
            
            for(int z1=0, z2=2*size+2; z1<=2*size+2; ++z1)
            {
                maze_matrix[z1,0] = 0;
                maze_matrix[z1,z2] = 0;
            }
            for(int z1=0, z2=2*size+2; z1<=2*size+2; ++z1)
            {
                maze_matrix[0,z1] = 0;
                maze_matrix[z2,z1] = 0;
            }
            //建立出口
            maze_matrix[2,1] = 0;
            maze_matrix[2*size,2*size+1] = 0;
            Random random=new Random(GetRandomSeed());
            searchPath(random.Next(size)+1,random.Next(size)+1);
        }
        public int searchPath(int x,int y ){
            int[,] dir= {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
            int zx = x*2;
            int zy = y*2;
            int  turn;
            maze_matrix[zx,zy] = 0;
            Random random=new Random(GetRandomSeed());
            turn=random.Next(2)==0?1:3;
            for (int i = 0,next=random.Next(4); i < 4; ++i,next=(next+turn)%4) {
                if (maze_matrix[zx+2*dir[next,0],zy+2*dir[next,1]]==1) {
                    maze_matrix[zx+dir[next,0],zy+dir[next,1]]=0;
                    searchPath(x+dir[next,0],y+dir[next,1]);
                }
            }
            return 0;
        }
        
        public void Debugs(int size){
            Form f=new Form();
            f.Size=new Size(400,300);
            TextBox textbox=new TextBox();
            textbox.Multiline=true;
            textbox.Size=new Size(400,300);
            
            f.Controls.Add(textbox);
            
            
            f.Show();
            for(int z2=1; z2<=size*2+1; z2++)
            {
                for(int z1=1;z1<=size*2+1;z1++){
                    textbox.Text+=maze_matrix[z2,z1]==0?" ":"1";
                }
                textbox.Text+="\r\n";
            }
            
        }
        int GetRandomSeed()
        {

            byte[] bytes = new byte[4];

            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rng.GetBytes(bytes);

            return BitConverter.ToInt32(bytes, 0);

        }
        public void Render(int size){
            this.maze_panel.Refresh();
            bitmap=new Bitmap(300,300,PixelFormat.Format32bppArgb);
            Graphics g=Graphics.FromImage(bitmap);
            
            
            for(int z2=1; z2<=size*2+1; z2++)
            {
                for(int z1=1;z1<=size*2+1;z1++){
                    if (maze_matrix[z2,z1]==1) {
                        g.DrawRectangle(new Pen(Color.Red),new Rectangle(z2*SIZE,z1*SIZE,SIZE,SIZE));
                    }
                }
                
            }
            
            Graphics mazeg=this.maze_panel.CreateGraphics();
        
            mazeg.DrawImage(bitmap,0,0);
        }
    }

 

好的,我可以为你提供一份Python代码实现Prim算法生成迷宫,并用动画展示的方法。你需要安装Python的相关库`numpy`, `matplotlib`, `pillow`和`imageio`。以下是代码: ```python import numpy as np import matplotlib.pyplot as plt from PIL import Image import imageio def create_maze(width, height): maze = np.zeros((height, width)) start_x = np.random.randint(0, width) start_y = np.random.randint(0, height) maze[start_y, start_x] = 1 walls = [] if start_x > 0: walls.append((start_x - 1, start_y, start_x, start_y)) if start_x < width - 1: walls.append((start_x, start_y, start_x + 1, start_y)) if start_y > 0: walls.append((start_x, start_y - 1, start_x, start_y)) if start_y < height - 1: walls.append((start_x, start_y, start_x, start_y + 1)) while walls: wall = walls.pop(np.random.randint(0, len(walls))) x1, y1, x2, y2 = wall if maze[y1, x1] == 1 and maze[y2, x2] == 0: maze[y2, x2] = 1 if x2 > 0: walls.append((x2 - 1, y2, x2, y2)) if x2 < width - 1: walls.append((x2, y2, x2 + 1, y2)) if y2 > 0: walls.append((x2, y2 - 1, x2, y2)) if y2 < height - 1: walls.append((x2, y2, x2, y2 + 1)) elif maze[y2, x2] == 1 and maze[y1, x1] == 0: maze[y1, x1] = 1 if x1 > 0: walls.append((x1 - 1, y1, x1, y1)) if x1 < width - 1: walls.append((x1, y1, x1 + 1, y1)) if y1 > 0: walls.append((x1, y1 - 1, x1, y1)) if y1 < height - 1: walls.append((x1, y1, x1, y1 + 1)) return maze def animate_maze(maze, filename): height, width = maze.shape frames = [] for i in range(height): for j in range(width): if maze[i, j] == 0: img = np.ones((10, 10, 3)) img[:, :, 0] = 0 else: img = np.zeros((10, 10, 3)) img[:, :, 0] = 1 frames.append(img) imageio.mimsave(filename, frames, fps=30) maze = create_maze(50, 50) animate_maze(maze, 'maze.gif') maze_img = np.zeros((maze.shape[0] * 10, maze.shape[1] * 10)) for i in range(maze.shape[0]): for j in range(maze.shape[1]): if maze[i, j] == 0: maze_img[i*10:(i+1)*10, j*10:(j+1)*10] = 255 maze_img = Image.fromarray(maze_img.astype(np.uint8)) maze_img.show() ``` 这份代码将会生成一个大小为50x50的迷宫,并将迷宫动画保存为一个GIF文件,同时还会将迷宫以图像的形式展示出来。你可以尝试修改大小、保存格式等参数,自己生成不同的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值