JSFiddle - React, Tailwind, and code Playground

by Ahmad Baktash Hayeri

HTML

<h1>Tic-Tac-Toe</h1>
<div id="message"></div>

<table border="3">
    <tr>
        <td class="Square" id="s1" onclick="nextMove(this)"></td>
        <td class="Square" id="s2" onclick="nextMove(this)"></td>
        <td class="Square" id="s3" onclick="nextMove(this)"></td>
    </tr> 
    <tr>
        <td class="Square" id="s4" onclick="nextMove(this)"></td>
        <td class="Square" id="s5" onclick="nextMove(this)"></td>
        <td class="Square" id="s6" onclick="nextMove(this)"></td>
    </tr> 
    <tr>
        <td class="Square" id="s7" onclick="nextMove(this);"></td>
        <td class="Square" id="s8" onclick="nextMove(this);"></td>
        <td class="Square" id="s9" onclick="nextMove(this);"></td>
    </tr> 
</table>

CSS

.Square{
    width:20px;
    height:20px;
    cursor: pointer;
}

JavaScript

var turn = "X";

function setMessage(msg) {
document.getElementById("message").innerHTML = msg;
 }

function nextMove(square) {
   if (square.innerHTML == "X" || square.innerHTML == "O") {
       alert('It has already been selected'); 
   } else {
       square.innerHTML = turn;
       switchTurn();
    }   
}

function switchTurn() {
   if (checkforWinner(turn)) { 
      alert("Congratulations, " + turn + "! You win");
    } else if (turn == "X") {
        turn = "O";
     setMessage("It's " + turn + "'s turn!");
     } else {
        turn = "X";
  setMessage("It's " + turn + "'s turn!");
   }

}

function checkforWinner(move) {
   var result = false;
   if (checkRow(1,2,3, move) || 
       checkRow(4,5,6, move) ||
       checkRow(7,8,9, move) ||
       checkRow(1,4,7, move) ||
       checkRow(2,5,8, move) ||
       checkRow(3,6,9, move) ||
       checkRow(1,5,9, move) ||
       checkRow(3,5,7, move)) {

       result = true;
}
      return result;
 }
function checkRow(a,b,c, move) {
     var result = false;
     if (getBox(a) === move && getBox(b) === move && getBox(c) === move) {
          result = true;
    }

return result; 
}
function getBox(number) {
document.getElementById("s" + number).innerHTML

}