JSFiddle - React, Tailwind, and code Playground
HTML
<p id="msg">
Welcome to Tic Tac Toe
</p>
<div id="box1" class="box" onclick="clickSquare(1)"></div>
<div id="box2" class="box" onclick="clickSquare(2)"></div>
<div id="box3" class="box" onclick="clickSquare(3)"></div>
<div id="box4" class="box" onclick="clickSquare(4)"></div>
<div id="box5" class="box" onclick="clickSquare(5)"></div>
<div id="box6" class="box" onclick="clickSquare(6)"></div>
<div id="box7" class="box" onclick="clickSquare(7)"></div>
<div id="box8" class="box" onclick="clickSquare(8)"></div>
<div id="box9" class="box" onclick="clickSquare(9)"></div>
CSS
.box{
border: 2px solid white;
background-color: black;
width: 70px;
height: 70px;
float: left;
text-align: center;
line-height: 70px;
font-size: 40pt;
font-family: cursive, "Comic Sans MS";
}
#box4,#box7{
clear: both;
}
.X{
background-color: red;
}
.O{
background-color: green;
}
body{
background-color: #ff6600;
text-align: center;
margin: 0 20%;
}
#msg{
font-family: cursive,"Comic Sans MS";
font-size: 30pt;
}
JavaScript
var playerTurn = "X";
var moves = ["","","","","","","","",""];
var gameFinished = false;
function clickSquare(num){
if (gameFinished){
return
}
if(checkifEmpty(num)){
document.getElementById("box"+num).innerHTML=playerTurn;
document.getElementById("box"+num).classList.add(playerTurn);
moves[num-1]=playerTurn;
console.log(moves);
if (!checkWin()){
if(playerTurn=="X"){
playerTurn="O";
}else{
playerTurn="X";
}//end if
console.log(moves.join("").length);
if (checkDraw()){
document.getElementById("msg").innerHTML="Game is a DRAW";
}else{
document.getElementById("msg").innerHTML="Player "+playerTurn+" goes next";
}
}
}else{
// alert("Invalid Move!");
document.getElementById("msg").innerHTML="Invalid Move!";
}//end if
}//end function
function checkifEmpty(num){
if (moves[num-1]==""){
return true;
}
return false;
}
function checkWin(){
if((moves[0]==moves[1]) && (moves[1]==moves[2]) && (moves[0] !="") ||
(moves[3]==moves[4]) && (moves[3]==moves[5]) && (moves[3] !="") ||
(moves[6]==moves[7]) && (moves[6]==moves[8]) && (moves[6] !="") ||
(moves[0]==moves[3]) && (moves[0]==moves[6]) && (moves[0] !="") ||
(moves[1]==moves[4]) && (moves[1]==moves[7]) && (moves[1] !="") ||
(moves[2]==moves[5]) && (moves[2]==moves[8]) && (moves[2] !="") ||
(moves[0]==moves[4]) && (moves[0]==moves[8]) && (moves[8] !="") ||
(moves[2]==moves[4]) && (moves[2]==moves[6]) && (moves[2] !="")
){
document.getElementById("msg").innerHTML=playerTurn+" wins!!";
gameFinished = true;
return true;
}
return false;
}
function checkDraw(){
if (moves.join("").length==9){
return true;
}
return false;
}