帮我用html和js写一个扫雷小游戏
时间: 2023-05-26 19:01:41 浏览: 130
当然可以!以下是一个基本的扫雷小游戏示例:
HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<title>Minesweeper</title>
<style>
button {
width: 30px;
height: 30px;
background-color: #ddd;
border: 1px solid #999;
font-weight: bold;
font-size: 20px;
color: #444;
margin: 1px;
padding: 0;
outline: none;
}
button[data-mine="true"] {
background-color: red;
}
button.revealed {
background-color: #fff;
border-color: #ccc;
color: #000;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="minesweeper.js"></script>
</body>
</html>
```
JavaScript 代码:
```
var container = document.getElementById("container");
var board = [];
function generateBoard(width, height, mines) {
// 初始化棋盘数组
for(var i=0; i<height; i++) {
board[i] = [];
for(var j=0; j<width; j++) {
board[i][j] = {revealed: false, mine: false, value: 0};
}
}
// 在棋盘上随机放置地雷
var count = 0;
while(count < mines) {
var x = Math.floor(Math.random() * width);
var y = Math.floor(Math.random() * height);
if(!board[y][x].mine) {
board[y][x].mine = true;
count++;
// 更新周围方格的数值
for(var i=y-1; i<=y+1; i++) {
for(var j=x-1; j<=x+1; j++) {
if(i>=0 && j>=0 && i<height && j<width && !(i===y && j===x)) {
board[i][j].value++;
}
}
}
}
}
}
function reveal(x, y) {
if(board[y][x].mine) {
// 点击到地雷,游戏失败
board.forEach(row => {
row.forEach(cell => {
if(cell.mine) {
cell.revealed = true;
}
});
});
drawBoard();
alert("You Lose!");
} else if(!board[y][x].revealed) {
// 没有点击到地雷,且当前方格未被打开
board[y][x].revealed = true;
if(board[y][x].value === 0) {
// 如果当前方格周围没有雷,递归打开相邻方格
for(var i=y-1; i<=y+1; i++) {
for(var j=x-1; j<=x+1; j++) {
if(i>=0 && j>=0 && i<board.length && j<board[0].length && !(i===y && j===x)) {
reveal(j, i);
}
}
}
}
drawBoard();
checkWin();
}
}
function checkWin() {
var unrevealedCount = 0;
board.forEach(row => {
row.forEach(cell => {
if(!cell.revealed) {
unrevealedCount++;
}
});
});
if(unrevealedCount === 0) {
// 棋盘上没有未打开的方格,游戏胜利
board.forEach(row => {
row.forEach(cell => {
if(cell.mine) {
cell.revealed = true;
}
});
});
drawBoard();
alert("You Win!");
}
}
function drawBoard() {
container.innerHTML = "";
board.forEach(row => {
var rowEl = document.createElement("div");
rowEl.style.display = "flex";
rowEl.style.flexFlow = "row";
row.forEach(cell => {
var buttonEl = document.createElement("button");
buttonEl.dataset.mine = cell.mine;
buttonEl.classList.toggle("revealed", cell.revealed);
if(cell.revealed) {
if(cell.mine) {
buttonEl.innerText = "*";
} else {
buttonEl.innerText = cell.value;
}
} else {
buttonEl.addEventListener("click", () => {
reveal(row.indexOf(cell), board.indexOf(row));
});
buttonEl.innerText = "-";
}
rowEl.appendChild(buttonEl);
});
container.appendChild(rowEl);
});
}
// 开始游戏
generateBoard(10, 10, 10);
drawBoard();
```
运行 HTML 文件,就能在浏览器中玩扫雷小游戏了!
阅读全文