I've been trying to figure out how can I use WinCombos to determine a winner but failed.
How can I compare my array (winCombos) with the cells in a 3x3 tic tac toe board to determine a winner?
var player1 = "X";
var player2 = "O";
let currentClass = player1
const winCombos = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[6, 4, 2]
]
let cells = document.querySelectorAll(".row>div");
console.log(cells);
for (var i = 0; i < cells.length; i++){
cells[i].addEventListener('click', cellClicked, {once: true})
var j = cells[i]
}
function cellClicked(){
if(currentClass == player1){
event.target.textContent = currentClass;
currentClass = player2;
if(checkWin(currentClass)){
console.log("winner");
}
}else{
currentClass == player2;
event.target.textContent = currentClass;
currentClass = player1;
}
}
We can use Array.prototype.some
and Array.prototype.every
in order to accomplish our goal.
function checkWin(player) {
return winCombos.some(v => v.every(k => cells[k].textContent == player));
}