Zum Inhalt springen

Rekursive Labyrinthe/ MazeArray

Aus Wikibooks
/*
  Source file: MazeArray.java
  Program: Maze Array
  Author: Markus Bautsch
  Licence: public domain
  Date: 23 October 2020
  Version: 1.0
  Programming language: Java
*/

/*
  This class implements a rectangular maze
  with width fields in horizontal direction and
  with height maze fields in vertical direction.
  A maze field is rectangular and can have walls and borders at its edges.
  The maze has to be initialised with all walls blocked
  and some of these walls can be removed for building a maze.
  The outer rim of the maze has to be defined by borders.
  Borders are also allowed within the maze to exclude certain fields from the maze.
  Borders must have walls.
  Maze fields outside the outer borders must not have walls.
*/

public class MazeArray
{
	/* Size of maze */
	private int width;
	private int height;
	
	/* Array for maze fields */
	public MazeField [][] fields;

	/* Constructor */
	public MazeArray (int width, int height)
	{
		this.width = width;
		this.height = height;
		createMazeFields ();
	}

	public int getWidth ()
	{
		return this.width;
	}

	public int getHeight ()
	{
		return this.height;
	}
	
	/* This method creates all maze fields */
	private void createMazeFields ()
	{
		int width = this.width;
		int height = this.height;

		fields = new MazeField [width][height];

		int y = 0;
		while (y < height)
		{
			int x = 0;
			while (x < width)
			{
				fields [x][y] = new MazeField (x, y);
				x++;
			}
			y++;
		}
	}

	/* This method throws a MazeException if it detects formal errors within the maze */
	public void checkMaze () throws MazeException
	{
		int width = this.width;
		int height = this.height;

		int y = 0;
		while (y < height)
		{
			int x = 0;
			while (x < width)
			{
				if (!fields [x][y].checkBorders ())
				{
					throw new MazeException ("Maze field design error at: x = " + x + " / y = " + y);
				}
				x++;
			}
			y++;
		}
	}
}