写一个可以在html中运行的扫雷游戏
时间: 2023-05-13 16:06:59 浏览: 246
扫雷游戏可以通过使用 JavaScript 和 HTML 进行编写实现。下面是一份简单的 HTML 代码示例:
```
<html>
<head>
<style>
table {
border-collapse: collapse;
}
td {
width: 30px;
height: 30px;
border: 1px solid black;
text-align: center;
}
</style>
</head>
<body>
<table id="minefield"></table>
<script>
const MINE = "💣";
const EMPTY = "⬜️";
function createMinefield(rowCount, columnCount, mineCount) {
const minefield = [];
for (let row = 0; row < rowCount; row++) {
minefield.push([]);
for (let column = 0; column < columnCount; column++) {
minefield[row].push(EMPTY);
}
}
let minePlaced = 0;
while (minePlaced < mineCount) {
const row = Math.floor(Math.random() * rowCount);
const column = Math.floor(Math.random() * columnCount);
if (minefield[row][column] !== MINE) {
minefield[row][column] = MINE;
minePlaced++;
}
}
return minefield;
}
function renderMinefield(minefield) {
const table = document.querySelector("#minefield");
table.innerHTML = "";
for (const row of minefield) {
const tr = document.createElement("tr");
for (const cell of row) {
const td = document.createElement("td");
td.textContent = cell;
tr.appendChild(td);
}
table.appendChild(tr);
}
}
const minefield = createMinefield(10, 10, 20);
renderMinefield(minefield);
</script>
</body>
</html>
```
这段代码实现了一个 10x10 的扫雷游戏,带有 20 个地雷。可以在 HTML 文件中直接运行,以在浏览器中体验扫雷游戏。