HTML code : Tic _ Tac _ Toe Game

  • Tic-Tac-Toe is a pen-paper game. I am sure you would have played this game once in your childhood. This is a game for two players one is X and other is 0. They mark the spaces of 3*3 grid with 0 and X one by one.The player who succeeds in placing three respective marks in a horizontal, vertical, or diagonal row wins the game.
  • I am going to create this game with HTML 5 canvas and JavaScript. HTML5 Canvas is used for drawing the 3*3 grid boxes and Javascript is used for develop the logic for the game.
  • You must have the basic knowledge of html language and html canvas to understand the given program. You can learn HTML from our HTML Tutorial.


You must have the basic knowledge of html language and html canvas to understand the given program. Please see our HTML Tutorial.

tic-tac-toe

HTML code to create Tic-Tac-Toe Game

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var draw;
var values;
var wincombinations;
var turn = 0;
var theCanvas;
var c;
var cxt;
var squaresFilled = 0;
var w;
var y;
//Instanciate Arrays
window.onload=function(){
draw = new Array();
values = new Array();
wincombinations = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
for(var l = 0; l <= 8; l++){
draw[l] = false;
values[l]='';
}
}
//Game methods
function canvasClicked(canvasNumber){
theCanvas = "canvas"+canvasNumber;
c = document.getElementById(theCanvas);
cxt = c.getContext("2d");
if(draw[canvasNumber-1] ==false){
if(turn%2==0){
cxt.beginPath();
cxt.moveTo(10,10);
cxt.lineTo(40,40);
cxt.moveTo(40,10);
cxt.lineTo(10,40);
cxt.stroke();
cxt.closePath();
values[canvasNumber-1] = 'X';
}
else{
cxt.beginPath();
cxt.arc(25,25,20,0,Math.PI*2,true);
cxt.stroke();
cxt.closePath();
values[canvasNumber-1] = 'O';
}
turn++;
draw[canvasNumber-1] = true;
squaresFilled++;
checkForWinners(values[canvasNumber-1]);
if(squaresFilled==9){
alert("Game Draw!");
location.reload(true);
}
}
else{
alert("Sorry, This Space is Already Occupied!");
}
}
function checkForWinners(symbol){
for(var a = 0; a < wincombinations.length; a++){
if(values[wincombinations[a][0]]==symbol&&values[wincombinations[a][1]]== symbol&&values[wincombinations[a][2]]==symbol){
alert(symbol+ " WON!");
playAgain();
}
}
}
function playAgain(){
y=confirm("PLAY AGAIN?");
if(y==true){
alert("Thank You");
location.reload(true);
}
else{
alert("Come Back Again!");
}
}
</script>
</head>
<body>
<marquee direction="right"><img src="wall.jpg" /></marquee>
<center>
<div>
<h3><font color="red">Tic - Tac - Toe : Created by www.eitworld.com</green></h3>
<canvas id = "canvas1" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(1)"></canvas>
<canvas id = "canvas2" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(2)"></canvas>
<canvas id = "canvas3" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(3)"></canvas><br>
<canvas id = "canvas4" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(4)"></canvas>
<canvas id = "canvas5" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(5)"></canvas>
<canvas id = "canvas6" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(6)"></canvas><br>
<canvas id = "canvas7" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(7)"></canvas>
<canvas id = "canvas8" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(8)"></canvas>
<canvas id = "canvas9" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(9)"></canvas>
</div>
</center>
<marquee direction="right"><img src="wall.jpg" /></marquee>
</body>
</html>


Click the Button to See Demo

Code Explanation

  • This game can be played by two human players who can play one by one by using mouse.
  • When the game draw then the game will restart automatically.
  • When a user won then he will be asked to restart the game If so, the game will restart. If not, then same page will be in-front of him.
  • Now let's go through the given code. You must have the basic knowledge of HTML5 Canvas and JavaScript.
  • We will learn this code into two parts: In First part we will see the creation of 3*3 grid by using HTML5 Canvas and in second part we will see the logic of the game by using JavaScript.
  • Now let see the given line of code:

    <canvas id = "canvas1" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(1)"></canvas>
  • The above line of code will create a square of (60*60) size. Canvas is basically used for applying the graphics in web pages. Here we are creatig 3*3 grid through this canvas.
  • In this line of code: id must be mention so that we won't mistake it for another canvas. width and height specify the size of box. style element create a 3px border of blue color. onclick element is very crucial withouth this we can't do anything with this game.onclick is a javascript function which shows that when we click on the canvas it will do something.Now what it will do ?drawing! A circle or an x. we will learn in the second part that is JavaScript.
  • But first, we have to create all the 9 canvasses, use the same line of code for each canvas box but change their id to canvas + "canvas number" and on the onclick value change the number inside "canvasClicked()" to the number of that canvas. as given below:

    <canvas id = "canvas2" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(2)"></canvas>
    <canvas id = "canvas3" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(3)"></canvas><br>
    <canvas id = "canvas4" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(4)"></canvas>
    <canvas id = "canvas5" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(5)"></canvas>
    <canvas id = "canvas6" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(6)"></canvas><br>
    <canvas id = "canvas7" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(7)"></canvas>
    <canvas id = "canvas8" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(8)"></canvas>
    <canvas id = "canvas9" width="60" height="60" style="border:3px solid blue" onclick="canvasClicked(9)"></canvas>
  • When a canvas is clicked, it expects the browser to look for the function canvasClicked on the html. Now where is canvasClicked? It is present in our second part that is Javascript code. So now we are going to discuss about Javascript code that will decide the logic for the game.
  • We will add the Javascript in our html document by writing the given statement in the head part:

    <script type="text/javascript">
  • A quick glance shows us that there are 4 functions: an anonymous function upon window load,canvasClicked, checkForWinners, and playAgain. Plus a lot of lines outside the functions.

  • The codes outside are global variables. They are used throughout the life of the html page to hold values that are of importance to the game. In JavaScript variable can be declared without datatypes, JavaScript can identify the type of variable by going throgh its value.Here is the declaration of the JavaScript variable:

    var turn = 0;
  • The anonymous function upon the loading of the window is what we use to instanciate all the values for arrays. We use values array to see what the canvas contains and we use the draw array to check if the canvas contains something already to prevent using that canvas again. Using our for loop we automate the giving of values to the draw and values arrays. We can simultaneously give them values since they have the same length.
  • Array winCombinations is a multi-dimensional array:meaning it goes through two or more indices. We use two. The main index tells us that this particular index holds another array of values. The second index lets us access particular values of that particular base index. In here we give the winCombinations all the possible combinations where a player could win in Tic - Tac - Toe, and we will be using it shortly.
  • Now we will see each Javascript function in details:

  • First function which we are going to explain is : canvasClicked

    function canvasClicked(canvasNumber)
    theCanvas = "canvas"+canvasNumber;
  • On the first call, canvasClicked function provides the number we sent it from the body of the html to the variable canvasNumber. Variable theCanvas give us the complete name of any of the canvasses down on the body. So if we clicked canvas4, canvasClicked will receieve 4, then instantly give theCanvas the value "canvas4". This is how we identify that what canvas we are now using.
  • Below we have the some next lines of code given above. Please read the comments in blue to learn the use of these statements:

    c = document.getElementById(theCanvas);//variable c contains the canvas we want, document.getElementById is a JavaScript Function which is used to access parts of the html page dynamically. There is an id attribute present in the body part which corresponds to the "theCanvas" variable.
    cxt = c.getContext("2d");//this gives us the context of the canvas. We will use 2d to draw in the x and y coordinates.
    if(draw[canvasNumber-1] ==false)//this condition tells us that the canvas should not be occupied because we have to draw on it.
    {
    if(turn%2==0)//This condition determines whose turn it is now.
    {
    //It's time to draw in canvas.
    cxt.beginPath(); //this statement shows that we are going to draw a new path.
    cxt.moveTo(10,10);//this statement use to position the drawing cursor to a coordinate (10,10).
    cxt.lineTo(40,40);//this statement draw a straight line from the starting position (drawing cursor) to a new position that is (40,40).
    cxt.moveTo(40,10);//Again,this statement use to position the drawing cursor to a coordinate (40,10).
    cxt.lineTo(10,40);//Again,this statement draw a straight line from the starting position (drawing cursor) to a new position that is (10,40).
    cxt.stroke();//this statement make the lines visible.
    cxt.closePath();// Will put away the cursor for us.
    values[canvasNumber-1] = 'X';//This gives the array values the value of 'X', meaning X just marked this canvas.
    }
    else{//If it isn't X's turn, it's 0's turn! Let's draw a circle.
    cxt.beginPath();
    cxt.arc(25,25,20,0,Math.PI*2,true);//This statement will print the circle.In this arc function first two arguments shows the center of circle that is (25,25), third argument shows the radius of the circle that is 20, here fourth and fifth arguments shows the starting and ending angle here starting angle is 0 and ending angle is 2*Math.PI which is must for drawing a circle.
    cxt.stroke();
    cxt.closePath();
    values[canvasNumber-1] = 'O';
    }
    turn++;//We increment the turn so that we now that next turn would be the other player.
    draw[canvasNumber-1] = true;//This statement will tell that particular canvas is filled.
    squaresFilled++;//We tell that the number of canvasses filled has gone up.
    checkForWinners(values[canvasNumber-1]);//Another function! We'll give it the content of the current canvas so we know which player just made a turn
    if(squaresFilled==9){//If all the boxes are filled than it will show tha JavaScript alert that is Game Draw.
    alert("Game Draw!"); location.reload(true); } } else{ alert("Sorry, This Space is Already Occupied!");//If you clicked on the occupied space than it will show the message Sorry, This Space is Already Occupied!
    } }
  • Now After drawing the symbols we need to check if that turn decided the game. Hence, go towards the next function that is checkForWinners:

    function checkForWinners(symbol){
    for(var a = 0; a < wincombinations.length; a++){
    if(values[wincombinations[a][0]]==symbol&&values[wincombinations[a][1]]== symbol&&values[wincombinations[a][2]]==symbol){
    alert(symbol+ " WON!");
    playAgain();
    }
    }
    }
    function playAgain()
  • The function checkForWinners takes the argument symbol so that we know what current player just made a move. In the for loop we use the array winCombinations and give it to value.

  • Now as you can see there are three signs of equal operator if the symbol is equal to three different canvas locations. That is where we use the winCombinations array. See, the variable a will tell us that the array is currently on a particular combination, and the static numbers of 0,1, and 2 each correspond to the values inside that current index, since there should be 3 to make a line in Tic - Tac - Toe.
  • Now if our if proves true, that symbol would win. Of course the value of symbol, not symbol itself. So we print a message that the current player(the current value of symbol) won. If not, it's the next players turn.
  • To see what happens if someone wins lets discuss the last function : playAgain.
  • Below we have the some next lines of code given above. Please read the comments in blue to learn the use of these statements:

    function playAgain() {
    y=confirm("PLAY AGAIN?");// confirm will show a popup box with the values "OK" or "CANCEL", choosing ok will give the value "true" to y, otherwise, false.
    if(y==true){
    alert("Thank You");//We reload the page automatically!
    location.reload(true);
    }
    else{
    alert("Come Back Again!");//Don't want to quit? You have to close it yourself. This one I did not cover.
    }

    Now, we've finished the whole game Tic - Tac - Toe! Enjoy with the game..