Home > Back-end >  how do i check winner in tic tac toe from an array
how do i check winner in tic tac toe from an array

Time:01-26

im trying to find a simple way to check a winner in tic tac toe. The code that i could use now is this

const cellElement = document.querySelectorAll('[data-cell]')
const winner = document.getElementById("winner")
let nextTurn = true

cellElement.forEach(cell => {
    cell.addEventListener("click", handleClick, { once: true })

    function handleClick() {
        switchnextTurn(cell)
        checkWin(cell)
        //check for draw
    }
});

function switchnextTurn(cell) {
    if (nextTurn == true) {
        cell.innerHTML = "X"
        nextTurn = false
    } else if (nextTurn == false) {
        cell.innerHTML = "O"
        nextTurn = true
    }
}

console.log(winningConditions.length);
function checkWin(cell) {

    for (let i = 0; i < cellElement.length; i  ) {     
         if (cellElement[0].innerHTML == "X" && cellElement[1].innerHTML == "X" && cellElement[2].innerHTML == "X") {
         console.log(true);
         winner.innerHTML = "X WON!!!"
        } else {
            console.log(false)
        }
    }

}

i could use the if statement i used above in checkWin() but then i have to repeat it 8 times to check X and 8 times for circle but i want to simplify it with less code and i dont want it to be such repetitive.

i want to for example use this array that checks for every possible win conditions. i have tried it but cant seem to get it right.

let winningConditions = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ]

i tried for example this but then i get an error that says "Cannot read properties of undefined (reading 'innerHTML')"

for (let i = 0; i < winningConditions.length; i  ) {
    if (cellElement[winningConditions[i][i]].innerHTML == "X") {
        console.log(true);
        console.log("X WON!!!");
        winner.innerHTML = "X WON!!!"
    } else {
        console.log(false)
    }
}

you can check it out here https://jsfiddle.net/pcs2j4ow/

CodePudding user response:

Try something like that

function checkWin(cell) {
  for (let winCondition of winningConditions) {
    if(winCondition.every(w => cellElement[w].innerHTML == "X")) {
      winner.innerHTML = "X WON!!!"
      return "X";
    }
    if(winCondition.every(w => cellElement[w].innerHTML == "O")) {
      winner.innerHTML = "O WON!!!"
      return "O";
    }
  }
  return "";
}
  •  Tags:  
  • Related