JavaScriptでマインスイーパを作成してください。ただしcanvasは使用せず、爆弾や数字などのすべての要素はbutton要素を使って表してください。なお...

❓ Prompt

💬 Answer

マインスイーパーをJavaScriptで作成することはできます。以下に、canvasを使用せずにbutton要素を使ってマインスイーパーを作成する基本的なコードを示します。このコードは8x8のマス目で、爆弾の数は16個です。変数を使用してマス目のサイズや爆弾の数を変更できるようにしています。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minesweeper</title>
    <style>
        .board {
            display: grid;
            grid-template-columns: repeat(8, 40px);
            gap: 2px;
        }
        .cell {
            width: 40px;
            height: 40px;
            text-align: center;
            vertical-align: middle;
            font-size: 18px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div class="board" id="board"></div>

    <script>
        const boardSize = 8;
        const totalBombs = 16;

        function createBoard() {
            const board = document.getElementById('board');
            for (let i = 0; i < boardSize; i++) {
                for (let j = 0; j < boardSize; j++) {
                    const cell = document.createElement('button');
                    cell.classList.add('cell');
                    cell.setAttribute('data-row', i);
                    cell.setAttribute('data-col', j);
                    board.appendChild(cell);
                }
            }
        }

        function placeBombs() {
            const cells = document.querySelectorAll('.cell');
            const bombIndices = Array.from({ length: boardSize * boardSize }, (_, index) => index);
            for (let i = 0; i < totalBombs; i++) {
                const randomIndex = Math.floor(Math.random() * bombIndices.length);
                const bombCellIndex = bombIndices.splice(randomIndex, 1)[0];
                cells[bombCellIndex].classList.add('bomb');
            }
        }

        function initializeGame() {
            createBoard();
            placeBombs();
        }

        initializeGame();
    </script>
</body>
</html>

このコードは、8x8のボードを表示し、16個の爆弾をランダムに配置します。セルが爆弾である場合、そのセルに"bomb"クラスが追加されます。必要に応じてこの基本的なコードを拡張して、マインスイーパーゲームを完成させることができます。

initializeGame関数を実装してゲームを完成させてください

❓ Prompt

💬 Answer

もちろんです。以下が、完全なマインスイーパーゲームを実装したコードです。このコードは、8x8のボードに16個の爆弾を配置し、プレイヤーがセルをクリックした際に爆弾があるかどうかを確認し、爆弾の数を表示します。爆弾があるセルをクリックするとゲームオーバーになります。

` <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minesweeper</title>
    <style>
        .board {
            display: grid;
            grid-template-columns: repeat(8, 40px);
            gap: 2px;
        }
        .cell {
            width: 40px;
            height: 40px;
            text-align: center;
            vertical-align: middle;
            font-size: 18px;
            border: 1px solid #ccc;
        }
        .bomb {
            background-color: red;
            color: white;
        }
    </style>
</head>
<body>
    <div class="board" id="board"></div>

    <script>
        const boardSize = 8;
        const totalBombs = 16;

        function createBoard() {
            const board = document.getElementById('board');
            for (let i = 0; i < boardSize; i++) {
                for (let j = 0; j < boardSize; j++) {
                    const cell = document.createElement('button');
                    cell.classList.add('cell');
                    cell.setAttribute('data-row', i);
                    cell.setAttribute('data-col', j);
                    board.appendChild(cell);
                }
            }
        }

        function placeBombs() {
            const cells = document.querySelectorAll('.cell');
            const bombIndices = Array.from({ length: boardSize * boardSize }, (_, index) => index);
            for (let i = 0; i < totalBombs; i++) {
                const randomIndex = Math.floor(Math.random() * bombIndices.length);
                const bombCellIndex = bombIndices.splice(randomIndex, 1)[0];
                cells[bombCellIndex].classList.add('bomb');
            }
        }

        function initializeGame() {
            createBoard();
            placeBombs();
            const cells = document.querySelectorAll('.cell');
            cells.forEach(cell => {
                cell.addEventListener('click', handleCellClick);
            });
        }

        function countBombsAround(cell) {
            const row = parseInt(cell.getAttribute('data-row'));
            const col = parseInt(cell.getAttribute('data-col'));
            let bombCount = 0;
            for (let i = row - 1; i <= row + 1; i++) {
                for (let j = col - 1; j <= col + 1; j++) {
                    const neighbor = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
                    if (neighbor && neighbor.classList.contains('bomb')) {
                        bombCount++;
                    }
                }
            }
            return bombCount;
        }

        function handleCellClick(event) {
            const clickedCell = event.target;
            if (clickedCell.classList.contains('bomb')) {
                gameOver();
            } else {
                const bombCount = countBombsAround(clickedCell);
                clickedCell.textContent = bombCount || '';
                clickedCell.disabled = true;
            }
        }

        function gameOver() {
            const cells = document.querySelectorAll('.cell');
            cells.forEach(cell => {
                cell.disabled = true;
                if (cell.classList.contains('bomb')) {
                    cell.textContent = '💣';
                }
            });
            alert('Game Over! Try again.');
        }

        initializeGame();
    </script>
</body>
</html>

このコードは、ボード上の各セルに対してクリックイベントをリッスンし、爆弾の数をカウントして表示します。セルが爆弾である場合、ゲームオーバーとしてアラートが表示されます。

インデントを1スペースに変換してください

❓ Prompt

💬 Answer

もちろんです。以下が、インデントが1スペースに変更されたコードです:

` <!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Minesweeper</title>
  <style>
   .board {
    display: grid;
    grid-template-columns: repeat(8, 40px);
    gap: 2px;
   }
   .cell {
    width: 40px;
    height: 40px;
    text-align: center;
    vertical-align: middle;
    font-size: 18px;
    border: 1px solid #ccc;
   }
   .bomb {
    background-color: red;
    color: white;
   }
  </style>
 </head>
 <body>
  <div class="board" id="board"></div>

  <script>
   const boardSize = 8;
   const totalBombs = 16;

   function createBoard() {
    const board = document.getElementById('board');
    for (let i = 0; i < boardSize; i++) {
     for (let j = 0; j < boardSize; j++) {
      const cell = document.createElement('button');
      cell.classList.add('cell');
      cell.setAttribute('data-row', i);
      cell.setAttribute('data-col', j);
      board.appendChild(cell);
     }
    }
   }

   function placeBombs() {
    const cells = document.querySelectorAll('.cell');
    const bombIndices = Array.from({ length: boardSize * boardSize }, (_, index) => index);
    for (let i = 0; i < totalBombs; i++) {
     const randomIndex = Math.floor(Math.random() * bombIndices.length);
     const bombCellIndex = bombIndices.splice(randomIndex, 1)[0];
     cells[bombCellIndex].classList.add('bomb');
    }
   }

   function initializeGame() {
    createBoard();
    placeBombs();
    const cells = document.querySelectorAll('.cell');
    cells.forEach(cell => {
     cell.addEventListener('click', handleCellClick);
    });
   }

   function countBombsAround(cell) {
    const row = parseInt(cell.getAttribute('data-row'));
    const col = parseInt(cell.getAttribute('data-col'));
    let bombCount = 0;
    for (let i = row - 1; i <= row + 1; i++) {
     for (let j = col - 1; j <= col + 1; j++) {
      const neighbor = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
      if (neighbor && neighbor.classList.contains('bomb')) {
       bombCount++;
      }
     }
    }
    return bombCount;
   }

   function handleCellClick(event) {
    const clickedCell = event.target;
    if (clickedCell.classList.contains('bomb')) {
     gameOver();
    } else {
     const bombCount = countBombsAround(clickedCell);
     clickedCell.textContent = bombCount || '';
     clickedCell.disabled = true;
    }
   }

   function gameOver() {
    const cells = document.querySelectorAll('.cell');
    cells.forEach(cell => {
     cell.disabled = true;
     if (cell.classList.contains('bomb')) {
      cell.textContent = '💣';
     }
    });
    alert('Game Over! Try again.');
   }

   initializeGame();
  </script>
 </body>
</html>

このように、すべてのコード行が1スペースのインデントで整形されています。

ゲームをリセットするボタンを作成してください