Home > database >  Unable to get Tic Tac Toe game to change player to turn
Unable to get Tic Tac Toe game to change player to turn

Time:01-08

I have been trying different ways to get the currentPlayers and playerTitle to change. I am not sure if I am correctly implementing the if statement because the else if is not executing. `"use strict";

const gameClock = document.querySelector(".clock");
const playerTitle = document.querySelector(".player-title");
const ticTacToeBoard = document.querySelector(".tic-tac-toe-container");
const cells = document.querySelectorAll(".cell");
const startPauseBtn = document.querySelector("start-btn");
const resetBtn = document.querySelector(".resetBtn");

let currentPlayer = "X";
ticTacToeBoard.classList.add("player-turn");
//functions

const playerMove = () =\> {
cells.forEach((cell) =\> {
if (ticTacToeBoard.classList.contains("player-turn")) {
cell.addEventListener("click", () =\> {
cell.append(currentPlayer);
playerTitle.innerHTML = "Player: 2";
currentPlayer = "O";
ticTacToeBoard.classList.toggle("player-turn");
});
} else if (ticTacToeBoard.classList.contains("player-turn") === false) {
cell.addEventListener("click", () =\> {
cell.append(currentPlayer);
playerTitle.innerHTML = "Player: 1";
currentPlayer = "X";
ticTacToeBoard.classList.toggle("player-turn");
});
}
});
};`

playerMove();

I have tried to get the currentPlayer to switch back from "O" to "X" and playerTitle back to "Player: 1" with ticTacToeBoard.classList.contains() as the condition within an if statement but it does not execute the if else statement. So currentPlayer remains "O" and playerTitle remains "Player: 2".

CodePudding user response:

You only check if ticTacToeBoard.classList contains "player-turn" at the beginning of the game, which means each cell is hardcoded to change the turn to "O". You need to move the if statement inside the cell event listener so that each cell actually checks whether ticTacToeBoard.classList contains "player-turn".

Also, you don't need to check if ticTacToeBoard.classList.contains("player-turn") is false, a simple else is enough.

  • Related