JavaScriptでマインスイーパを作成する際には、HTMLとCSSも使用します。以下の手順に従ってください。
HTMLはシンプルに、ゲームボードとなる部分を定義します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>マインスイーパ</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="minefield"></div>
<script src="script.js"></script>
</body>
</html>
CSSでは、ボタンのスタイルを定義します。
#minefield {
display: grid;
grid-template-columns: repeat(8, 40px);
grid-template-rows: repeat(8, 40px);
gap: 2px;
}
button {
width: 40px;
height: 40px;
font-size: 20px;
font-weight: bold;
color: #333;
border: none;
background-color: #ddd;
cursor: pointer;
}
button.revealed {
background-color: #bbb;
}
JavaScriptでは、マインスイーパのロジックを実装します。
const SIZE = 8;
const BOMB_COUNT = 16;
function createMinefield() {
const minefield = [];
for (let y = 0; y < SIZE; y++) {
const row = [];
for (let x = 0; x < SIZE; x++) {
row.push({
x,
y,
isBomb: false,
neighborBombs: 0,
isRevealed: false,
});
}
minefield.push(row);
}
addBombs(minefield);
calculateNeighborBombs(minefield);
return minefield;
}
function addBombs(minefield) {
let bombsAdded = 0;
while (bombsAdded < BOMB_COUNT) {
const x = Math.floor(Math.random() * SIZE);
const y = Math.floor(Math.random() * SIZE);
if (!minefield[y][x].isBomb) {
minefield[y][x].isBomb = true;
bombsAdded++;
}
}
}
function calculateNeighborBombs(minefield) {
for (const row of minefield) {
for (const cell of row) {
cell.neighborBombs = getNeighbors(minefield, cell.x, cell.y)
.filter(neighbor => neighbor.isBomb)
.length;
}
}
}
function getNeighbors(minefield, x, y) {
const neighbors = [];
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dy === 0 && dx === 0) continue;
const nx = x + dx, ny = y + dy;
if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE) {
neighbors.push(minefield[ny][nx]);
}
}
}
return neighbors;
}
function reveal(cell) {
if (cell.isRevealed) return;
cell.isRevealed = true;
const button = document.querySelector(`button[data-x="${cell.x}"][data-y="${cell.y}"]`);
button.classList.add('revealed');
if (cell.isBomb) {
button.textContent = '💣';
alert('Game Over!');
} else if (cell.neighborBombs > 0) {
button.textContent = cell.neighborBombs;
} else {
getNeighbors(minefield, cell.x, cell.y)
.forEach(neighbor => reveal(neighbor));
}
}
function setupUI(minefield) {
const minefieldElement = document.getElementById('minefield');
minefieldElement.innerHTML = '';
minefield.forEach(row => {
row.forEach(cell => {
const button = document.createElement('button');
button.dataset.x = cell.x;
button.dataset.y = cell.y;
button.addEventListener('click', () => reveal(cell));
minefieldElement.appendChild(button);
});
});
}
const minefield = createMinefield();
setupUI(minefield);
このコードは基本的なマインスイーパの機能を提供します。追加の機能や改善は必要に応じて行ってください。
盤面をリセットするために、リセットボタンを追加し、関連する機能をJavaScriptに実装します。HTMLとJavaScriptを以下のように更新します。