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
  Date: 24 April 2026
  Version: 1.1 with Javadoc comments
  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 for the initialisation of instances of the class MazeArray
	 * All MazeFields will be created with four walls, but without borders
	 * @param width size of maze in x-direction
	 * @param height size of maze in y-direction
	 */
	public MazeArray (int width, int height)
	{
		this.width = width;
		this.height = height;
		createMazeFields ();
	}

	/** Get width of the maze in x-direction
	 * @return width of the maze
	 *  */
	public int getWidth ()
	{
		return this.width;
	}

	/** Get height of the maze in y-direction
	 * @return height of the maze
	 *  */
	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++;
		}
	}

	/** Check all borders of the maze
	 * @throws MazeException if it detects formal border 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++;
		}
	}
}