扫雷是一款经典的桌面游戏,玩家需要在一个网格中找出所有非雷区格子,同时避开隐藏的雷。下面是一个简单的JavaScript扫雷游戏的实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Minesweeper</title>
<style>
.cell { width: 20px; height: 20px; border: 1px solid #ccc; display: inline-block; margin: 2px; text-align: center; line-height: 20px; }
.mine { background-color: red; }
.number { background-color: #ddd; }
</style>
</head>
<body>
<div id="game-board"></div>
<script src="minesweeper.js"></script>
</body>
</html>const ROWS = 10;
const COLS = 10;
const MINES = 10;
function createBoard() {
const board = document.getElementById('game-board');
let html = '';
for (let row = 0; row < ROWS; row++) {
html += '<div class="row">';
for (let col = 0; col < COLS; col++) {
html += `<div class="cell" data-row="${row}" data-col="${col}"></div>`;
}
html += '</div>';
}
board.innerHTML = html;
}
function placeMines() {
const cells = document.querySelectorAll('.cell');
let minesPlaced = 0;
while (minesPlaced < MINES) {
const index = Math.floor(Math.random() * cells.length);
const cell = cells[index];
if (!cell.classList.contains('mine')) {
cell.classList.add('mine');
minesPlaced++;
}
}
}
function calculateNumbers() {
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => {
if (!cell.classList.contains('mine')) {
const row = cell.getAttribute('data-row');
const col = cell.getAttribute('data-col');
let minesNearby = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const newRow = parseInt(row) + i;
const newCol = parseInt(col) + j;
if (newRow >= 0 && newRow < ROWS && newCol >= 0 && newCol < COLS) {
const neighbor = document.querySelector(`.cell[data-row="${newRow}"][data-col="${newCol}"]`);
if (neighbor.classList.contains('mine')) {
minesNearby++;
}
}
}
}
if (minesNearby > 0) {
cell.classList.add('number');
cell.textContent = minesNearby;
}
}
});
}
function revealCell(event) {
const cell = event.target;
if (cell.classList.contains('mine')) {
alert('Game Over!');
resetGame();
} else {
cell.classList.add('revealed');
if (cell.textContent === '') {
const row = cell.getAttribute('data-row');
const col = cell.getAttribute('data-col');
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const newRow = parseInt(row) + i;
const newCol = parseInt(col) + j;
if (newRow >= 0 && newRow < ROWS && newCol >= 0 && newCol < COLS) {
const neighbor = document.querySelector(`.cell[data-row="${newRow}"][data-col="${newCol}"]`);
revealCell({ target: neighbor });
}
}
}
}
}
}
function resetGame() {
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => {
cell.classList.remove('mine', 'number', 'revealed');
cell.textContent = '';
});
placeMines();
calculateNumbers();
}
createBoard();
placeMines();
calculateNumbers();
document.getElementById('game-board').addEventListener('click', revealCell);这个简单的扫雷游戏实现了一个基本的扫雷逻辑,可以根据需要进一步扩展功能,比如添加计时器、记录最佳成绩等。
没有搜到相关的文章