Python CUIで迷路生成(3)
スタートとゴールの場所を指定するところまで。
set_start_goal
ランダムに座標を指定し、そこが通路ならスタート”S”、またはゴール”G” をそこに設置する。
import sys import random class Maze(): PATH = 0 WALL = 1 START = 2 GOAL = 3 def __init__(self, height, width): self.maze = [] self.width = width self.height = height if (self.width % 2) == 0: self.width += 1 if (self.height % 2) == 0: self.height += 1 def set_outer_wall(self): for y in range(0, self.height): row = [] for x in range(0, self.width): if (x == 0 or y == 0 or x == self.width - 1 or y == self.height - 1): cell = self.WALL else: cell = self.PATH row.append(cell) self.maze.append(row) def set_inner_wall(self): for x in range(2, self.width-1, 2): for y in range(2, self.height-1, 2): self.maze[y][x] = self.WALL while True: wall_x = x wall_y = y if y == 2: direction = random.randrange(0, 4) else: direction = random.randrange(0, 3) if direction == 0: wall_x += 1 elif direction == 1: wall_y += 1 elif direction == 2: wall_x -= 1 else: wall_y -= 1 if self.maze[wall_y][wall_x] != self.WALL: self.maze[wall_y][wall_x] = self.WALL break def set_start_goal(self): # set start while True: s_x = random.randrange(1, self.width-1) s_y = random.randrange(1, self.height-1) if self.maze[s_y][s_x] == self.PATH: self.maze[s_y][s_x] = self.START break # set goal while True: g_x = random.randrange(1, self.width-1) g_y = random.randrange(1, self.height-1) if self.maze[g_y][g_x] == self.PATH: self.maze[g_y][g_x] = self.GOAL break def print_maze(self): for row in self.maze: for cell in row: if cell == self.PATH: print(' ', end='') elif cell == self.WALL: print('#', end='') elif cell == self.START: print('S', end='') elif cell == self.GOAL: print('G', end='') print() args = sys.argv maze = Maze(int(args[1]), int(args[2])) maze.set_outer_wall() maze.set_inner_wall() maze.set_start_goal() maze.print_maze()
出力例
$ python create_maze.py 10 20 ##################### # # # # # # ### ##### # ### ### # # # # ##### # # ##### ### # # # # # S# # ##### ####### ##### # # # # # # ##### ### # # ### # # G# # # # # #####################