生成一个javaScript+html版的扫雷实例
下面是一个简单的JavaScript+HTML版的扫雷实例:
HTML部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>扫雷</title>
<style>
.tile {
width: 30px;
height: 30px;
border: 1px solid #ccc;
display: inline-block;
text-align: center;
font-size: 20px;
cursor: pointer;
background-color: #eee;
}
</style>
</head>
<body>
<h1>扫雷</h1>
<div id="gameboard"></div>
<script src="minesweeper.js"></script>
<script>
var game = new MinesweeperGame(10, 10, 10);
game.startGame();
</script>
</body>
</html>
JavaScript部分(minesweeper.js):
function MinesweeperGame(rows, cols, mines) {
this.rows = rows;
this.cols = cols;
this.mines = mines;
this.board = [];
}
MinesweeperGame.prototype.startGame = function() {
this.createBoard();
this.placeMines();
this.renderBoard();
};
MinesweeperGame.prototype.createBoard = function() {
for (var i = 0; i < this.rows; i++) {
this.board[i] = [];
for (var j = 0; j < this.cols; j++) {
this.board[i][j] = {
mine: false,
revealed: false,
adjacentMines: 0
};
}
}
};
MinesweeperGame.prototype.placeMines = function() {
var count = 0;
while (count < this.mines) {
var row = Math.floor(Math.random() * this.rows);
var col = Math.floor(Math.random() * this.cols);
if (!this.board[row][col].mine) {
this.board[row][col].mine = true;
count++;
}
}
};
MinesweeperGame.prototype.renderBoard = function() {
var gameboard = document.getElementById('gameboard');
gameboard.innerHTML = '';
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.cols; j++) {
var tile = document.createElement('div');
tile.className = 'tile';
tile.dataset.row = i;
tile.dataset.col = j;
tile.addEventListener('click', this.handleTileClick.bind(this));
gameboard.appendChild(tile);
}
gameboard.appendChild(document.createElement('br'));
}
};
MinesweeperGame.prototype.handleTileClick = function(event) {
var row = parseInt(event.target.dataset.row);
var col = parseInt(event.target.dataset.col);
if (this.board[row][col].mine) {
event.target.style.backgroundColor = 'red';
event.target.textContent = 'X';
alert('Game Over!');
} else {
var adjacentMines = this.countAdjacentMines(row, col);
event.target.style.backgroundColor = '#ddd';
event.target.textContent = adjacentMines;
this.board[row][col].revealed = true;
}
};
MinesweeperGame.prototype.countAdjacentMines = function(row, col) {
var count = 0;
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
if (row + i >= 0 && row + i < this.rows && col + j >= 0 && col + j < this.cols) {
if (this.board[row + i][col + j].mine) {
count++;
}
}
}
}
return count;
};
这个扫雷实例使用了一个MinesweeperGame对象来管理游戏。在startGame方法中,它创建了一个游戏板,放置地雷,并渲染游戏板。点击每个方块时,它会检查是否有地雷,如果有,游戏结束;如果没有,它会显示方块周围的地雷数量,并将方块标记为已揭示。countAdjacentMines方法用于计算方块周围的地雷数量
原文地址: https://www.cveoy.top/t/topic/iBBm 著作权归作者所有。请勿转载和采集!