<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 &lt; 100; i++) {
  let cell = document.createElement('div');
  cell.classList.add('cell');
  board.appendChild(cell);
  cells.push(cell);
}

// plant mines
let plantedMines = 0;
while (plantedMines &lt; 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 =&gt; {
  cell.addEventListener('click', event =&gt; {
    if (cell.classList.contains('mine')) {
      alert('Game Over!');
    } else {
      cell.classList.add('clicked');
    }
  });
});
</code></pre>
  </script>
</body>
</html>
Play Minesweeper Game Online - HTML Code Example

原文地址: https://www.cveoy.top/t/topic/lma9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录