int rand_neighbour(t_maze *data, t_generating *var) { int direction; direction = 0; while ((direction < 5 || direction > 9) && direction != 10) direction = my_rand() % 9; if ((var->y - 1 != -1) && data->maze[var->x][var->y - 1] == UNVISITED && direction == NORTH) (var->y) -= 1; else if (((var->y + 1) != data->width) && data->maze[var->x][var->y + 1] == UNVISITED && direction == SOUTH) var->y += 1; else if ((var->x + 1 != data->height) && data->maze[var->x + 1][var->y] == UNVISITED && direction == WEST) var->x += 1; else if ((var->x - 1 != -1) && data->maze[var->x - 1][var->y] == UNVISITED && direction == EAST) var->x -= 1; else rand_neighbour(data, var); return (0); }
/* Generate the maze * * Parameter(s): maze - maze cells * w - maze width * h - maze height * * Return: 0 on allocation error * 1 otherwise */ int generate(int **maze, const int w, const int h) { struct stack *st = NULL; int x, y, tmpx, tmpy; /* Seed rand() for rand_neighbour() */ srand((unsigned int) time(NULL)); /* Maze generation starts at bottom right corner. It's easiest to solve * the maze in the same 'way' it was generated, and since we believe * people intuitively will start at the top left corner, we start it * opposite of that (bottom right) */ x = w - 2; y = h - 2; while (1) { maze[y][x] = VISIT; tmpx = x; tmpy = y; if (rand_neighbour(maze, &x, &y, w, h)) { if (!push(&st, tmpx, tmpy)) { free_stack(&st); return 0; } } else { /* If no neighbour, we backtrack to the mother cell */ x = st->x; y = st->y; pop(&st); /* End generation if we can't backtrack further */ if (st->next == NULL) { break; } } } free_stack(&st); /* Mark exit and entrance */ maze[1][0] = VISIT; maze[h - 2][w - 1] = VISIT; return 1; }
int generate( char maze[][ MAP_WSIZE ], const int w, const int h) { struct stack *st = NULL; int x, y, tmpx, tmpy; srand( time( 0 ) ); x = w - 2; y = h - 2; while( 1 ){ maze[y][x] = VISIT; tmpx = x; tmpy = y; if (rand_neighbour(maze, &x, &y, w, h)) { if( push(&st, tmpx, tmpy)) { free_stack(&st); return 0; } } else { /* If no neighbour, we backtrack to the mother cell */ x = st->x; y = st->y; pop( &st ); /* End generation if we can't backtrack further */ if( st->next == 0 ) { break; } } } free_stack( &st ); /* Mark exit and entrance */ maze[1][0] = PLAYER; maze[h - 2][w - 1] = MONSTER; return 1; }