728x90
자바스크립트로 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
반응형
'Software > JavaScript' 카테고리의 다른 글
JavaScript 시작하기 - 마우스 클릭 한 TD에 DIV 겹치기 (0) | 2024.04.03 |
---|---|
NodeJS에서 SQLite3 사용하기 (0) | 2023.12.25 |
JavaScript 시작하기 - three.js 소개 (0) | 2023.12.10 |
JavaScript 시작하기 - Code Pan 소개 (0) | 2023.12.03 |
JavaScript 시작하기 - 미로 만들기 함수 활용 (0) | 2023.12.02 |