【C#】壁のない迷路を生成する

迷路の幅と高さをそれぞれ width, height として設定し、
その数値にしたがって壁のない迷路を生成する。
※迷路の幅と高さは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 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.print_maze();
        for (int y = 0; y < maze1.maze.GetLength(0); ++y) {
            for (int x = 0; x < maze1.maze.GetLength(1); ++x) {
                Console.Write(maze1.maze[y,x]);
            }
            Console.WriteLine();
        }
        Console.WriteLine("{0} {1}", maze1.maze.GetLength(1), maze1.maze.GetLength(0));
    }
}

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

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