我试图移植此代码: http://www.emanueleferonato.com/2008/12/08/perfect-maze-generation-tile-based-version-as3/ 到c#,用XNA编写。
但我迷失了迷宫:
我是c#的新手,也许有人可以帮助我?
这是我的C#代码(我删除了绘制方法):
class Maze
{
private int MAZE_WIDTH = 30;
private int MAZE_HEIGHT = 30;
private int TILE_SIZE = 10;
private int _width;
private int _height;
private int [,] _maze;
private List<int> _moves;
private int _startX;
private int _startY;
private int _finishX;
private int _finishY;
public Maze()
{
_width = MAZE_WIDTH *2 - 1;
_height = MAZE_HEIGHT *2 - 1;
_startX = 1;
_startY = 1;
_finishX = _height - 2;
_finishY = _height - 2;
Generate();
}
public void Generate()
{
InitMaze();
CreateMaze();
}
private void InitMaze()
{
_maze = new int[_width, _height];
for (var x = 0; x < _height; x++)
{
for (var y = 0; y < _width; y++)
_maze[x, y] = 1;
}
_maze[_startX, _startY] = 0;
}
private void CreateMaze()
{
var posX = _startX;
var posY = _startY;
_moves = new List<int>();
_moves.Add(posY + (posX*_width));
while (_moves.Count > 0)
{
string possibleDirections = "";
if ((posX + 2 < _height) && (_maze[posX + 2, posY] == 1) && (posY + 2 != 0) && (posX + 2 != _height - 1))
{
possibleDirections += "S";
}
if ((posX - 2 >= 0) && (_maze[posX - 2, posY] == 1) && (posX - 2 != 0) && (posX - 2 != _height - 1))
{
possibleDirections += "N";
}
if ((posY - 2 >= 0) && (_maze[posX, posY - 2] == 1) && (posY - 2 != 0) && (posY - 2 != _width - 1))
{
possibleDirections += "W";
}
if ((posY + 2 < _width) && (_maze[posX, posY + 2] == 1) && (posY + 2 != 0) && (posY + 2 != _width - 1))
{
possibleDirections += "E";
}
if (possibleDirections.Length > 0)
{
var move = Utils.RandInt(0, (possibleDirections.Length - 1));
switch (possibleDirections[move].ToString())
{
case "N":
_maze[posX - 2, posY] = 0;
_maze[posX - 1, posY] = 0;
posX -= 2;
break;
case "S":
_maze[posX + 2, posY] = 0;
_maze[posX + 1, posY] = 0;
posX += 2;
break;
case "W":
_maze[posX,posY - 2] = 0;
_maze[posX,posY - 1] = 0;
posY -= 2;
break;
case "E":
_maze[posX,posY + 2] = 0;
_maze[posX,posY + 1] = 0;
posY += 2;
break;
}
}
else
{
var back = _moves[_moves.Count - 1];
_moves.RemoveAt(_moves.Count - 1);
posX = back/_width;
posY = back%_width;
}
}
}
public void DrawMaze(ScreenBase screen)
{
//just drawing tiles
}
private int RandInt(int min, int max)
{
return new Random().Next(min, max);
}
//End of class
}
class Utils
{
private static readonly Random rnd = new Random();
public static int RandInt(int min, int max)
{
return rnd.Next(min, max);
}
}
答案 0 :(得分:0)
您每次拨打Random
时都会生成一个新的RandInt()
对象。当它快速连续发生时,它使用相同的种子,因为它基于系统时间,你最终得到相同的&#34;随机&#34;价值一遍又一遍。
修复它的一种方法是添加另一个字段:
private Random _random = new Random();
然后将您的RandInt()
方法更改为:
private int RandInt(int min, int max)
{
return _random.Next(min, max);
}