I wrote a quick algorithm that detects a win in a TicTacToe Game.
fn game()
loops through a simulated ticTacToe
board, finds all the index's of a given value, then loops through all the possible winning combos, finds any index's where the actual value is equal to the index's from the first loop, (I know :/) then replaces the value with the value passed into the function (either x or o).
Then, a subsequent function is run that checks if every value inside any of the nested arrays inside the possibleWinCombos
are all equal to each other. If true, a winner is found.
const possibleWinCombos = [
[0, 1, 2], //================ //
[3, 4, 5], //== Horizontal == //
[6, 7, 8], //=================//
[0, 3, 6], //================ //
[1, 4, 7], //== Vertical == //
[2, 5, 8], //=================//
[0, 4, 8], //=================//
[2, 4, 6], //== Diagonal == //
]
const ticTacToe = [
'x', 'o', null,
null, 'x', null,
'o', null, 'x',
]
const game = (value) => {
ticTacToe.forEach((cell, idxOfCell) => {
if(cell === value){
for (winCombo of possibleWinCombos){
let idxToReplace = winCombo.indexOf(idxOfCell)
winCombo.splice(idxToReplace, 1, value)
}
}
})
checkForWinner(value) ?
console.log(`${value}'s win`) : console.log('game still going')
}
const checkForWinner = (value) => {
return possibleWinCombos.some((winCombo) => {
return winCombo.every((winComboValue) => winComboValue === value);
})
}
game('x') // x's win
game('o') // game still going
It's only two functions so it's not very code heavy but I feel like game()
wouldn't score very high on the performance rankings due to the nested looping. Any recommendations on some improvements would be great.