08-生成一个随机迷宫
2.2.1 生成一个随机迷宫
Maze
类将在内部记录一个表示其状态的网格(列表的列表)。还有表示行数、列数、起始位置和目标位置的实例变量,该网格将被随机填入一些路障单元格。
这里生成的迷宫应该相当地稀疏,以便从给定的起始位置到给定的目标位置的路径几乎总是存在(毕竟这里只是为了测试算法)。实际的稀疏度将由迷宫的调用者决定,但这里将给出默认的稀疏度为20%的路障。如果某个随机数超过了当前 sparseness
参数给出的阈值,就会简单地用路障单元格替换空单元格。如果对迷宫中的每个位置都执行上述操作,那么从统计学上说,整个迷宫的稀疏度将近似于给定的 sparseness
参数。具体代码如代码清单2-12所示。
代码清单2-12 maze.py(续)
class Maze:
def __init__(self, rows: int = 10, columns: int = 10, sparseness: float = 0.2, start:
MazeLocation = MazeLocation(0, 0), goal: MazeLocation = MazeLocation(9, 9)) -> None:
# initialize basic instance variables
self._rows: int = rows
self._columns: int = columns
self.start: MazeLocation = start
self.goal: MazeLocation = goal
# fill the grid with empty cells
self._grid: List[List[Cell]] = [[Cell.EMPTY for c in range(columns)]
for r in range(rows)]
# populate the grid with blocked cells
self._randomly_fill(rows, columns, sparseness)
# fill the start and goal locations in
self._grid[start.row][start.column] = Cell.START
self._grid[goal.row][goal.column] = Cell.GOAL
def _randomly_fill(self, rows: int, columns: int, sparseness: float):
for row in range(rows):
for column in range(columns):
if random.uniform(0, 1.0) < sparseness:
self._grid[row][column] = Cell.BLOCKED
现在我们有了迷宫,还需要一种把它简洁地打印到控制台的方法。输出的字符应该靠得很近,以便使该迷宫看起来像一个真实的迷宫。具体代码如代码清单2-13所示。
代码清单2-13 maze.py(续)
# return a nicely formatted version of the maze for printing
def __str__(self) -> str:
output: str = ""
for row in self._grid:
output += "".join([c.value for c in row]) + "\n"
return output
然后测试一下上述这些迷宫函数。
maze: Maze = Maze()
print(maze)