如何将井字棋带ID的DOM元素映射为数组以实现胜利条件?
井字棋游戏:ID映射、状态改造与胜利条件实现
1. 单元格ID转数组索引
从单元格ID(如cell-1)提取数字后减1,就能直接得到0-8的数组索引,代码示例:
function handleCellClick(e) { const cellId = e.target.id; // 拆分ID获取数字部分,转成整数后减1 const index = parseInt(cellId.split('-')[1]) - 1; // 后续用index操作gameState数组 }
2. 用布尔值替换'x'/'o'表示玩家
初始化游戏状态数组,用null表示空单元格,true代表X,false代表O,落子逻辑同步调整:
// 游戏状态:null=空,true=X,false=O let gameState = new Array(9).fill(null); let currentPlayer = true; // X先手 function placeMark(index) { // 给对应索引设置当前玩家的布尔值 gameState[index] = currentPlayer; // 添加对应的CSS类 const targetCell = document.getElementById(`cell-${index + 1}`); targetCell.classList.add(currentPlayer ? 'x' : 'o'); // 切换玩家(取反布尔值) currentPlayer = !currentPlayer; }
3. 实现胜利条件检查
先定义所有可能的获胜索引组合,每次落子后检查当前玩家的标记是否匹配任意组合:
// 所有获胜的索引组合 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 checkWin(player) { return winningCombos.some(combo => { // 判断组合里的所有索引是否都是当前玩家的标记 return combo.every(index => gameState[index] === player); }); } // 完善点击事件处理 function handleCellClick(e) { const index = parseInt(e.target.id.split('-')[1]) - 1; // 跳过已落子的单元格 if (gameState[index] !== null) return; placeMark(index); // 注意:placeMark后currentPlayer已切换,所以当前落子的玩家是!currentPlayer const currentMarker = !currentPlayer; if (checkWin(currentMarker)) { alert(currentMarker ? 'X获胜!' : 'O获胜!'); resetGame(); // 调用重置函数 } } // 重置游戏的辅助函数 function resetGame() { gameState = new Array(9).fill(null); currentPlayer = true; // 清除所有单元格的X/O类 document.querySelectorAll('[id^="cell-"]').forEach(cell => { cell.classList.remove('x', 'o'); }); }
内容的提问来源于stack exchange,提问作者Amogh Amar
相关产品推荐
相关产品推荐

