开发井字棋时比较Object.values数组失效问题求助
Hey Matt, let's figure out why your tic-tac-toe win condition check isn't working!
First off, I spotted a super common (and easy to fix) issue: typos in your win condition array. You’ve got several instances where "empty" is misspelled as "emtpy"—these inconsistent spellings will throw off any logic using Object.values() to compare states, since the values won’t match up correctly.
Step 1: Fix the Typos in Your Win Condition Array
Let’s correct all the misspelled "emtpy" entries first. Here’s the cleaned-up version:
let winConditions = [ {box1: "empty", box2: "empty", box3: "empty"}, {box1: "empty", box4: "empty", box7: "empty"}, {box1: "empty", box5: "empty", box9: "empty"}, {box2: "empty", box5: "empty", box8: "empty"}, // Fixed "emtpy" to "empty" {box3: "empty", box6: "empty", box9: "empty"}, // Fixed both "emtpy" entries {box3: "empty", box5: "empty", box7: "empty"}, {box4: "empty", box5: "empty", box6: "empty"}, // Fixed "emtpy" to "empty" {box7: "empty", box8: "empty", box9: "empty"} // Fixed "emtpy" to "empty" ];
Step 2: Make Sure Your Comparison Logic is Correct
Assuming your goal is to check if the current board state matches any win condition, here’s a reliable example of how to do that. We’ll compare the actual current board values against each win condition, not the default "empty" values in your array:
function checkForWin(currentBoard) { // Loop through each win condition for (const condition of winConditions) { // Grab the current board values for the boxes in this condition const boxValues = Object.keys(condition).map(boxKey => currentBoard[boxKey]); // Check if all values are the same and not empty (meaning a player filled them) if (boxValues.every(val => val === boxValues[0] && val !== "empty")) { return boxValues[0]; // Return the winning player ("X" or "O") } } return null; // No winner yet }
Bonus: Simplify Your Win Condition Definition
For easier maintenance, you can refactor your win conditions to use position indices instead of object keys. This makes the logic cleaner and less error-prone:
// Indexes correspond to box1=0, box2=1, ..., box9=8 const winConditions = [ [0,1,2], [3,4,5], [6,7,8], // Horizontal wins [0,3,6], [1,4,7], [2,5,8], // Vertical wins [0,4,8], [2,4,6] // Diagonal wins ]; // Updated check function for the array-based conditions function checkForWin(boardArray) { for (const [a, b, c] of winConditions) { if (boardArray[a] && boardArray[a] === boardArray[b] && boardArray[a] === boardArray[c]) { return boardArray[a]; } } return null; }
With these fixes, your win detection logic should work as expected!
内容的提问来源于stack exchange,提问作者Matt Comeaux

