Skip to content

Web实现井字棋游戏:JavaScript DOM基础与实例教程

井字棋(Tic-Tac-Toe)是一款经典的两人对战游戏,适合作为学习JavaScript DOM操作的实践项目。本文将通过一个简单的实例,介绍如何使用JavaScript和DOM API来实现一个井字棋游戏,并讲解相关的JavaScript DOM基础知识。

JavaScript DOM基础

DOM(Document Object Model)是HTML和XML文档的编程接口。在JavaScript中,DOM提供了一种结构化的方式来表示和操作网页内容。通过DOM,我们可以获取元素、修改样式、绑定事件等。

创建HTML结构

首先,我们需要创建一个包含游戏板和结果显示的HTML结构。

html
<div class="board">
  <!-- 游戏格子 -->
  <div class="cell"></div>
  <!-- ... 其他格子 ... -->
</div>
<div id="result"></div>

编写JavaScript逻辑

初始化游戏

在JavaScript中,我们首先定义游戏板的状态、玩家当前回合以及游戏是否结束的状态。

javascript
const board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameEnded = false;

事件绑定

为每个游戏格子绑定点击事件,以便在玩家点击时更新游戏状态。

javascript
const cells = document.querySelectorAll(".cell");
cells.forEach((cell, index) => {
  cell.addEventListener("click", () => updateGameState(index));
});

更新游戏状态

定义updateGameState函数来处理玩家的每一步操作,包括更新棋盘状态、检查胜利条件、切换玩家回合以及在适当的时候结束游戏。

javascript
// ... 更新棋盘逻辑 ...
    function updateGameState(cellIndex) {
      if (!gameEnded && board[cellIndex] === "") {
        board[cellIndex] = currentPlayer;
        renderBoard();
        if (checkWin(currentPlayer)) {
          endGame("Player " + currentPlayer + " wins!");
        } else if (checkDraw()) {
          endGame("It's a draw!");
        } else {
          currentPlayer = currentPlayer === "X" ? "O" : "X";
          if (currentPlayer === "O") {
            setTimeout(makeComputerMove, 500);
          }
        }
      }
    }

检查胜利条件和平局

在每一步操作后,使用checkWincheckDraw函数来检查是否有玩家获胜或游戏是否平局。

javascript
// ... 检查胜利逻辑 ...
    function checkWin(player) {
      const winningCombinations = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
      ];

      for (let i = 0; i < winningCombinations.length; i++) {
        const [a, b, c] = winningCombinations[i];
        if (board[a] === player && board[b] === player && board[c] === player) {
          return true;
        }
      }
      return false;
    }

// ... 检查平局逻辑 ...
    function checkDraw() {
      return board.every((cell) => cell !== "");
    }

电脑AI移动

在玩家为"O"时,电脑AI需要进行自动移动。makeComputerMove函数负责实现这一逻辑。

javascript
// ... 电脑AI移动逻辑 ...
    function makeComputerMove() {
      const emptyCells = board.reduce((acc, cell, index) => {
        if (cell === "") {
          acc.push(index);
        }
        return acc;
      }, []);
      if (emptyCells.length > 0) {
        const randomIndex = Math.floor(Math.random() * emptyCells.length);
        const computerMove = emptyCells[randomIndex];
        updateGameState(computerMove);
      }
    }

渲染棋盘

使用renderBoard函数将棋盘状态更新到页面上。

javascript
// ... 渲染棋盘逻辑 ...
    function renderBoard() {
      for (let i = 0; i < cells.length; i++) {
        cells[i].textContent = board[i];
      }
    }

重置游戏

提供一个重置游戏的函数,以便玩家可以重新开始新游戏。

javascript
// ... 重置游戏逻辑 ...
    function resetGame() {
      board.fill("");
      currentPlayer = "X";
      gameEnded = false;
      resultElement.textContent = "";
      renderBoard();
    }

全部代码

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>洛可可白😁井字棋游戏</title>

    <style>
      .board {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-template-rows: repeat(3, 1fr);
        gap: 5px;
        width: 300px;
        height: 300px;
        margin: 0 auto;
        border: 1px solid #ccc;
        padding: 5px;
      }

      .cell {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: bold;
        background-color: #f2f2f2;
        cursor: pointer;
      }

      #result {
        text-align: center;
        font-size: 24px;
        margin-top: 20px;
      }
    </style>
  </head>

  <body>
    <div class="board">
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
    </div>
    <div id="result"></div>
  </body>

  <script>
    const board = ["", "", "", "", "", "", "", "", ""];
    const cells = document.querySelectorAll(".cell");
    const resultElement = document.getElementById("result");
    let currentPlayer = "X";
    let gameEnded = false;

    function updateGameState(cellIndex) {
      if (!gameEnded && board[cellIndex] === "") {
        board[cellIndex] = currentPlayer;
        renderBoard();
        if (checkWin(currentPlayer)) {
          endGame("Player " + currentPlayer + " wins!");
        } else if (checkDraw()) {
          endGame("It's a draw!");
        } else {
          currentPlayer = currentPlayer === "X" ? "O" : "X";
          if (currentPlayer === "O") {
            setTimeout(makeComputerMove, 500);
          }
        }
      }
    }

    function checkWin(player) {
      const winningCombinations = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
      ];

      for (let i = 0; i < winningCombinations.length; i++) {
        const [a, b, c] = winningCombinations[i];
        if (board[a] === player && board[b] === player && board[c] === player) {
          return true;
        }
      }
      return false;
    }

    function checkDraw() {
      return board.every((cell) => cell !== "");
    }

    function endGame(message) {
      gameEnded = true;
      resultElement.textContent = message;
    }

    function makeComputerMove() {
      const emptyCells = board.reduce((acc, cell, index) => {
        if (cell === "") {
          acc.push(index);
        }
        return acc;
      }, []);
      if (emptyCells.length > 0) {
        const randomIndex = Math.floor(Math.random() * emptyCells.length);
        const computerMove = emptyCells[randomIndex];
        updateGameState(computerMove);
      }
    }

    function renderBoard() {
      for (let i = 0; i < cells.length; i++) {
        cells[i].textContent = board[i];
      }
    }

    function resetGame() {
      board.fill("");
      currentPlayer = "X";
      gameEnded = false;
      resultElement.textContent = "";
      renderBoard();
    }

    cells.forEach((cell, index) => {
      cell.addEventListener("click", () => updateGameState(index));
    });

    resetGame();
  </script>
</html>