JSFiddle - React, Tailwind, and code Playground

by YameenYasin

HTML

<h1>Tic Tac Toe</h1>
 <h2 id="who"></h2>
 <div class="grid" id="grid"></div>

CSS

.game{
  margin: 0 auto;
}
.grid{
  border:2px solid #000;
  display: inline-block;
}
.row{
  display:flex;
}
.col{
  width:100px;
  height:100px;
  border:1px solid #ccc;
  font-size: 46px;
  padding: 26px;
  box-sizing: border-box;
}

JavaScript

const size = 3;
const p1 = 0;
const p1_sym = 'O';
const p2 = 1;
const p2_sym = 'X'
let player_turn = false;
let grid = [
  [Infinity, Infinity, Infinity],
  [Infinity, Infinity, Infinity],
  [Infinity, Infinity, Infinity],
];

const createGrid = () => {
	
  let row;
  let col;
  let parent = document.getElementById('grid');
  
  for(let i=0 ; i< size; i++) {
  
  	row = document.createElement('div');
    row.setAttribute('class','row');
    
    for(let j=0; j < size; j++){
    	col = document.createElement('div');
    	col.setAttribute('class','col');
      col.setAttribute('data-r',i);
      col.setAttribute('data-c',j);
      
      row.appendChild(col);
    }
    
    parent.appendChild(row);  
  }
};

const checkTurn = () => {
	const el = document.getElementById('who');
  const pl = player_turn ? 'Player 2': 'Player 1';
  el.innerText = pl + ':Ready to Play';
};


const playGame = () => {
	const gridEle = document.getElementById('grid');
  gridEle.addEventListener('click',e =>{
  	const t = e.target;
    const r = t.getAttribute('data-r');
    const c = t.getAttribute('data-c');
    
    if(grid[r][c] === Infinity){
    	grid[r][c] = !player_turn ? p1_sym : p2_sym;
      t.appendChild(document.createTextNode(grid[r][c]));
      player_turn = !player_turn;
      checkTurn();
    }
    
  },false)
}

createGrid();
checkTurn();
playGame();