井字棋游戏获胜后如何阻止未填充方块接收输入?
Hey there! Let's sort out that annoying issue where players can keep clicking empty tiles even after someone's already won the round—leading to incorrect score updates. Here's a straightforward solution using a game state flag:
Step 1: Add a Game State Variable
First, declare a global variable to track whether the game is still active. Put this at the top of your code, outside any functions:
let gameActive = true;
This acts as a "switch"—when it's true, tiles accept clicks; when false, all input gets blocked.
Step 2: Flip the Switch When a Winner is Found
Modify your existing winner-check code to set gameActive to false as soon as a winner is detected. This stops any further tile interactions:
if(checkForWinner()){ gameActive = false; // Mark game as ended if(currentTurn === 2){ // X player wins alert(`${player1Name} won this round.`) player1score++ document.querySelector('#player_one_score').innerText = player1score } else{ alert(`${player2Name} won this round.`) player2score++ document.querySelector('#player_two_score').innerText = player2score } }
Step 3: Block Clicks When Game is Inactive
Find the function that handles tile clicks (the one attached to each square's click event). At the very start of this function, add a check for gameActive—if it's false, exit the function immediately so no new moves are processed:
function handleTileClick(event) { // Exit early if game has ended if (!gameActive) return; // Rest of your existing code for placing X/O, switching turns, etc. }
Step 4: Reset the State for New Rounds
Don't forget to reset gameActive back to true when starting a new round (like after a reset button is clicked or a round finishes). For example:
function resetGame() { gameActive = true; // Re-enable tile clicks // Reset board, scores (if needed), current turn, etc. }
That's it! Now once a player wins, all empty tiles will ignore clicks, and your score won't keep updating incorrectly.
内容的提问来源于stack exchange,提问作者octaviandd

