You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vanilla JS 井字棋游戏胜负判断与玩家切换逻辑异常问题求助

Vanilla JS 井字棋游戏胜负判断与玩家切换逻辑异常问题求助

我最近一直在折腾原生JS(之前太依赖框架了),正在做一个简单的井字棋游戏,但卡在了胜负判断和玩家切换的逻辑上。下面是我的代码(hopefully it's not too long):

const GameBoard = (() => {
  const board = Array(9).fill("");
  const getBoard = () => board;
  const resetBoard = () => board.fill("");

  const setBoard = (symbol, index) =>
    board.forEach(() => (board[index] === "" ? (board[index] = symbol) : ""));

  const checkForWinner = () => {
    const winningCombinations = [
      [0, 1, 2], // Top row
      [3, 4, 5], // Middle row
      [6, 7, 8], // Bottom row
      [0, 3, 6], // Left column
      [1, 4, 7], // Middle column
      [2, 5, 8], // Right column
      [0, 4, 8], // Diagonal from top-left to bottom-right
      [2, 4, 6], // Diagonal from top-right to bottom-left
    ];

    for (const combo of winningCombinations) {
      const [a, b, c] = combo;

      if (
        getBoard()[a] &&
        getBoard()[a] === getBoard()[b] &&
        getBoard()[a] === getBoard()[c]
      ) {
        return true;
      }
    }

    return false;
  };

  return { checkForWinner, getBoard, resetBoard, setBoard };
})();

const players = () => {
  const activePlayers = [
    {
      name: "Player 1 (X)",
      symbol: "X",
      active: true,
    },
    {
      name: "Player 2 (O)",
      symbol: "O",
      active: false,
    },
  ];

  const getActivePlayer = () => activePlayers.find((player) => player.active);
  const switchPlayers = () =>
    activePlayers.forEach((player) => (player.active = !player.active));

  return { getActivePlayer, switchPlayers };
};

(() => {
  const gameBoardContainer = document.querySelector("#game-board");
  const { checkForWinner, getBoard, setBoard } = GameBoard;
  const { getActivePlayer, switchPlayers } = players();
  let button;

  for (let i = 0; i < getBoard().length; i++) {
    button = document.createElement("button");
    gameBoardContainer.appendChild(button);
  }

  document.querySelectorAll("button").forEach((button, index) => {
    button.addEventListener("click", () => {
      if (getBoard()[index] === "" && !checkForWinner()) {
        setBoard(getActivePlayer().symbol, index);
        button.textContent = getActivePlayer().symbol;
        switchPlayers();
      }

      if (checkForWinner()) {
        console.log(`${getActivePlayer().name} has won!`);
        return;
      }
    });
  });
})();
<div id="game-board"></div>

我的问题出在按钮元素的addEventListener逻辑里。胜负判断的逻辑似乎能正常工作,但当我用console.log打印获胜的活跃玩家时,显示的却是错误的用户。比如当所有格子都是X时,它会显示O赢了,反过来也是一样。我猜这和switchPlayers函数有关,但不确定具体哪里出问题了以及原因是什么。

有人能给点思路吗?谢谢...!

备注:内容来源于stack exchange,提问作者Lushmoney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:18:06