Im making a game of "tic tac toe" also called "naughts and crosses".
Each of the 9 squares has a number:
1 2 3
4 5 6
7 8 9
As each player has a go the number they've chosen is added to the state. So if user1 has chosen squares 1 and 2, and user2 has chosen squares 4 and 5 then the state object looks like this:
const state = selected: {
user1: [1,2],
user2: [4,5]
}
After each go I need to check the state to see if either user has 3 in a row. Here are all the possible winning numbers:
const winingNumbers = [
[1,2,3], // top row
[4,5,6], // middle row
[7,8,9], // bottom row
[1,4,7], // first column
[2,5,8], // second column
[3,6,9], // last column
[1,5,9], // last column
[3,6,9], // diagonal 1
[3,5,7] // diagonal 2
];
How can I check the state to see if any of the users have a row? In this example user1 has a match:
const state = selected: {
user1: [6,3,2,1],
user2: [9,4,5]
}
In this example user2 has a match:
const state = selected: {
user1: [1,9,2,8],
user2: [5,4,3,6]
}
Note that the numbers can be an any order and other numbers not part of the match might be in the state also. Im using Bable so I can use ES6 syntax.