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 trialBruno Godinho
Full Stack JavaScript Techdegree Graduate 17,585 Pointsshouldn't there be 4 diagonal loops?
shouldn't there be 4 diagonal loops? because from what i understand the code is only checking the 2 diagonals that go backwards on the x axis. for example :what if i drop my token on (0,0) and i want to check the spaces (1,1),(2,2)and (3,3)
maybe i am missing something but i think there should be 6 loops in total ,no?
2 Answers
Jason Larson
8,361 PointsThe reason that there are only 4 (double) loops is that they are covering all the winning combinations on the board. In your example for the token at 0,0, and checking it diagonally upwards to the right, this is actually the first sequence that is checked in the second diagonal loop. It starts at 3,3, then checks 2,2, then 1,1 and finally 0,0. You only need 2 diagonal loops checking to the left upwards and downwards because the outer loop starts the x position at 3 and then moves it over to the right on each iteration, while the inner loop moves the starting row. So the first diagonal loop starts at 3,0 (middle column, bottom row) and checks left and up 3 times. Then the starting position is moved to 3,1 and it does the same checks, then 3,2 which checks back to 0,5 (first column, top row). Then the outer loop iterates and moves the starting position to 4,0, and then 4,1, then 4,2 etc. until the final place it starts checking is 5,2, meaning that all diagonal sequences of 4 spaces starting from the right and going up and to the left would have been checked. The same thing happens with the other diagonal loop, except that it starts at 3,3 and looks left and down, with the final check starting at 5,5 (top right corner).
JASON LEE
17,352 PointsI thought the same as your question that there should be 4 diagonal loops, and two directions for horizontal (right to left, left to right). But then realized that this method is literally checking the ENTIRE gameboard for any consecutive 4 token by the same owner, and without regard to the last-placed token.