This is the entire code of my Tic Tac Toe game.
I created the functions count1 & count2 to score the players wins, and it works but when I refresh the page the score shows 0. I would like to resolve this to only shows 0 if I clean the score by clicking in the "Clean Score" button (that's why I created the scoreCleaner function).
And instead of refreshing the page to clean the Board, I would like to click in the "restart game" button.
How can I do it works?
let board = ["", "", "", "", "", "","", "", ""];
let playerTime = 0;
let gameOver = false;
let symbols = ["o", "x"];
let winStates = [
[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 handleMove(position) {
if (gameOver) {
return;
}
if (board[position] == "") {
board[position] = symbols[playerTime];
gameOver = isWin();
if (!gameOver) {
playerTime = (playerTime == 0) ? 1 : 0;
}
}
return gameOver;
}
function isWin() {
for (let i = 0; i < winStates.length; i++) {
let seq = winStates[i];
let pos1 = seq[0];
let pos2 = seq[1];
let pos3 = seq[2];
if (board[pos1] == board[pos2] &&
board[pos1] == board[pos3] &&
board[pos1] != "") {
return true;
}
}
return false;
}
document.addEventListener("DOMContentLoaded", ()=>{
let squares = document.querySelectorAll(".square");
squares.forEach((square) => {
square.addEventListener("click", handleClick);
})
})
function handleClick(event) {
let square = event.target;
let postion = square.id;
if (handleMove(postion)) {
let c1 = 0;
let c2 = 2;
setTimeout(()=> {
alert("Game is Over. " + playerTime + " wins.");
}, 10);
if (playerTime == 0) {
c1 = c1 + 1;
count1();
} else {
c2 = c2 + 1;
count2();
}
}
updateSquare(postion);
}
function updateSquare(postion) {
let square = document.getElementById(postion.toString());
let symbol = board[postion];
square.innerHTML = `<div class='${symbol}'></div>`
}
function count1() {
if (localStorage.count) {
localStorage.count = Number(localStorage.count)+1;
} else {
localStorage.count = 1;
}
document.getElementById("player1Score").innerHTML = localStorage.count;
}
function count2() {
if (localStorage.count) {
localStorage.count = Number(localStorage.count)+1;
} else {
localStorage.count = 1;
}
document.getElementById("player2Score").innerHTML = localStorage.count;
}
function scoreCleaner() {
localStorage.clear();
document.getElementById("player1Score").innerHTML = 0;
document.getElementById("player2Score").innerHTML = 0;
}