用html写出扫雷游戏
时间: 2023-05-15 15:06:32 浏览: 197
html实现扫雷游戏
可以使用HTML、CSS和JavaScript来编写扫雷游戏。以下是一个简单的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>扫雷游戏</title>
<style>
.cell {
width: 20px;
height: 20px;
border: 1px solid #ccc;
display: inline-block;
text-align: center;
line-height: 20px;
font-size: 14px;
cursor: pointer;
}
.cell.mine {
background-color: red;
color: white;
}
.cell.revealed {
background-color: #eee;
cursor: default;
}
</style>
</head>
<body>
<script>
var rows = 10;
var cols = 10;
var mines = 10;
var board = [];
var gameOver = false;
function initBoard() {
for (var i = 0; i < rows; i++) {
board[i] = [];
for (var j = 0; j < cols; j++) {
board[i][j] = {
mine: false,
revealed: false,
flagged: false,
value: 0
};
}
}
var count = 0;
while (count < mines) {
var i = Math.floor(Math.random() * rows);
var j = Math.floor(Math.random() * cols);
if (!board[i][j].mine) {
board[i][j].mine = true;
count++;
}
}
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
if (!board[i][j].mine) {
var count = 0;
for (var ii = Math.max(0, i - 1); ii <= Math.min(rows - 1, i + 1); ii++) {
for (var jj = Math.max(0, j - 1); jj <= Math.min(cols - 1, j + 1); jj++) {
if (board[ii][jj].mine) {
count++;
}
}
}
board[i][j].value = count;
}
}
}
}
function revealCell(i, j) {
if (gameOver || board[i][j].revealed || board[i][j].flagged) {
return;
}
board[i][j].revealed = true;
if (board[i][j].mine) {
gameOver = true;
alert("游戏结束,你输了!");
return;
}
if (board[i][j].value == 0) {
for (var ii = Math.max(0, i - 1); ii <= Math.min(rows - 1, i + 1); ii++) {
for (var jj = Math.max(0, j - 1); jj <= Math.min(cols - 1, j + 1); jj++) {
revealCell(ii, jj);
}
}
}
}
function flagCell(i, j) {
if (gameOver || board[i][j].revealed) {
return;
}
board[i][j].flagged = !board[i][j].flagged;
renderBoard();
}
function renderBoard() {
var html = "";
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
var cell = board[i][j];
var className = "cell";
if (cell.revealed) {
className += " revealed";
if (cell.mine) {
className += " mine";
} else {
className += " value-" + cell.value;
}
} else if (cell.flagged) {
className += " flagged";
}
html += "<div class='" + className + "' onclick='revealCell(" + i + ", " + j + ")' oncontextmenu='flagCell(" + i + ", " + j + "); return false;'></div>";
}
html += "<br>";
}
document.body.innerHTML = html;
}
initBoard();
renderBoard();
</script>
</body>
</html>
```
这个代码使用了一个二维数组来表示扫雷游戏的棋盘,每个元素包含了一个地雷标记、是否被翻开、是否被标记、以及周围地雷的数量。使用递归算法来翻开周围的方块,直到遇到有数字的方块或者边界。右键点击方块可以标记或取消标记。
阅读全文