Paranoid
Paranoid

Reputation: 25

Switch Players in a two player Tic Tac Toe game

I am new to JavaScript and I am trying to create a 2 player tic tac toe game, and I have the basic code, but I don't understand how to switch the letter from X to O or change the player turn.

This is what I have so far:

var player2= "O" ;
var player1 = "X";

var cells = document.querySelectorAll(".cell");
const winCombos = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 4, 8],
  [6, 4, 2],
  [2, 5, 8],
  [1, 4, 7],
  [0, 3, 6],
]

startGame();

function startGame() {
  document.querySelector('.endgame').style.display = "none";
  //board = [0,1,2,3,4,5,6,7,8]
  for (var i = 0; i < cells.length; i++) {
    cells[i].innerText = '';
    cells[i].style.removeProperty('background-color');
    cells[i].addEventListener('click',   changeTurn)
  }
}

function changeTurn(square) {
  console.log(square.target.id);
  let squareId = square.target.id;

  document.getElementById(squareId).innerText = player1;

}

Please suggest any way I can switch player turns. Thank You

Upvotes: 0

Views: 1309

Answers (2)

Ritesh Khandekar
Ritesh Khandekar

Reputation: 4005

Use counter :

There are total 9 turns are present

  • 5 turns of X
  • 4 turns of O

Set counter to 0 and increment it when div is get clicked

Game starts with X so print X on first click like:

  • when number is odd then print X(counter++ = 1)
  • when number is even then print O(counter++ =2)

when it is 9th turn show results like this:

if(counter==9){
//do some stuff to Show results
}

Code:

var turncount=0;
function changeTurn(square) {
var player1="X";
var player2="O";
turncount++;
var squareId = square.target.id;
var sqr = document.getElementById(squareId);
if (turncount == 9){
    //Results
    return;
  }
if (turncount % 2 == 0) {
    sqr.innerText=player2;
}else{
    sqr.innerText=player1;
  }
}

Upvotes: 0

niyasc
niyasc

Reputation: 4490

Use a global variable to store active Player and switch the player inside changeTurn method.

var activePlayer = 0;
var players = ['X', '0'];
....
function changeTurn() {
  // fill cell with players[activePlayer] and check for win logic.  

  activePlayer = activePlayer == 0 ? 1 : 0;
}

Upvotes: 0

Related Questions