CCCPaste

Untitled

let playerText = document.getElementById("playerText")
let restartButton = document.getElementById("restartButton")
let boxes = Array.from(document.getElementsByClassName("box"))
const xText = "X"
const oText = "O"
let currentPlayer = xText
let idleBlock = getComputedStyle(document.body).getPropertyValue('--idle-block')
let cells = Array(9).fill(null)
let winningblocks = getComputedStyle(document.body).getPropertyValue('--winning-blocks')
function startGame() {
    boxes.forEach(box => {
        box.addEventListener('click', boxClicked)
    })
}
function boxClicked(e) {
    let cellsNotEmpty = 0;
    let idx = e.target.id;
    cells.forEach(cell => {
        if(cell) {
            cellsNotEmpty++
        }
    })
    if(cellsNotEmpty == 9) {
        playerText.innerText = "It is a draw!"
        return
    }
    if(!cells[idx]) {
        cells[idx] = currentPlayer
        e.target.innerText = currentPlayer
        const hasWon = playerWon()

        if(hasWon.length == 3) {
            for(let i = 0; i < 3; i++) {
                Array.from(document.getElementsByClassName("box"))[hasWon[i]].style.backgroundColor = winningblocks;

            }
            playerText.innerText = currentPlayer + " has won!"
            boxes.forEach(box => {
                box.removeEventListener('click', boxClicked)
            })
            return 
        }

        if(currentPlayer == xText) {
            currentPlayer = oText
        }
        else {
            currentPlayer = xText
        }
    }
}
const winningCombos = [
    [0, 1, 2],
 [3, 4, 5],
 [6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
function playerWon() {
    for(let i = 0; i < winningCombos.length; i++) {
        let cnt = 0;
        for(let j = 0; j < 3; j++) {
            if(cells[winningCombos[i][j]] == currentPlayer) {
                cnt++;
            }
        }
        if(cnt == 3) {
            return winningCombos[i]
        }
    }
    return []
}
restartButton.addEventListener('click', restart)

function restart() {
    cells.fill(null)
    currentPlayer = xText
    
    boxes.forEach(box => {
         box.innerHTML = ''
        box.addEventListener('click', boxClicked)
    })
    for(let i = 0; i < 9; i++) {
        Array.from(document.getElementsByClassName("box"))[i].style.backgroundColor = idleBlock
    }
    playerText.innerText = 'Tic tac toe'
    window.location.reload()
}
/**
 * winning combos
 
 */

startGame();