
本文将深入探讨如何在javaScript实现的井字棋游戏中准确判断平局。针对现有代码中平局检测逻辑的不足,我们将引入一个已填充格子计数器,并详细讲解如何修改 `getwinner` 函数以在所有格子被填充且无胜者时宣布平局,从而完善游戏体验。
在开发基于javascript的井字棋(Tic-Tac-Toe)游戏时,正确处理游戏结束的各种情况至关重要,这包括玩家获胜和游戏平局。尽管很多实现能够成功判断出胜者,但在所有格子都被填充且没有玩家获胜时,准确宣布平局往往成为一个挑战。本文将针对这一常见问题,提供一个清晰且易于实现的解决方案。
井字棋游戏状态与核心逻辑回顾
首先,我们回顾一下井字棋游戏的核心状态变量和关键函数:
- board: 一个包含9个元素的数组,代表井字棋的九个格子。初始值为 0 表示空,1 表示玩家X,-1 表示玩家O。
- turn: 当前玩家的回合,1 或 -1。
- winner: 游戏结果,NULL 表示游戏进行中,1 或 -1 表示对应玩家获胜,’T’ 表示平局。
- COMBOS: 预定义的获胜组合数组。
- handleClick(Event): 处理用户点击事件,更新 board 状态,切换玩家回合,并调用 getWinner()。
- getWinner(): 检查当前 board 状态,判断是否有玩家获胜,或者游戏是否平局。
- renderMessage(): 根据 winner 状态显示相应的游戏信息。
原始代码中的 getWinner 函数在判断胜者方面表现良好,但平局判断存在逻辑缺陷。尝试在循环中或循环外过早地返回 ‘T’ 会导致游戏在仅点击一次后就结束,因为此时游戏既没有胜者,也不是平局,但逻辑却强制返回了平局状态。
立即学习“Java免费学习笔记(深入)”;
问题分析:原始 getWinner 函数的局限性
原始的 getWinner 函数结构如下:
function getWinner() { for (let i = 0; i < COMBOS.length; i++) { if (Math.abs(board[COMBOS[i][0]] + board[COMBOS[i][1]] + board[COMBOS[i][2]]) === 3) { return board[COMBOS[i][0]]; // 发现胜者 } else if (board.includes(null)) { // 这一行是问题所在 return null; // 游戏仍在进行 } } // return 'T'; // 在这里返回也会导致问题 }
这里存在两个主要问题:
- board.includes(null) 的误用: 游戏板 board 初始化时使用的是 0 来表示空位,而不是 null。因此,board.includes(null) 将永远返回 false,导致此条件分支从未被执行。正确的检查空位方式应该是 board.includes(0)。
- 平局判断的时机: else if (board.includes(null))(即使改为 board.includes(0))放置在循环内部是不正确的。如果在检查第一个获胜组合时没有发现胜者,并且板上还有空位,它会立即返回 null,而不会继续检查后续的获胜组合。这可能导致即使存在获胜者,游戏也提前被判定为仍在进行中。
平局的定义是:所有格子都被填充,但没有玩家获胜。这意味着我们应该在所有获胜组合都被检查完毕且没有发现胜者之后,再去判断是否所有格子都已被填充。
解决方案:引入已填充格子计数器
为了准确判断平局,我们将引入一个新的状态变量 filledFields,用于跟踪已被玩家标记的格子数量。
1. 新增状态变量 filledFields
在 state variables 部分添加 filledFields:
/*----- state variables -----*/ let board; // array of 9 boxes let turn; // 1 or -1 let winner; // null = no winner; 1 or -1 winner; 'T' = Tie let filledFields; // 新增:记录已填充的格子数量
2. 初始化 filledFields
在 init() 函数中,将 filledFields 初始化为 0:
//Initializes state and calls render() function init() { board = [0, 0, 0, 0, 0, 0, 0, 0, 0]; turn = 1; winner = null; filledFields = 0; // 初始化已填充格子计数器 render(); }
3. 更新 filledFields
在 handleClick() 函数中,每当玩家成功在一个空位上落子后,就递增 filledFields。
//Get index of the clicked box function handleClick(event) { const boxIdx = parseInt(event.target.id.replace('box-', '')); //if statement in case someone clicks outside box, the box is filled or there is a winner if (isNaN(boxIdx) || board[boxIdx] || winner) return; //update state of board with the current turn value board[boxIdx] = turn; filledFields++; // 在成功落子后递增计数器 //switch player turn turn *= -1; // check for a winner winner = getWinner(); render(); }
4. 优化 getWinner() 函数逻辑
现在,我们可以修改 getWinner() 函数,使其在检查完所有获胜组合后,再根据 filledFields 的值来判断是否平局。
//Check for a winner in the state. 1(X) or -1(O), 'T' for Tie, null for no winner yet function getWinner() { // 1. 遍历所有获胜组合,检查是否有玩家获胜 for (let i = 0; i < COMBOS.length; i++) { const [a, b, c] = COMBOS[i]; if (Math.abs(board[a] + board[b] + board[c]) === 3) { return board[a]; // 发现胜者,立即返回胜者标识 } } // 2. 如果没有玩家获胜,则检查是否所有格子都已填充 if (filledFields === 9) { return 'T'; // 所有格子已满且无胜者,判定为平局 } // 3. 如果没有胜者,且仍有空位(即 filledFields < 9),则游戏仍在进行中 return null; }
通过以上修改,getWinner 函数的逻辑变得清晰:它首先确保检查所有可能的获胜情况,如果没有找到胜者,再判断游戏是否因所有格子被填充而达到平局。
完整 JavaScript 代码示例
以下是经过修改和优化的完整 JavaScript 代码:
/*----- constants -----*/ //Display of background color for the selected box. Player 1 is 1, pink and X. Player 2 is -1, green and O const COLORS = { '0': 'white', '1': 'pink', '-1': 'lightgreen' }; //Display for selected box. X or O const MARK = { '0': '', '1': 'X', '-1': 'O' }; //Winning combos to win the math const COMBOS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [6, 4, 2], [0, 4, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8] ]; /*----- state variables -----*/ let board; //array of 9 boxes let turn; // 1 or -1 let winner; //null = no winner; 1 or -1 winner; 'T' = Tie let filledFields; // 新增:记录已填充的格子数量 /*----- cached elements -----*/ const message = document.querySelector('h1'); const resetButton = document.querySelector('button'); /*----- event listeners -----*/ document.getElementById('board').addEventListener('click', handleClick); resetButton.addEventListener('click', init); /*----- functions -----*/ init(); //Initializes state and calls render() function init() { board = [0, 0, 0, 0, 0, 0, 0, 0, 0]; turn = 1; winner = null; filledFields = 0; // 初始化已填充格子计数器 render(); } //Visualizes all state in the DOM function render() { renderBoard(); renderMessage(); } //Iterate over the squares in the board function renderBoard() { board.forEach(function(boardArr, boardIdx) { const squareId = `box-${boardIdx}`; const squareEl = document.getElementById(squareId); //styles for player selection squareEl.style.backgroundColor = COLORS[boardArr]; squareEl.innerhtml = MARK[boardArr]; squareEl.style.display = 'flex'; squareEl.style.justifyContent = 'center'; squareEl.style.alignItems = 'center'; squareEl.style.fontSize = '19vmin'; }); } //Display whose turn it is and the winner function renderMessage() { if (winner === 'T') { message.innerHTML = 'Tie Game! Game Over!'; } else if (winner) { message.innerHTML = `Player ${MARK[winner]} Wins!`; } else { message.innerHTML = `Player ${MARK[turn]}'s Turn`; } } //Get index of the clicked box function handleClick(event) { const boxIdx = parseInt(event.target.id.replace('box-', '')); //if statement in case someone clicks outside box, the box is filled or there is a winner if (isNaN(boxIdx) || board[boxIdx] !== 0 || winner) // 注意这里改为 board[boxIdx] !== 0 return; //update state of board with the current turn value board[boxIdx] = turn; filledFields++; // 在成功落子后递增计数器 //switch player turn turn *= -1; // check for a winner winner = getWinner(); render(); } //Check for a winner in the state. 1(X) or -1(O), 'T' for Tie, null for no winner yet function getWinner() { // 1. 遍历所有获胜组合,检查是否有玩家获胜 for (let i = 0; i < COMBOS.length; i++) { const [a, b, c] = COMBOS[i]; if (Math.abs(board[a] + board[b] + board[c]) === 3) { return board[a]; // 发现胜者,立即返回胜者标识 } } // 2. 如果没有玩家获胜,则检查是否所有格子都已填充 if (filledFields === 9) { return 'T'; // 所有格子已满且无胜者,判定为平局 } // 3. 如果没有胜者,且仍有空位(即 filledFields < 9),则游戏仍在进行中 return null; }
css (style.css) 和 HTML (index.html) 代码保持不变,因为它们不涉及游戏逻辑的修改。
/* style.css */ * { box-sizing: border-box; } body { height: 100vh; margin: 0; font-family: 'Raleway', sans-serif; display: flex; flex-direction: column; justify-content: center; align-items: center; } header { margin-top: 5vmin; font-size: 10vmin; color: darkslategrey; } h1 { color: slategrey; } #board { display: grid; grid-template-columns: repeat(3, 20vmin); grid-template-rows: repeat(3, 20vmin); } #board>div { border: 0.5vmin solid slategrey; } button { margin-top: 5vmin; margin-bottom: 5vmin; padding: 2vmin; font-size: 3vmin; border-radius: 4vmin; border: 0.5vmin solid lightslategrey; background-color: aliceblue; color: darkslategrey; } button:hover { color: azure; background-color: cadetblue; }
<!-- index.html --> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100&display=swap" rel="stylesheet"> <header>Tic-Tac-Toe</header> <h1>X's Turn</h1> <section id="board"> <div id="box-0"></div> <div id="box-1"></div> <div id="box-2"></div> <div id="box-3"></div> <div id="box-4"></div> <div id="box-5"></div> <div id="box-6"></div> <div id="box-7"></div> <div id="box-8"></div> </section> <button>Reset Match</button>
注意事项与总结
- 状态变量管理: filledFields 作为一个新的状态变量,必须在 init() 函数中正确初始化,并在每次有效的玩家操作后进行更新。
- handleClick 中的空位判断: 确保 handleClick 函数中判断格子是否为空的条件是 board[boxIdx] !== 0,而不是 board[boxIdx]。虽然在JavaScript中 0 是假值,但明确使用 !== 0 可以提高代码可读性和严谨性。
- getWinner 逻辑顺序: 在 getWinner 函数中,判断胜者的逻辑必须优先于判断平局的逻辑。只有在确认没有胜者之后,才能检查是否满足平局条件。如果游戏既没有胜者,也没有平局,则游戏应继续进行。
- 可扩展性: 这种计数器方法对于固定大小的棋盘(如3×3的井字棋)非常有效。对于更复杂的棋盘游戏,可能需要更通用的方法来检测所有格子是否已满。
通过引入 filledFields 计数器并优化 getWinner 函数的逻辑,我们成功地解决了井字棋游戏中平局判断不准确的问题。现在,您的井字棋游戏将能够正确地识别胜者、平局以及游戏进行中的状态,从而提供更完整的游戏体验。