Tic Tac Toe win conditions

Tic Tac Toe win conditions
0.0 0

#1

So I got the game mostly done, except for the win conditions. I haven’t looked at how others have solved this, but the way my tic tac toe game works is the following…

You’ve got an array called board. board = [0,1,2,3,4,5,6,7,8]; The array is visually set up like this.

0 | 1 | 2

3 | 4 | 5

6 | 7 | 8

When an X or O is placed on the board, it replaces one of those ints with a
string for “X” or “O”.

So when, for example…board[0,1,2] =[“X”,“X”,“X”] or also with O…it’s a winning turn. And the same for these.
3,4,5
6,7,8
0,3,6
1,4,7
2,5,8
0,4,8
2,4,6

I could have a bunch of if statements but that seems really redundant. Then I thought about making the array a string and checking for regex patterns but the pattern here seems like it would be really complex. Any way around a bunch of if statements or a regex string longer than a Tolstoy novel?


#2

If you put those triplets of possibilities (each as an array), in an array, you can run some over it at the end of every turn. You would be checking, in the some callback, if every element in that triplet was an X/O on the game array (depending on turn). If it returned true, that’s a win, otherwise not


#3

Ahh I knew there had to be some functions I could take advantage of. Forgot about those ones. Thank you, I will try it!


#4

Also, there is this. As far as I can remember it works, but I may have forgotten something. It’s not really worth spoilering, as you will see; if it actually works it works by way of magic

// Assuming board array is same order you had,
// left to right, row by row. Keep running total of score
// for each player:
const squareScores = [1, 2, 4, 8, 16, 32, 64, 128, 256];
const wins = [7, 56, 448, 73, 146, 292, 273, 84];
const hasWon = (score) => wins.some(win => win & score === win);

#5

So it’s mostly done now aside from styling. There’s an annoying bug I can’t seem to fix but aside from that, this is how I solved the issue from this topic, thanks to you.

This is taking the X or the O and replacing all the numbers in the 2d array that match the index clicked with it.
function alterGameWin(num, str) {
for (var i = 0; i < gameWin.length; i++) {
for (var j = 0; j < gameWin[i].length; j++) {
if (gameWin[i][j] == num) {
gameWin[i][j] = str;
}
}
}
}

And this is checking is every index in one of the inner arrays matches X or O. Then after this I am doing some conditional logic to see if the player or the ai won so I can display the correct message.
function checkTurnWin() {
let checkWinX = gameWin.some(function(val, i) {
return gameWin[i].every(function(val) {
return val === “X”;
});
});
let checkWinO = gameWin.some(function(val, i) {
return gameWin[i].every(function(val) {
return val === “O”;
});
});