-
Notifications
You must be signed in to change notification settings - Fork 0
/
maze.c
120 lines (102 loc) · 2.43 KB
/
maze.c
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
109
110
111
112
113
114
115
116
MAZE MAZE_CreateMaze(int size)
{
MAZE maze;
maze.size = size;
maze.visited_sum = 0;
maze.cells = (CELL**)malloc(sizeof(CELL*)*maze.size);
maze.visited = (int**)malloc(sizeof(int*)*maze.size);
for(int i = 0; i < maze.size; i++)
{
maze.cells[i] = (CELL*)malloc(sizeof(CELL)*maze.size);
maze.visited[i] = (int*)malloc(sizeof(int)*maze.size);
for(int j = 0; j < maze.size; j++)
{
maze.cells[i][j] = (CELL){i, j, j*CELL_W, i*CELL_H, 0, 0, 0, 0, NULL, NULL, 1, 1, 1, 1};
maze.visited[i][j] = 0;
};
};
return maze;
};
void MAZE_UpdateMazeBasedOnStep(CELL * previous, CELL * current)
{
int iStep = current->i - previous->i;
int jStep = current->j - previous->j;
if(jStep == 1)
{
current->walls[3] = 0;
previous->walls[1] = 0;
}
if(jStep == -1)
{
current->walls[1] = 0;
previous->walls[3] = 0;
}
if(iStep == 1)
{
current->walls[0] = 0;
previous->walls[2] = 0;
}
if(iStep == -1)
{
current->walls[2] = 0;
previous->walls[0] = 0;
}
}
CELL * MAZE_GetRandomNeighborn(MAZE *maze, int iC, int jC)
{
CELL *neighborns[4];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int valid = 0;
for(int k = 0; k < 4; k++)
{
int i = iC + dx[k];
int j = jC + dy[k];
if(i >= 0 && i < maze->size && j >= 0 && j < maze->size && !maze->visited[i][j])
neighborns[valid++] = &maze->cells[i][j];
}
if(valid)
{
return neighborns[rand()%valid];
}
else
return NULL;
}
void MAZE_GenerateMaze(MAZE *maze)
{
CELL *current = &maze->cells[0][0];
while(maze->visited_sum < (MAZE_SIZE*MAZE_SIZE) - 1)
{
maze->visited[current->i][current->j] = 1;
maze->visited_sum++;
CELL * choice = MAZE_GetRandomNeighborn(maze, current->i, current->j);
if(choice == NULL)
{
CELL * parent = current;
while(MAZE_GetRandomNeighborn(maze, parent->i, parent->j) == NULL)
{
MAZE_UpdateMazeBasedOnStep(parent, parent->mazeParent);
parent = parent->mazeParent;
}
choice = MAZE_GetRandomNeighborn(maze, parent->i, parent->j);
MAZE_UpdateMazeBasedOnStep(parent, choice);
};
MAZE_UpdateMazeBasedOnStep(current, choice);
choice->mazeParent = current;
current = choice;
int t = usleep(3000);
}
maze->visited[current->i][current->j] = 1;
}
void MAZE_ResetMaze(MAZE * maze)
{
maze->visited_sum = 0;
for(int i = 0; i < maze->size; i++)
{
for(int j = 0; j < maze->size; j++)
{
maze->cells[i][j] = (CELL){i, j, j*CELL_W, i*CELL_H, 0, 0, 0, 0, NULL, NULL, 1, 1, 1, 1};
maze->visited[i][j] = 0;
};
};
};