好的,下面是一个简单的扫雷小游戏的HTML和JavaScript代码:
HTML部分:
<!DOCTYPE html>
<html>
<head>
<title>扫雷小游戏</title>
<style>
.grid {
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid black;
background-color: gray;
text-align: center;
line-height: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>扫雷小游戏</h1>
<div id="gridContainer"></div>
<script src="game.js"></script>
</body>
</html>
JavaScript部分(game.js):
window.onload = function() {
const gridContainer = document.getElementById("gridContainer");
const gridSize = 10;
const numBombs = 10;
let grid = [];
// 创建游戏格子
for (let i = 0; i < gridSize; i++) {
let row = [];
for (let j = 0; j < gridSize; j++) {
let cell = document.createElement("div");
cell.className = "grid";
cell.onclick = function() {
handleClick(i, j);
};
gridContainer.appendChild(cell);
row.push(cell);
}
grid.push(row);
}
// 随机放置炸弹
for (let i = 0; i < numBombs; i++) {
let row = Math.floor(Math.random() * gridSize);
let col = Math.floor(Math.random() * gridSize);
grid[row][col].setAttribute("bomb", true);
}
// 处理点击事件
function handleClick(row, col) {
let cell = grid[row][col];
if (cell.getAttribute("bomb")) {
cell.style.backgroundColor = "red";
alert("你踩到了炸弹,游戏结束!");
} else {
let count = countBombs(row, col);
cell.innerHTML = count;
cell.style.backgroundColor = "lightgray";
cell.onclick = null;
if (count === 0) {
handleEmptyCell(row, col);
}
}
}
// 计算周围的炸弹数量
function countBombs(row, col) {
let count = 0;
for (let i = row - 1; i <= row + 1; i++) {
for (let j = col - 1; j <= col + 1; j++) {
if (isValidCell(i, j)) {
if (grid[i][j].getAttribute("bomb")) {
count++;
}
}
}
}
return count;
}
// 处理空白格子
function handleEmptyCell(row, col) {
for (let i = row - 1; i <= row + 1; i++) {
for (let j = col - 1; j <= col + 1; j++) {
if (isValidCell(i, j)) {
let cell = grid[i][j];
if (!cell.hasAttribute("bomb") && cell.innerHTML === "") {
let count = countBombs(i, j);
cell.innerHTML = count;
cell.style.backgroundColor = "lightgray";
cell.onclick = null;
if (count === 0) {
handleEmptyCell(i, j);
}
}
}
}
}
}
// 验证格子是否有效
function isValidCell(row, col) {
return row >= 0 && row < gridSize && col >= 0 && col < gridSize;
}
};
以上代码创建了一个10x10的扫雷游戏网格,其中包含10个随机放置的炸弹。当玩家点击一个网格时,如果是炸弹格子,则游戏结束,否则会显示周围的炸弹数量,并将其颜色变为灰色。如果点击的是一个没有周围炸弹的空白格子,会递归地显示周围的格子。