미로 만들기 함수을 이용해서 미로 만들었다.

 

※ 소스

<html>
<head>
    <style>
        body {
            margin: 0;
            background: #0c4a6e;
        }
        table {
            border-collapse: collapse;
            border: none;
        }
        tr:nth-child(odd) {
            height: 3px;
        }
        tr:nth-child(even) {
            height: 40px;
        }
        td:nth-child(odd) {
            width: 3px;
        }
        td:nth-child(even) {
            width: 40px;
        }
        .x {
            background: white;
        }
    </style>
</head>
<body>
    <table class='maze'>
    </table>
    <script>
        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);
        let $maze = document.querySelector('.maze');
        let $tr = '';
        for(let tr of maze) {
            $tr += '<tr>';
            for(let td of tr) {
                if (td)
                    $tr +=  "<td></td>";
                else
                    $tr +=  "<td class='x'></td>";
            }
            $tr += '</tr>';
        }
        $maze.innerHTML = $tr;
    </script>
</body>
</html>

 

※ 실행화면

728x90

+ Recent posts