<!DOCTYPE html> <html> <head> <title>扫雷游戏</title> <style> .cell { width: 20px; height: 20px; border: 1px solid #ccc; display: inline-block; text-align: center; vertical-align: middle; background-color: #eee; font-weight: bold; cursor: pointer; } </style> </head> <body> <h1>扫雷游戏</h1> <div id="board"></div> <script> var rows = 10; var cols = 10; var mineCount = 10; var board = []; var gameOver = false; function createBoard() { var boardElement = document.getElementById('board'); for (var i = 0; i < rows; i++) { var row = []; for (var j = 0; j < cols; j++) { var cell = document.createElement('div'); cell.className = 'cell'; cell.setAttribute('data-row', i); cell.setAttribute('data-col', j); cell.addEventListener('click', cellClick); boardElement.appendChild(cell); row.push({ element: cell, hasMine: false, revealed: false }); } board.push(row); boardElement.appendChild(document.createElement('br')); } } function initMines() { var count = 0; while (count < mineCount) { var row = Math.floor(Math.random() * rows); var col = Math.floor(Math.random() * cols); if (!board[row][col].hasMine) { board[row][col].hasMine = true; count++; } } } function cellClick(event) { if (gameOver) { return; } var cell = event.target; var row = parseInt(cell.getAttribute('data-row')); var col = parseInt(cell.getAttribute('data-col')); if (board[row][col].hasMine) { gameOver = true; cell.style.backgroundColor = 'red'; alert('Game Over'); } else { revealCell(row, col); } } function revealCell(row, col) { var cell = board[row][col].element; if (board[row][col].revealed) { return; } board[row][col].revealed = true; cell.style.backgroundColor = '#ddd'; var mineCount = countAdjacentMines(row, col); if (mineCount > 0) { cell.innerText = mineCount; } else { revealAdjacentCells(row, col); } } function countAdjacentMines(row, col) { var count = 0; for (var i = Math.max(0, row - 1); i <= Math.min(rows -1, row + 1); i++) { for (var j = Math.max(0, col - 1); j <= Math.min(cols - 1, col + 1); j++) { if (board[i][j].hasMine) { count++; } } } return count; } function revealAdjacentCells(row, col) { for (var i = Math.max(0, row - 1); i <= Math.min(rows - 1, row + 1); i++) { for (var j = Math.max(0, col - 1); j <= Math.min(cols - 1, col + 1); j++) { if (!board[i][j].hasMine && !board[i][j].revealed) { revealCell(i, j); } } } } function initGame() { createBoard(); initMines(); } initGame(); </script> </body> </html>
|