【p5.js】棒倒し法で迷路を生成する

迷路の幅と高さをそれぞれ width, height として設定し、
その数値にしたがって棒倒し法で迷路を生成する。
※迷路の幅と高さは5以上の奇数とする。

let maze1;

function setup() {
  maze1 = new Maze(15, 15);
  maze1.set_maze_boutaoshi();
  maze1.print_maze();
}

class Maze {
  constructor(width, height, seed=0) {
    this.PATH = 0;
    this.WALL = 1;
    this.width = width;
    this.height = height;
    if (this.width < 5 || this.height < 5) {
      return;
    }
    if (this.width%2 == 0) {
      this.width++;
    }
    if (this.height%2 == 0) {
      this.height++;
    }
    this.maze = Array.from(new Array(this.height), () => new Array(this.width).fill(this.PATH));
    randomSeed(seed);
  }

  set_outer_wall() {
    for (let y = 0; y < this.height; ++y) {
      for (let x = 0; x < this.width; ++x) {
        if (x == 0 || y == 0 || x == this.width-1 || y == this.height-1) {
          this.maze[y][x] = this.WALL;
        }
      }
    }
    return this.maze;
  }
  
  set_inner_wall() {
    for (let y = 2; y < this.height-1; y+=2) {
      for (let x = 2; x < this.width-1; x+=2) {
        this.maze[y][x] = this.WALL;
      }
    }
    return this.maze;
  }
  
  set_maze_boutaoshi() {
    let wall_x;
    let wall_y;
    let direction;
    this.set_outer_wall();
  this.set_inner_wall();
  for (let y = 2; y < this.height-1; y+=2) {
      for (let x = 2; x < this.width-1; x+=2) {
        while (true) {
          wall_x = x;
          wall_y = y;
          if (y == 2) {
            direction = floor(random(4));
          } else {
            direction = floor(random(3));
          }
          if (direction == 0) {
            wall_x += 1;
          } else if (direction == 1) {
            wall_y += 1;
          } else if (direction == 2) {
            wall_x -= 1;
          } else if (direction == 3) {
            wall_y -= 1;
          }
          if (this.maze[wall_y][wall_x] != this.WALL) {
            this.maze[wall_y][wall_x] = this.WALL;
            break;
          }
        }
      }
    }
    return this.maze;
  }

  print_maze() {
    for (let col of this.maze) {
      let arr = '';
      for(let cell of col) {
        if (cell == this.WALL) {
          arr += '#';
        } else if (cell == this.PATH) {
          arr += ' ';
        }
      }
      console.log(arr);
    }
  }
}

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

###############
#     #       #
# ### ### ### #
#   #     #   #
# # # # ##### #
# # # # #     #
# ### ##### ###
# #     #     #
# # # # # # ###
# # # # # #   #
# ##### # ### #
#     # #   # #
# ### ### # # #
#   # #   # # #
###############
p5.js Web Editor
A web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators,...

参考

迷路生成(棒倒し法) - Algoful
棒倒し法は迷路生成アルゴリズムの一種で比較的実装が容易ですが、その分生成される迷路も単純です。シミュレーション機能で生成される過程を確認できます。C#の実装サンプルを用意しているのでUnityでのゲーム開発の参考にどうぞ。
[Python] 棒倒し法による迷路生成
迷路生成のアルゴリズム 迷路生成のアルゴリズムは数多くあります。 Maze Classification -M…
自動生成迷路

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