Write maze generation procedure with no randomisation
This commit is contained in:
parent
9646a67faa
commit
02873d3120
48
main.c
48
main.c
@ -18,10 +18,55 @@
|
|||||||
|
|
||||||
#define PX(x) ((x) << 3)
|
#define PX(x) ((x) << 3)
|
||||||
|
|
||||||
|
#define GOAL (GRID_SIZE - 1)
|
||||||
|
|
||||||
|
typedef enum { LEFT, RIGHT, UP, DOWN } dir_t;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
bool cells[GRID_SIZE][GRID_SIZE];
|
bool cells[GRID_SIZE][GRID_SIZE];
|
||||||
} maze_t;
|
} maze_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int x, y;
|
||||||
|
} vec2_t;
|
||||||
|
|
||||||
|
static const vec2_t steps[] = {
|
||||||
|
[LEFT] = { .x = -2, .y = 0 },
|
||||||
|
[RIGHT] = { .x = 2, .y = 0 },
|
||||||
|
[UP] = { .x = 0, .y = -2 },
|
||||||
|
[DOWN] = { .x = 0, .y = 2 },
|
||||||
|
};
|
||||||
|
|
||||||
|
static void generate_step(maze_t *m, int x, int y)
|
||||||
|
{
|
||||||
|
m->cells[x][y] = true;
|
||||||
|
if (GOAL == x && GOAL == y)
|
||||||
|
return;
|
||||||
|
|
||||||
|
dir_t visit[] = { LEFT, RIGHT, UP, DOWN };
|
||||||
|
|
||||||
|
for (int i = 0; i < 4; ++i) {
|
||||||
|
const int xp = x + steps[visit[i]].x;
|
||||||
|
const int yp = y + steps[visit[i]].y;
|
||||||
|
|
||||||
|
const bool x_in_bounds = xp >= 0 && xp < GRID_SIZE;
|
||||||
|
const bool y_in_bounds = yp >= 0 && yp < GRID_SIZE;
|
||||||
|
if (x_in_bounds && y_in_bounds && !m->cells[xp][yp]) {
|
||||||
|
const int xi = (x + xp) / 2;
|
||||||
|
const int yi = (y + yp) / 2;
|
||||||
|
m->cells[xi][yi] = true;
|
||||||
|
|
||||||
|
generate_step(m, xp, yp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void generate_maze(maze_t *m)
|
||||||
|
{
|
||||||
|
memset(m, 0, sizeof(maze_t));
|
||||||
|
generate_step(m, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
static void draw_maze(Display *dpy, Window w, GC gc, const maze_t *m)
|
static void draw_maze(Display *dpy, Window w, GC gc, const maze_t *m)
|
||||||
{
|
{
|
||||||
// Draw walls
|
// Draw walls
|
||||||
@ -76,8 +121,9 @@ int main(void)
|
|||||||
XNextEvent(dpy, &evt);
|
XNextEvent(dpy, &evt);
|
||||||
while (MapNotify != evt.type);
|
while (MapNotify != evt.type);
|
||||||
|
|
||||||
|
// Generate and draw maze
|
||||||
maze_t m;
|
maze_t m;
|
||||||
memset(&m, 0, sizeof(maze_t));
|
generate_maze(&m);
|
||||||
draw_maze(dpy, w, gc, &m);
|
draw_maze(dpy, w, gc, &m);
|
||||||
|
|
||||||
// Wait for window exit
|
// Wait for window exit
|
||||||
|
Loading…
x
Reference in New Issue
Block a user