I have to generate a maze for a school project, but I'm stuck in a loop, I have no idea why, and my IDE ignores my breakpoints for some reason...
Here is my code:
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct _maze_cell {
int wallAbove, wallLeft, cellValue;
} MazeCell;
/* define maze structure */
typedef struct _maze_t {
/* maze size = m lines * n columns */
int row, column;
/* array of cells */
MazeCell* *array;
} Maze;
MazeCell* initMazeCell(){
MazeCell* cell = malloc(sizeof(MazeCell));
cell->wallAbove = 1;
cell->wallLeft = 1;
cell->cellValue = 0;
return cell;
}
int rand_a_b(int a, int b){
return rand()%(b-a) +a;
}
Maze* initMaze(int m, int n)
{
Maze* oMaze= malloc(sizeof(Maze));
int nbCells=m*n;
printf("%d \n", nbCells);
oMaze->array = malloc(nbCells*sizeof(MazeCell));
int counter=1;
int i;
for(i=0;i<m*n;i++)
{
if(i%m==0)
{
printf("\n");
}
oMaze->array[i]= initMazeCell();
oMaze->array[i]->cellValue=counter++;
printf("%4d", oMaze->array[i]->cellValue);
}
printf("\n");
//------------------------loop debut
int done=0;
while(done==0)
{
done=1;
int sizeofTab=m*n-1;
int nbAl=rand_a_b( 0, sizeofTab);
int wallChoosen=rand_a_b( 1, 2);
if(wallChoosen==1)
{
if(nbAl>n)
{
int b=nbAl-n;
int oldValue=oMaze->array[b]->cellValue;
int newValue=oMaze->array[nbAl]->cellValue;
if(oldValue!=newValue)
{
oMaze->array[nbAl]->wallAbove=0;
for(i=0;i<m*n;i++)
{
if(oMaze->array[i]->cellValue==oldValue)
{
//printf("old: %d",oMaze->array[i]->cellValue);
oMaze->array[i]->cellValue=newValue;
// printf("new: %d",oMaze->array[i]->cellValue);
}
}
}
}
}
if(wallChoosen==2)
{
if(nbAl>0)
{
int b=nbAl-1;
int oldValue=oMaze->array[b]->cellValue;
int newValue=oMaze->array[nbAl]->cellValue;
if(oldValue!=newValue)
{
oMaze->array[nbAl]->wallLeft=0;
for(i=0;i<m*n;i++)
{
if(oMaze->array[i]->cellValue==oldValue)
{
oMaze->array[i]->cellValue=newValue;
}
}
//oMaze->array[b]->cellValue=oMaze->array[nbAl]->cellValue;
}
}
}
int a;
for(i=0;i<m*n;i++)
{
if(i==0)
{
a=oMaze->array[i]->cellValue;
}
if(i!=0 && oMaze->array[i]->cellValue!=a)
{
done=0;
printf("%4d", oMaze->array[i]->cellValue);
}
}
}
//--------------------------------loop end
printf("\n The end!!");
int y;
for(y=0;y<m*n;y++)
{
if(y%m==0)
{
printf("\n");
}
printf("%4d", oMaze->array[y]->cellValue);
}
return oMaze;
}
int main()
{
srand(time(NULL));
Maze* myMaze=initMaze(5,5);
return 0;
}
The teacher told us to use this method :maze generation(sorry it's in french, but the image will help understand my what I'm trying to do in my code).
Can someone help me understand what I'm doing wrong?
I added a counter and stopped the loop after 200 turn and I get this:
This shows that it works until a certain point, I don't know why it doesn't work until the end...