I wrote a tic-tac-toe game in JavaScript. I want to simulate the computer's turn and also update the score of the player with turn.
How do I write this code? I wrote some code which works with a player X and O but they don't get updated. I want to see which player's turn is and the score for each player
const gameState = {
currentPlayer: 'x',
players: ['x', 'o'],
board: [
[null, null, null],
[null, null, null],
[null, null, null]
]
}
var turn = 1;
var P1Score = 0;
var p2Score = 0;
function checkWinner(player) {
if ($(".row-1 .cell." + player).length === 3 ||
$(".row-2 .cell." + player).length === 3 ||
$(".row-3 .cell." + player).length === 3 ||
$(".col1." + player).length === 3 ||
$(".col2." + player).length === 3 ||
$(".col3." + player).length === 3 ||
($("#1").hasClass(player) &&
$("#5").hasClass(player) &&
$("#9").hasClass(player)) ||
($("#3").hasClass(player) &&
$("#5").hasClass(player) &&
$("#7").hasClass(player))) {
$(".cell ").empty();
$(".cell").removeClass("x");
$(".cell").removeClass("o");
$(".cell").css('background', 'blue')
return true;
}
}
$('.cell').click(function() {
if (gameState.currentPlayer == "x" && !$(this).hasClass("o")) {
$(this).text("x")
$(this).addClass("x")
$(".x").css('background', 'gold')
if (checkWinner("x")) {
alert(`${gameState.currentPlayer}is the winner!.Start a new game`)
} else checkTie()
} else if (!$(this).hasClass("x")) {
$(this).text("o")
$(this).addClass("o")
if (checkWinner("o")) {
alert(`${gameState.currentPlayer}is the winner!. Start a new game`)
} else checkTie()
}
changePlayer();
});
function changePlayer(){
if( gameState.currentPlaye == 'x') {
gameState.currentPlayer = 'o'
} else {
gameState.currentPlayer = 'x'
};
};
function checkTie() {
if ($(".x").length + $(".o").length === 9) {
$(".cell ").empty();
$(".x").removeClass("x");
$(".o").removeClass("o");
alert("Its a tie")
};
};
$('.restart').click(function() {
$(".cell ").empty();
$(".cell").removeClass("x");
$(".cell").removeClass("o");
$(".cell").css('background', 'blue')
});