Above you can watch speed code video of this example. Also codes are in this repo. Below I will give some explanations about the example.
We start this example in a div
which we name wrapper
class that surrounds the area where the game is played. In this wrapper, we add 9 div
with class name of cell
and one div
with class name of info
where we will use to display information about game.
We give our wrapper element 300px width and 5px padding
so that we have a balanced grid look with the 5px outer space margin
of the cell elements. Since there will be only one letter (X or O) in the cell, we give line height and font size accordingly. The letter of the player who clicks the cell in the game will be added to the cell’s class list. For this, we style special background colors for .cell.O
and .cell.X
states and the corresponding player letter for pseudo ::after
elements. We could also add the letter to the DOM by Javascript, but it will be more complex and hard to maintain.
In the Javascript section, first we create a function that will invoke itself and name it tictactoe
. With this encapsulation we prevent our variables from getting confused with other future variables in Javascript. The turn
variable, can get X or O, indicates which player’s turn it is. And We will use the playing
variable to check if the game is active or not.
We get cell
elements and we assign cellClick
function for the click events. Also we create an array named cells
which we use to hold a reference to DOM element, value of the cell and a reset method for our cells. Also we get info
element to print according messages on it.
On every move we have to check if there is a winner. For this we create checkWinner
method. In a Tic-Tac-Toe game there are eight possibility to win for each player and of course a draw possibility. We check all nine possibility and if there is a winner or a tie, we set playing
variable to false to stop the game, print according message to info
element.
Finally we add a restart button when game is over with the checkWinner
method. We return a restart
method for our initial tictactoe
variable. And assign this method toonclick
event of the button.