<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Maze Generation in JavaScript</title>
<style>
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: sans-serif;
}
canvas {
border: 2px solid #333;
background-color: #fff;
}
</style>
</head>
<body>
<h1>迷路の生成</h1>
<canvas id="mazeCanvas"></canvas>
<script>
// --- 設定 ---
const GRID_SIZE = 99; // グリッドのサイズ (99x99)
const CELL_SIZE = 6; // 1マスのピクセルサイズ
// --- Canvasの準備 ---
const canvas = document.getElementById('mazeCanvas');
const ctx = canvas.getContext('2d');
canvas.width = GRID_SIZE * CELL_SIZE;
canvas.height = GRID_SIZE * CELL_SIZE;
// --- 迷路生成ロジック ---
// 1. グリッド配列を0で初期化
let ary = Array.from({ length: GRID_SIZE }, () => Array(GRID_SIZE).fill(0));
// 2. 外周を壁(1)に設定
for (let i = 0; i < GRID_SIZE; i++) {
ary[i][0] = 1;
ary[i][GRID_SIZE - 1] = 1;
ary[0][i] = 1;
ary[GRID_SIZE - 1][i] = 1;
}
// 3. 柱の設置と壁のランダム追加
// 元のコードの i < 49, j < 49 に対応
for (let i = 1; i < (GRID_SIZE - 1) / 2; i++) {
for (let j = 1; j < (GRID_SIZE - 1) / 2; j++) {
const x = i * 2;
const y = j * 2;
// 柱を立てる
ary[x][y] = 1;
// 0から3のランダムな整数を生成し、壁を追加する方向を決める
const ranten = Math.floor(Math.random() * 4);
if (ranten === 0) { // 元コードの ranten == 0 (右へ)
ary[x + 1][y] = 1;
} else if (ranten === 1) { // 元コードの ranten == 1 (左へ)
ary[x - 1][y] = 1;
} else if (ranten === 2) { // 元コードの ranten == 2 (上へ)
ary[x][y + 1] = 1;
} else if (ranten === 3) { // 元コードの ranten == 3 (下へ)
ary[x][y - 1] = 1;
}
}
}
// --- 描画処理 ---
for (let i = 0; i < GRID_SIZE; i++) {
for (let j = 0; j < GRID_SIZE; j++) {
if (ary[i][j] === 1) {
// 壁を描画 (黒)
ctx.fillStyle = 'black';
ctx.fillRect(i * CELL_SIZE, j * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
// 道(0)はデフォルトの背景色(白)のまま
}
}
</script>
</body>
</html>
使用変数
ary | |
canvas | |
CELL_SIZE | |
charset | |
ctx | |
fillStyle | |
GRID_SIZE | |
height | |
i | |
id | |
j | |
lang | |
ranten | |
width | |
x | |
y |