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 trialmatthewchau2
8,343 PointsIs my solution also acceptable?
I understand how Ashley did it, but my code seems to work as well. We just went about it a little differently for the horizontal and diagonal directions. Just want to confirm that my solution is also acceptable.
/**
* checks if there is a winner on the board after each token drop
* @param {object} target - targeted space for dropped token
* @return {boolean} boolean value indicating whether the game has been won (true) or not (false)
*/
checkForWin(target) {
const owner = target.token.owner;
let win = false;
// vertical
for (let x = 0; x < this.board.columns; x++) {
for (let y = 0; y < this.board.rows - 3; y++) {
if (this.board.spaces[x][y].owner === owner &&
this.board.spaces[x][y + 1].owner === owner &&
this.board.spaces[x][y + 2].owner === owner &&
this.board.spaces[x][y + 3].owner === owner) {
win = true;
}
}
}
// horizontal
for (let y = 0; y < this.board.rows; y++) {
for (let x = 0; x < this.board.columns - 3; x++) {
if (this.board.spaces[x][y].owner === owner &&
this.board.spaces[x + 1][y].owner === owner &&
this.board.spaces[x + 2][y].owner === owner &&
this.board.spaces[x + 3][y].owner === owner) {
win = true;
}
}
}
// diagonal downwardly left to right
for (let x = 0; x < this.board.columns - 3; x++) {
for (let y = 0; y < this.board.rows - 3; y++) {
if (this.board.spaces[x][y].owner === owner &&
this.board.spaces[x + 1][y + 1].owner === owner &&
this.board.spaces[x + 2][y + 2].owner === owner &&
this.board.spaces[x + 3][y + 3].owner === owner) {
win = true;
}
}
}
// diagonal downwardly right to left
for (let x = 6; x > this.board.columns - 5; x--) {
for (let y = 0; y < this.board.rows - 3; y++) {
if (this.board.spaces[x][y].owner === owner &&
this.board.spaces[x - 1][y + 1].owner === owner &&
this.board.spaces[x - 2][y + 2].owner === owner &&
this.board.spaces[x - 3][y + 3].owner === owner) {
win = true;
}
}
}
return win;
}
1 Answer
Steven Parker
231,275 PointsIn programming, there is rarely just one way to create a solution. The more complex the problem, the larger the opportunity that different but equally valid solutions can be created.
And in this case, the order in which the possible win lines are examined is completely unimportant as long as they all get checked.