迷路の幅と高さをそれぞれ width, height として設定し、
その数値にしたがって上下左右1マス間隔で内壁を設置する。
※迷路の幅と高さは5以上の奇数とする。
using System;
public class Maze {
public const int PATH = 0;
public const int WALL = 1;
public int width;
public int height;
public int[,] maze;
public Maze(int width, int height) {
this.width = width;
this.height = height;
if (this.width < 5 || this.height < 5) {
Environment.Exit(0);
}
if (this.width % 2 == 0) {
this.width++;
}
if (this.height % 2 == 0) {
this.height++;
}
this.maze = new int[this.height,this.width];
for (int y = 0; y < this.height; ++y) {
for (int x = 0; x < this.width; ++x) {
this.maze[y,x] = Maze.PATH;
}
}
}
public int[,] set_outer_wall() {
for (int y = 0; y < this.height; ++y) {
for (int x = 0; x < this.width; ++x) {
if (x == 0 || y == 0 || x == this.width-1 || y == this.height-1) {
this.maze[y,x] = Maze.WALL;
}
}
}
return this.maze;
}
public int[,] set_inner_wall() {
for (int y = 2; y < this.height-1; y += 2) {
for (int x=2; x<this.width-1; x += 2) {
this.maze[y,x] = Maze.WALL;
}
}
return this.maze;
}
public void print_maze() {
for (int y = 0; y < this.maze.GetLength(0); ++y) {
for (int x = 0; x < this.maze.GetLength(1); ++x) {
if (this.maze[y,x] == Maze.WALL) {
Console.Write('#');
} else if (this.maze[y,x] == Maze.PATH) {
Console.Write(' ');
}
}
Console.WriteLine();
}
}
public static void Main() {
Maze maze1 = new Maze(15, 15);
maze1.set_outer_wall();
maze1.set_inner_wall();
maze1.print_maze();
}
}
今回は、以下のように出力される。
###############
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # #
# #
###############