
#include "cMaze.h"
#include "cArray2D.cpp"

static int xy[4][2] = { 0, -1, 0, 1, 1, 0, -1, 0 };
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

cMaze::cMaze(){

}

cMaze::~cMaze(){
	Destroy();
}

BOOL cMaze::Generate(int y, int x){
	if(!Create(y, x)) return FALSE;
	// 미로를 생성하기 위해 길을 모두 막는다.

	for(y = 0; y < Height; y ++){
		for(x = 0; x < Width; x ++){
			Elements[y * Width + x] = TRUE;
		}
	}
	// 이제 막힌 곳에 길을 뚫으며 미로를 생성한다.
	GenerateTree(Height / 4 * 2 - 1, Width / 4 * 2 - 1);

	return TRUE;
}

BOOL cMaze::GenerateLoose(int y, int x, int Rate){
	if(!Create(y, x)) return FALSE;

	for(y = 0; y < Height; y ++){
		for(x = 0; x < Width; x ++){
			Elements[y * Width + x] = TRUE;
		}
	}
	GenerateLooseTree(Height / 4 * 2 - 1, Width / 4 * 2 - 1, Rate);

	return TRUE;

}

void cMaze::GenerateTree(int y, int x){
	BOOL seq[4];
	int i, dx, dy, idx;
	BOOL tmp;

	if(y < 0 || x < 0 || y >= Height || x >= Width)
		return;
	if(Get(y, x) == FALSE) return;
	Set(y, x, FALSE);
	for(i = 0; i < 4; i ++) seq[i] = i;
	for(i = 0; i < 4; i ++){
		idx = rand() % 3;
		tmp = seq[idx];
		seq[idx] = seq[idx + 1];
		seq[idx + 1] = tmp;
	}
	for(i = 0; i < 4; i ++){
		idx = seq[i];
		dx = xy[idx][0];
		dy = xy[idx][1];
		if(y + dy + dy >= 0 && y + dy + dy < Height
			&& x + dx + dx >= 0 && x + dx + dx < Width){
			if(Get(y + dy + dy, x + dx + dx)){
				Set(y + dy, x + dx, FALSE);
				GenerateTree(y + dy + dy, x + dx + dx);
			}
		}
	}
}

void cMaze::GenerateLooseTree(int y, int x, int Rate){
	int i, dx, dy, idx;

	if(y < 0 || x < 0 || y >= Height || x >= Width)
		return;
	if(Get(y, x) == FALSE && (rand() % 256) < Rate) return;
	Set(y, x, FALSE);
	for(i = 0; i < 4; i ++){
		idx = rand() % 4;
		dx = xy[idx][0];
		dy = xy[idx][1];
		if(y + dy + dy >= 0 && y + dy + dy < Height
			&& x + dx + dx >= 0 && x + dx + dx < Width){
			if(Get(y + dy + dy, x + dx + dx) == TRUE || (rand() % 256) < Rate){
				Set(y + dy, x + dx, FALSE);
				GenerateLooseTree(y + dy + dy, x + dx + dx, Rate);
			}
		}
	}
}
