1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
Maze::Maze(int w, int h)
:maze((2*w+1)*(2*h+1))
,width(2*w+1)
,height(2*h+1)
{
std::generate(maze.begin(), maze.end(),[]{return 'X';});
}
Maze& Maze::build()
{
buildGrid();
buildMaze();
return *this;
}
int Maze::find(int a)
{
return a;
}
void Maze::join(int a, int b)
{
auto eqA = find(a);
auto eqB = find(b);
if(eqA == eqB) return;
removeWall(a,b);
}
void Maze::display()
{
for(int i = 0;i<height;++i)
{
for(int j=0;j<width;++j)
{
std::cout<<maze[i*width+j];
}
std::cout<<std::endl;
}
}
void Maze::buildMaze()
{
srand(time(NULL));
for(int i = 0; i<((height-1)*(width-1))/2;++i)
{
auto row = rand() %((height-1)/2);
auto col = rand() %((width-1)/2);
auto dir = rand() % 4;
switch(dir)
{
case 0:
join(getName(row,col),getName(row,col+1));
break;
case 1:
join(getName(row,col),getName(row+1,col));
break;
case 2:
join(getName(row,col),getName(row,col-1));
break;
case 3:
join(getName(row,col),getName(row-1,col));
break;
}
}
}
void Maze::buildGrid(){
for(int i = 1; i <height; i+=2)
for(int j=1; j<width; j+=2)
maze[i*(width)+j] = ' ';
}
void Maze::removeWall(int a, int b)
{
int colA = a % ((width-1) / 2);
int rowA = a % ((height-1) / 2);
int colB = b % ((width-1) / 2);
int rowB = b % ((height-1) / 2);
if(colA == colB)
{
maze[(rowA + rowB) * width + (colA *2)] = ' ';
}
if(rowA == rowB)
{
maze[(rowA*2) * width + (colA + colB)]= ' ';
}
}
int Maze::getName(int row, int col)
{
return( ((row * (width-1) / 2) + (col)));
}
|