C#自动生成迷宫

网上找到些自动生成迷宫的代码,主要是用C语言写的,可参照http://blog.sina.com.cn/s/blog_66ad7bba0100hk6k.html,本文对其稍作修改,使用C#改写,代码应该是我见到的最简单的了吧,如有兴趣,我们可以互相讨论。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    static class CreateMaze
    {
        static int[,] m=new int[50,50];
        static int[,] d = new int[4,2] { {0,1},{1,0},{0,-1},{-1,0}};
        static int w = 5,h=5,u = w * 2 + 1, v = h * 2 + 1;
        static Random num = new Random();
        static int Init(int y, int x)
        {
            if (x < 1 || y < 1 || x >= u - 1 || y >= v - 1 ||m[y,x]==1)
            { 
                return 0; 
            }
            else
            {
                m[y,x] = 1;
            }
            
            for (int f = num.Next() % 4, i = 0, p = (num.Next() &1)==1 ? 3: 1; i < 4; ++i, f = (f + p) % 4)
            {
                if (Init(y + d[f,0] * 2, x + d[f,1] * 2)==1)
                {
                    m[y + d[f,0],x + d[f,1]] = 1;
                }
            }
            return 1;
        }
        static void Main()
        { 
            Init(1,1);
            m[1, 0] = m[v - 2, u - 1] = 1;
            for (int y = 0; y < v; y++)
            {
                for (int x = 0; x < u; x++)
                {
                    Console.Write((m[y,x]==1) ? "  " : "█");
                }
                Console.WriteLine("");
            }
           
        }


    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值