迷路の幅と高さをそれぞれ width, height として設定し、
その数値にしたがって上下左右1マス間隔で内壁を設置する。
※迷路の幅と高さは5以上の奇数とする。
class Maze {
PATH: number;
WALL: number;
width: number;
height: number;
maze: number[][] = [];
constructor(width: number, height: number) {
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(this.height)].map(() => Array(this.width).fill(0));
}
set_outer_wall(): number[][] {
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(): number[][] {
for (let y = 2; y <= this.height-3; y+=2) {
for (let x = 2; x <= this.width-3; x+=2) {
this.maze[y][x] = this.WALL;
}
}
return this.maze;
}
print_maze(): void {
let arr: string;
for (let row of this.maze) {
arr = '';
for (let cell of row) {
if (cell === this.WALL) {
arr += '#';
} else if (cell === this.PATH) {
arr += ' ';
}
}
console.log(arr);
}
}
}
const maze1 = new Maze(15, 15);
maze1.set_outer_wall();
maze1.set_inner_wall();
maze1.print_maze();
今回は、以下のように出力される。
###############
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
###############