Play Minesweeper Game Online - HTML Code Example
<html>
<head>
<title>Minesweeper</title>
<style>
.board {
display: flex;
flex-wrap: wrap;
width: 400px;
height: 400px;
margin: 0 auto;
}
.cell {
width: 40px;
height: 40px;
border: 1px solid black;
background-color: #ccc;
text-align: center;
line-height: 40px;
font-size: 30px;
}
.cell.clicked {
background-color: #fff;
}
.cell.mine {
background-color: #f00;
}
</style>
</head>
<body>
<h1>Minesweeper</h1>
<div class='board'></div>
<script>
// create board
const board = document.querySelector('.board');
let mines = 10;
let cells = [];
<pre><code>// create cells
for (let i = 0; i < 100; i++) {
let cell = document.createElement('div');
cell.classList.add('cell');
board.appendChild(cell);
cells.push(cell);
}
// plant mines
let plantedMines = 0;
while (plantedMines < mines) {
let randomIndex = Math.floor(Math.random() * cells.length);
if (!cells[randomIndex].classList.contains('mine')) {
cells[randomIndex].classList.add('mine');
plantedMines++;
}
}
// add click event to cells
cells.forEach(cell => {
cell.addEventListener('click', event => {
if (cell.classList.contains('mine')) {
alert('Game Over!');
} else {
cell.classList.add('clicked');
}
});
});
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lma9 著作权归作者所有。请勿转载和采集!