【Python】迷路のスタートとゴールを設定する

迷路のスタートとゴールを座標によって設定し、
スタートを「S」、ゴールを「G」として出力する。

import sys
import random

class Maze:
  PATH = 0
  WALL = 1

  def __init__(self, width, height, seed=0):
    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)]
    self.start = [1, 1]
    self.goal = [self.width-2, self.height-2]
    random.seed(seed)

  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 set_inner_wall(self):
    for y in range(2, self.height-1, 2):
      for x in range(2, self.width-1, 2):
        self.maze[y][x] = self.WALL
    return self.maze

  def set_maze_boutaoshi(self):
    self.set_outer_wall()
    self.set_inner_wall()
    for y in range(2, self.height-1, 2):
      for x in range(2, self.width-1, 2):
        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
          elif direction == 3:
            wall_y -= 1
          if self.maze[wall_y][wall_x] != self.WALL:
            self.maze[wall_y][wall_x] = self.WALL
            break
    return self.maze

  def set_start_goal(self, start, goal):
    if self.maze[start[1]][start[0]] == self.PATH:
      self.start = start
    if self.maze[goal[1]][goal[0]] == self.PATH:
      self.goal = goal
    return self.maze

  def print_maze(self):
    self.maze[self.start[1]][self.start[0]] = 'S'
    self.maze[self.goal[1]][self.goal[0]] = 'G'
    for col in self.maze:
      for cell in col:
        if cell == self.WALL:
          print('#', end='')
        elif cell == self.PATH:
          print(' ', end='')
        elif cell == 'S':
          print('S', end='')
        elif cell == 'G':
          print('G', end='')
      print()

maze1 = Maze(15, 15)
maze1.set_maze_boutaoshi()
maze1.set_start_goal([5, 5], [9, 11])
maze1.print_maze()

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

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