자바스크립트로 2차원 배열을 이용해서 미로 만드는 함수입니다.

function generateSquareMaze(dimension) {

    function iterate(field, x, y) {
        field[x][y] = 0;
        while (true) {
            let directions = [];
            (x > 1 && field[x - 2][y]) && directions.push([-1, 0]);
            (x < field.length - 2 && field[x + 2][y]) && directions.push([1, 0]);
            (y > 1 && field[x][y - 2]) && directions.push([0, -1]);
            (y < field.length - 2 && field[x][y + 2]) && directions.push([0, 1]);
            if (directions.length == 0) return field;

            var dir = directions[Math.floor(Math.random() * directions.length)];
            field[x + dir[0]][y + dir[1]] = 0;
            field = iterate(field, x + dir[0] * 2, y + dir[1] * 2);
        }
    }

    // Initialize the field.
    let field = Array.from({ length: dimension }, () => new Array(dimension).fill(1));
    // Gnerate the maze recursively.
    field = iterate(field, 1, 1);
    field[0][1] = 0;
    return field;
}

 

아래와 같이 사용 할 수 있다.

let maze = generateSquareMaze(11);
console.log(maze);
728x90

+ Recent posts