Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
alborz
Full Stack JavaScript Techdegree Graduate 30,885 PointsCan't get tic tac toe board to display winner screen when a player wins.
Hi, I'm working on a tic tac toe game; I want to show the win screen when a player gets three consecutive shapes in a row and wins, but my code doesn't seem to work. Here's my repo, thanks!
1 Answer
Seth Kroger
56,416 PointsPutting aside the WETness of your code (you Wrote Everything Twice, quite literally) and just looking at the logic of the "is there a winner" part. My comments are surrounded by ****:
for (var i = 0; i < winningCombos.length; i++) {
var winningCombo = winningCombos[i];
console.log(winningCombo);
//var counter = 0; **** Why comment this out? Shouldn't it be set each outer loop? ****
// loop through the players checkedboxes array and see if the index matches one of the indexes for
// a winning combo. If it does, increment the counter by 1. Then if the length of the counter is
// equal to the length of the winning combo, the player wins and game ends
// **** The logic of your approach is sound. It's just the details of the implementation that get you. ****
for (var j = 0; j <= playerXCheckedBoxes.length; j++) {
console.log(playerXCheckedBoxes.length);
var player1SelectedBox = playerXCheckedBoxes[j]; // **** OK get an element out of one list and see if it's in the second. Good start ****
console.log(player1SelectedBox);
if (winningCombo.includes(player1SelectedBox.index)) { // **** I thought each element was a number, not an object ****
counter++; // **** Because you commented out the var declaration, this is a global ****
console.log(counter);
} if (player1SelectedBox == winningCombo) { // **** Wait, you're checking if an element is equal to a list? ****
// **** After already checking if the list contains the element? ****
// player wins **** Shouldn't this be outside the inner loop? ****
// **** and shouldn't you be checking that counter equals something as you wrote in the comment above? ****
board.style.display = 'none';
winScreenDiv.style.display = 'block';
}
}
// **** Ditto for 2nd loop ****