您的位置:首页 > 编程语言 > C#

C#自动生成迷宫

2013-10-15 15:32 246 查看
网上找到些自动生成迷宫的代码,主要是用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("");

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: