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

井字棋开发问题:关联gameBoard数组与gridItems及实现获胜检测

解决井字棋gameBoard数组与网格项的匹配问题

核心逻辑

让网格项的索引和gameBoard数组的索引一一绑定,点击网格时直接更新对应位置的数组值,后续获胜检测完全基于这个数组实现,既保证数据和UI同步,又不会破坏原有网格功能。

具体实现代码

// 初始化游戏数据与DOM元素
const gridItems = document.querySelectorAll('.grid-item');
const gameBoard = Array(9).fill(null); // 对应9个格子的数组,初始为空
let currentPlayer = 'X'; // 当前玩家标记

// 绑定网格点击事件,关联数组与UI
gridItems.forEach((item, index) => {
  item.addEventListener('click', () => {
    // 跳过已填充的格子
    if (gameBoard[index] !== null) return;

    // 更新数组与UI显示
    gameBoard[index] = currentPlayer;
    item.textContent = currentPlayer;

    // 检测获胜或平局
    const winner = checkWinner();
    if (winner) {
      showResult(`玩家 ${winner} 获胜!`);
      resetGame();
      return;
    }

    // 检测平局
    if (!gameBoard.includes(null)) {
      showResult('平局!');
      resetGame();
      return;
    }

    // 切换玩家
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
  });
});

// 获胜检测函数
function checkWinner() {
  // 预定义所有获胜组合
  const winPatterns = [
    [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 (const pattern of winPatterns) {
    const [a, b, c] = pattern;
    if (gameBoard[a] && gameBoard[a] === gameBoard[b] && gameBoard[a] === gameBoard[c]) {
      return gameBoard[a];
    }
  }
  return null;
}

// 结果展示函数(可替换成你需要的页面元素展示逻辑)
function showResult(text) {
  // 示例:用弹窗展示,也可以修改为操作页面DOM元素显示
  alert(text);
}

// 重置游戏函数
function resetGame() {
  gameBoard.fill(null);
  gridItems.forEach(item => {
    item.textContent = '';
  });
  currentPlayer = 'X';
}

关键注意点

  • 确保网格项数量和gameBoard数组长度一致(都是9个),索引对应准确
  • 点击事件中必须判断格子是否已填充,避免重复修改数据和UI
  • 玩家切换逻辑可按需调整,比如加入AI玩家时替换成AI落子逻辑

内容的提问来源于stack exchange,提问作者Jay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:10:40