#include "maze.h"

const int MAZE::width = MAZE_WIDTH;
const int MAZE::height = MAZE_HEIGHT;

MAZE::MAZE()
{
	reset();
}

void MAZE::reset()
{
	int _x, _y;
	for (_x = 0; _x < width; _x++)
	{
		for (_y = 0; _y < height; _y++)
		{
			wall[_y][_x][N] = true;
			wall[_y][_x][E] = true;
			wall[_y][_x][S] = true;
			wall[_y][_x][W] = true;
			border[_y][_x][N] = false;
			border[_y][_x][E] = false;
			border[_y][_x][S] = false;
			border[_y][_x][W] = false;
		}
	}

	for (_x = 0; _x < width; _x++)
	{
			border[0][_x][N] = true;
			border[height - 1][_x][S] = true;
	}
	for (_y = 0; _y < height; _y++)
	{
			border[_y][0][W] = true;
			border[_y][width - 1][E] = true;
	}
}



void MAZE::generate()
{
	reset();
	int x = rand() % width;
	int y = rand() % height;
	generate2(x, y);
}

bool MAZE::untouched(int _x, int _y)
{
	if (wall[_y][_x][N] == true)
	{
		if (wall[_y][_x][E] == true)
		{
			if (wall[_y][_x][S] == true)
			{
				if (wall[_y][_x][W] == true)
				{
					return true;
				}
			}
		}
	}
	return false;
}


void MAZE::generate2(int x, int y)
{
	int _d = rand() % 4;
	for (int _dc = 0; _dc < 4; _dc++)
	{
		switch ((_d + _dc) % 4)
		{
			case N:
				if ((border[y][x][N] != true) && untouched(x, y - 1))
				{
					wall[y][x][N] = false;
					wall[y-1][x][S] = false;
					generate2(x, y-1);
				}
				break;
			case E:
				if ((border[y][x][E] != true) && untouched(x + 1, y))
				{
					wall[y][x][E] = false;
					wall[y][x+1][W] = false;
					generate2(x+1, y);
				}
				break;	
			case S:
				if ((border[y][x][S] != true) && untouched(x, y + 1))
				{
					wall[y][x][S] = false;
					wall[y+1][x][N] = false;
					generate2(x, y+1);
				}
				break;	
			case W:
				if ((border[y][x][W] != true) && untouched(x - 1, y))
				{
						wall[y][x][W] = false;
						wall[y][x-1][E] = false;
						generate2(x-1, y);
				}
				break;	
		}
	}
}
