How to build a game of Tic Tac Toe from scratch

Hi and welcome to my video where I teach you at the giffgaff family how to code your very own game of Tic Tac Toe. This is going to be a super beginner tutorial. If you’ve never touched code in your life, this is definitely the video for you.

In this 15 minute video i’m going to walk you through how to set up your code editor as well as take you through step by step so by the end you’ll have your very own basic game of Tic Tac Toe.

The reason it’s going to be super basic is that you can then take it, make your own, level up, style it to the max. Go wild go mental!

If you would like a more in depth explanation into each in built method that we’re going to be using please go to my youtube channel where i do go into them in way more detail. But hey, it’s not for everyone so i’m going to keep this one really light and simple.

Once you have finished your game I would absolutely love for you to share it with me, i’d love to see what you’ve made so do reach out to me on YoutTube, Twitter, instagram or whatever.

Okay, so let’s get going. Big love to the giffgaff community.

The first thing we need to do is download the atom editor to your laptop. This will allow us to write code in our project files. If you haven’t done so already, i suggest heading over to atom.io and pausing right here until it has been downloaded. I’ve actually made a tutorial on the ideal set up of atom for your project but if you want a more in depth walk through on the pros of Atom and more tips please head over to that tutorial on my youtube.

Ok, now that we have Atom, search for your command line tool on your computer. On a mac simply go to your launch pad and type terminal. On a PC you have to search for your command line prompt. As I have a mac I’m going to be using a terminal.

Now open up your terminal and create a folder on your desktop for your projects. Do so by listing out all of the directories and use cd to go into the desktop directory. I’m going to create a folder called Tic Tac Toe. I will do so using the command mcdir. So let’s type mcdir tic-tac-toe

Let’s go into the folder again so type cd tic-tac-toe

If you ever want to get out of this folder we use the command cd . .

Now we need to create files in this folder and you can do so using the command called touch. Touch will create files. We need to create a html file, css file for our styling and a javascript file to hold our javascript. I’m going to choose to call them: index.html app.js and style.css

Now using atom we will prompt the project to open in our atom code editor.

Now let’s get to writing some code

We will start off with our html file. Html is a hypertext markup language file format used as the bass of a webpage. What i’m adding here is a standard html body plate.

The first thing we are going to do is give our project a title between the two title tags <title>Tic Tac Toe<title>

As this is inbetween the two head tags it will not show up on our browser. It will however show up in our tab.

Now let’s create our tic tac toe grid using divs

We will need 9 divs that we will style into squares. If you refresh your browser you will not see these divs as they have no styling. If you inspect the page however, by hitting ctrl and left clicking in the browser you will see that they are in fact there.

To add styling we need some css or cascading style sheets. css is the style sheet language used for describing the presentation of a document written up in a markup language like html.

We already have a css file called style.css we just need to link it to our html file using a link tag like this: <link rel=”stylesheet”></link>

We will also put the relative path of our style.css file in. As it’s in the root of our project like this: <link rel=”stylesheet” href-”style.css”></link>`

Now lets flip over to our style sheet to make the divs look like squares in a grid.

Let’s start with making our squares. We need to pick out the divs from our html file and style them in our css file

Ok now save your files and flip over to our browser. Great, if they don’t look like a grid yet, or stacked on top of each other, you can fix this by putting them in another div that is the square shape of our grid.

Go back to your html and put our divs in a div and give them a class name of a grid.

And now lets flip to our css file to style it. If you want to target a class in our html rather than an element itself then we use a dot before the name.

Buy using .grid I’m saying I want to target the div with a class grid in our html and assign some styling to it.

As I want my grid to be 3 by 3 squares of 200px height and width I will need to make my grid 600px x 600px to fit them all in.

We also need to make the nine divs go left to right rather than stack. For this we use display: flex;

Then refresh - amazing!

Now it’s time to write some javascript in order to give our game some functionality. But first we need to add a script tag in our html file to let our javascript tag talk to our browser. Like this:

<script src="app.js" charset="utf-8"></script>

Now flip over to your javascript file and let’s start by writing a dom avendus. This is what the script tag is listening to.

document.addEventListener('DOMContentLoaded', () => {}

From now on all of our code has to be written in this avendus.

As with the style sheet we need to pick out elements from our javascript to know what we want to target. We do so using document query selectors.

Again, we will pick out the divs in the divler class of the grid. Using a dot we state that is a class. So type .grid div and assign this to the const? Squares. Please note we used .querySelectorAll () as we want all the squares.

Now to make sure we only want the divs and the divler class of grid to be styled this way, in case we want to add other divs in the future, we use this syntax: .grid div

Let’s add this to the css file too.

Now the first thing we want to do is add in event listener into each square on our grid. I’m going to do this because I want to listen out for any time a square is clicked on and when it is clicked I want something to happen.

There is an inbuilt javascript method called .forEach () that will help us do this. We will also use it with an arrow function. =>`

Arrow functions are a feature of eS6 and above so if your atom code editor isn’t liking using the arrow function, i would suggest setting up extra bonus preference settings in your code editor as per my video that I mentioned at the beginning of this video.

Okay so let’s cut our squares.

For each - as in for each item - which I’m going to choose to call square, we add an event listener. This event listener means that every time we click a square we evoke a function.

This function, we’re going to call clickOutcome

So now let’s write the function. We are just going to check if this works by making an alert for each time we evoke a function.

Then save and flip to our browser to check. Don’t forget to refresh the browser.

Ok that works great. Let’s comment that out and we need to pass through an e to our function. E stands for event.

We need this to figure out which of our squares has been clicked using our knowledge of arrays, indexes and e targets.

The first thing we’re going to do is turn our 9 squares into an array. We do this by using an inbuilt javascript method called Array .from () This will turn all of the squares being collected into an array.

You will need this for finding out the index of each square. Of our nine squares, each has an assigned index of 0-8. You can find out exactly which one is clicked using etarget and a little function called .indexOf () and assign it to the const called index.

Let’s use console log to see which square has now been clicked. Remember, we can use console log at any point during our javascript to figure out what is going on under the hood. The result of the console log will show up when we inspect the page and click on the console and you will be able to see each outcome.

Now, let’s decide who is currently playing. To start the game let’s decide that the first player is always going to be called player x

So using let you write this: let currentPlayer = ‘PlayerX’ You want player x to be a string and you write it between two single quote marks.

We want to show this in our browser, so flip back to your html and add an <h3> tag with the id of the player. Let’s hardcode that player x will always start the game. No need to worry about player o for now.

Then go to your javascript file and pick this out. As it’s an ID we use the hash for our javascript to recognise this unlike a class. Let’s call this playerDisplay.

IDs are unique unlike classes.

Now in our function we assign the current player to be shown in our browser each time the function is clicked. We do so by using .innerHTML

So each time I click the current player is displayed in the <h3> tag with the ID player.

Now, using an if statement

If that player is currently player x and we want to change it to player O, this is how you write an if statement:

  if (_______) {
    //block of code
  }

  if ( currentPlayer === 'playerX' ) {
    //block of code
  }

So if the current player deeply equals - indicated by the three equals marks - this statement is true. We make the current player now player O.

If the statement is currently false, we simply pass back the string playerX

This is essentially the syntax for an if statement.

Okay let’s check this out in our browser. Ok cool! Now let’s add an X or an O as well as a result of the if statement.

So again, if the player is currently playerX we want to add a class of player X to the index we have clicked. Then we want to change the player to playerO

If the statement is false we add a class of playerO to the square and change it to playerX instead.

I do think it’s fun to make your own images. I’ve had some really cool versions of Tic Tac Toe shared with me in the past purely based on styling.

So now back to our stylesheet to make an X and an O. I’m going to show you how to import images into your stylesheet. First you need to get two png images, each 200px by 200px. You can find them online or you can go to my github, or alternatively you can make your own using editing sites like pixlr.com

Once you have them simply drop them into your folder. Make sure they are at the root of your folder.

Now, using something called background image, we style the playerX class and the playerO class like this:

.playerX {
  background-image: url('cross.png');
}

.playerO {
  background-image: url('circle.png');
}

There are so many other cool things you can do such as add animation and so on. I’ve literally spent hours styling a project before without noticing that the time goes by.

Again if you’re getting stuck or getting error messages please reach out to me on twitter. I’m usually pretty quick at replying.

And amazing! You can now play tic tac toe against a friend.

If you want to build a game that will allow you to play against a computer which tells you if you have won or lost, please do watch my other video on my youtube channel.

Once again, thank you for watching. I hope you enjoyed my video and a big shout out to the giffgaff community.