iT邦幫忙

1

Day17 C程式🗂️ maze_gen.c

c
  • 分享至 

  • xImage
  •  

🗂️ maze_gen.c

#include "maze_gen.h"
#include <stdlib.h>
#include <time.h>

static void carve(int x, int y, Maze *maze) {
    int dirs[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
    for (int i = 0; i < 4; i++) {
        int r = rand() % 4;
        int tx = dirs[i][0], ty = dirs[i][1];
        dirs[i][0] = dirs[r][0]; dirs[i][1] = dirs[r][1];
        dirs[r][0] = tx; dirs[r][1] = ty;
    }
    for (int i = 0; i < 4; i++) {
        int nx = x + dirs[i][0]*2, ny = y + dirs[i][1]*2;
        if (nx > 0 && ny > 0 && nx < maze->width-1 && ny < maze->height-1 &&
            maze->grid[ny][nx] == '#') {
            maze->grid[y + dirs[i][1]][x + dirs[i][0]] = ' ';
            maze->grid[ny][nx] = ' ';
            carve(nx, ny, maze);
        }
    }
}

void initMaze(Maze *maze, int w, int h) {
    maze->width = w;
    maze->height = h;
    maze->grid = malloc(h * sizeof(char *));
    for (int i = 0; i < h; i++) {
        maze->grid[i] = malloc(w * sizeof(char));
        for (int j = 0; j < w; j++) maze->grid[i][j] = '#';
    }
    maze->startX = 1;
    maze->startY = 1;
    maze->endX = w - 2;
    maze->endY = h - 2;
}

void generateMaze(Maze *maze) {
    srand(time(NULL));
    maze->grid[maze->startY][maze->startX] = ' ';
    carve(maze->startX, maze->startY, maze);
    maze->grid[maze->startY][maze->startX] = 'S';
    maze->grid[maze->endY][maze->endX] = 'E';
}

void freeMaze(Maze *maze) {
    for (int i = 0; i < maze->height; i++)
        free(maze->grid[i]);
    free(maze->grid);
}


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言