【Python】迷路の外壁を設置する

迷路の幅と高さをそれぞれ width, height として設定し、
その数値にしたがって外壁を設置する。
※迷路の幅と高さは5以上の奇数とする。

import sys

class Maze:
  PATH = 0
  WALL = 1

  def __init__(self, width, height):
    self.width = width
    self.height = height
    if self.width < 5 or self.height < 5:
      sys.exit()
    if self.width % 2 == 0:
      self.width += 1
    if self.height % 2 == 0:
      self.height += 1
    self.maze = [[self.PATH for x in range(self.width)] for y in range(self.height)]

  def set_outer_wall(self):
    for y in range(0, self.height):
      for x in range(0, self.width):
        if x == 0 or y == 0 or x == self.width-1 or y == self.height-1:
          self.maze[y][x] = self.WALL
    return self.maze

  def print_maze(self):
    for col in self.maze:
      for cell in col:
        if cell == self.WALL:
          print('#', end='')
        elif cell == self.PATH:
          print(' ', end='')
      print()

maze1 = Maze(15, 15)
maze1.set_outer_wall()
maze1.print_maze()

今回は、以下のように出力される。

###############
#             #
#             #
#             #
#             #
#             #
#             #
#             #
#             #
#             #
#             #
#             #
#             #
#             #
###############
タイトルとURLをコピーしました