JavaScript井字棋:对象内数组与获胜组合数组对比问题排查
井字棋获胜判断问题修复方案
核心问题:数组直接比较无效
你在checkGameOver里用_gameBoardObj.gameboard == [1, 1, 1, "", "", "", "", "", ""]完全行不通。数组是引用类型,==或===只会对比两个数组是否指向内存中的同一个对象,不会检查数组内容是否一致。
修复步骤
1. 定义所有获胜组合
先把井字棋所有可能的获胜位置整理成二维数组:
const winningCombos = [ [0,1,2], [3,4,5], [6,7,8], // 横向获胜 [0,3,6], [1,4,7], [2,5,8], // 纵向获胜 [0,4,8], [2,4,6] // 斜向获胜 ];
2. 编写获胜检查工具函数
写一个函数判断某玩家是否占据了任意一组获胜位置:
function checkWin(player) { return winningCombos.some(combo => { // 检查当前组合的所有位置是否都属于同一个玩家 return combo.every(index => _gameBoardObj.gameboard[index] === player); }); }
3. 重构checkGameOver函数
用上面的工具函数实现完整的胜负判断,还可以加上平局检测:
function checkGameOver() { if (checkWin(1)) { // 检查X玩家(你代码中用1代表X) alert("X获胜,游戏结束!"); } else if (checkWin(0)) { // 后续扩展O玩家时用这个判断 alert("O获胜,游戏结束!"); } else if (_gameBoardObj.gameboard.every(tile => tile !== "")) { alert("平局,游戏结束!"); // 所有格子填满但无人获胜时触发 } }
4. 修复renderBoard的循环错误
你写的嵌套for循环用了同一个变量i,外层循环会被内层完全覆盖,直接简化成单个循环即可:
function renderBoard() { tiles.forEach((tile, index) => { if (_gameBoardObj.gameboard[index] === 0) { tile.textContent = "O"; } else if (_gameBoardObj.gameboard[index] === 1) { tile.textContent = "X"; } else { tile.textContent = ""; } }); }
完整修复后的代码
const tiles = document.querySelectorAll('.tile'); const _gameBoardObj = { gameboard: ["", "", "", "", "", "", "", "", ""], }; const winningCombos = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]; function renderBoard() { tiles.forEach((tile, index) => { if (_gameBoardObj.gameboard[index] === 0) { tile.textContent = "O"; } else if (_gameBoardObj.gameboard[index] === 1) { tile.textContent = "X"; } else { tile.textContent = ""; } }); } function chooseTile() { tiles.forEach((tile, index) => { tile.addEventListener('click', () => { if (_gameBoardObj.gameboard[index] == "") { _gameBoardObj.gameboard[index] = 1; renderBoard(); checkGameOver(); // 这里可以添加AI走O的逻辑,比如调用placeO()函数 } }) }) } function checkWin(player) { return winningCombos.some(combo => { return combo.every(index => _gameBoardObj.gameboard[index] === player); }); } function checkGameOver() { if (checkWin(1)) { alert("X获胜,游戏结束!"); } else if (checkWin(0)) { alert("O获胜,游戏结束!"); } else if (_gameBoardObj.gameboard.every(tile => tile !== "")) { alert("平局,游戏结束!"); } } chooseTile();
CSS和HTML部分保持你原有的代码即可。
内容的提问来源于stack exchange,提问作者JF123
相关产品推荐
相关产品推荐

