扫雷游戏是一种单人电脑游戏,玩家需要在一个网格中找出所有非雷区格子,并且避免触雷。以下是一个简单的JavaScript实现扫雷游戏的示例代码:
以下是一个简单的HTML和JavaScript实现的扫雷游戏:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Minesweeper</title>
<style>
.grid {
display: grid;
grid-template-columns: repeat(10, 30px);
gap: 2px;
}
.cell {
width: 30px;
height: 30px;
background-color: #ddd;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="game" class="grid"></div>
<script>
const gridSize = 10;
const mineCount = 10;
const gameGrid = document.getElementById('game');
let mines = [];
let revealedCells = [];
function createGrid() {
for (let i = 0; i < gridSize * gridSize; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.addEventListener('click', () => revealCell(i));
gameGrid.appendChild(cell);
}
}
function placeMines() {
for (let i = 0; i < mineCount; i++) {
let randomIndex;
do {
randomIndex = Math.floor(Math.random() * (gridSize * gridSize));
} while (mines.includes(randomIndex));
mines.push(randomIndex);
}
}
function revealCell(index) {
if (mines.includes(index)) {
alert('Game Over! You hit a mine.');
resetGame();
return;
}
const cell = gameGrid.children[index];
cell.textContent = getAdjacentMines(index);
cell.style.backgroundColor = '#fff';
revealedCells.push(index);
if (revealedCells.length === gridSize * gridSize - mineCount) {
alert('Congratulations! You won!');
resetGame();
}
}
function getAdjacentMines(index) {
let count = 0;
const row = Math.floor(index / gridSize);
const col = index % gridSize;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const newRow = row + i;
const newCol = col + j;
if (newRow >= 0 && newRow < gridSize && newCol >= 0 && newCol < gridSize) {
const adjacentIndex = newRow * gridSize + newCol;
if (mines.includes(adjacentIndex)) {
count++;
}
}
}
}
return count > 0 ? count : '';
}
function resetGame() {
mines = [];
revealedCells = [];
gameGrid.innerHTML = '';
createGrid();
placeMines();
}
createGrid();
placeMines();
</script>
</body>
</html>
通过以上代码和解释,你可以了解扫雷游戏的基本实现和相关概念。如果有更多具体问题,欢迎继续提问!
云+社区技术沙龙[第5期]
云+社区技术沙龙[第8期]
“中小企业”在线学堂
云+社区技术沙龙[第25期]
企业创新在线学堂
2022vivo开发者大会
云+社区技术沙龙[第9期]
云+社区沙龙online[数据工匠]
云+社区技术沙龙[第12期]
云+社区沙龙online[新技术实践]