TransWikia.com

x and o in tic tac toe keeps alternating

Stack Overflow Asked by Channee MathMath on November 20, 2021

in my tic tac toe game the x and o’s keep alternating no matter where i click on my cell boxes. i tried typing return at the end of the function and it doesnt stop. i know it has something to do with the turn += 1, at the bottom but dont know how to come about it. really appreciate some advice.

let playerOne = 'x';
let playerTwo = 'o';
let turn = 0;
let lastClicked;

const gameBoard = document.querySelector('.gameBoard');

for (i = 0; i < 9; i++) {
  const gameBox = document.createElement('div');
  gameBox.classList.add('gridCellItem');
  gameBox.id = 'cell' + i;
  gameBox.addEventListener('click', clickGameBox);
  gameBoard.appendChild(gameBox);
}


function clickGameBox(event) {

  if (turn === 0) {
    event.target.innerText = playerOne;
    lastClicked = playerOne;
  } else {
    if (lastClicked === playerOne) {
      event.target.innerText = playerTwo;
      lastClicked = playerTwo;

    } else {
      event.target.innerText = playerOne;
      lastClicked = playerOne;

    }
  }
  turn += 1;

}
<div class="gameBoard"></div>

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP