Build Multiplayer Realtime Tic Tac Toe Game with Socket.io and Vue
Tags: javascript, showdev, vue, tutorial
Published: 2021-11-05 18:52:46


![Photo by [Visual Stories || Micheile](https://unsplash.com/@micheile?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)](https://cdn-images-1.medium.com/max/9446/0*lSNWNj7XtNjts61u)

In this article, we will develop a tic-tac-toe game from scratch using Vue. We will integrate the real time feature with socket.io, so that two players can play the game from different browsers at the same time. 

## Video Tutorial
{% youtube 7eEDH-qQl8Y %}
## Project creation

First, create a blank Vue project  and in the app.vue,remove the hello world component and add the html for the grid. I copied the CSS from this [tutorial](https://dev.to/ayushmanbthakur/how-to-make-tic-tac-toe-in-browser-with-html-css-and-js-28ed). 

We will define 9 blocks with id block_0 to block_8 with class block for each block.
{% gist https://gist.github.com/nilmadhab/a58e8bbb789a174dd1c06c5c144dc7b6.js %}
You will see the result like this. 

![Basic grid implementation](https://cdn-images-1.medium.com/max/2000/1*L7bUoSF9gJXfbfa31ZhfHQ.png)

You can find the Github code till now in this branch.
[**GitHub - nilmadhab/tic-tac-toe-youtube at grid-setup**](https://github.com/nilmadhab/tic-tac-toe-youtube/tree/grid-setup)

## Draw X and O on click

Now, we will define two variables in the data section:

 1. content

 2. turn
{% gist https://gist.github.com/nilmadhab/bff30fa6c945232646ab893ae67c146c.js %}
Content will be an array of length 9, one element for each block of html, initialized with the empty string. When we click one block, we will change the value at that index of the content. Let’s define the function @click, and use it.
{% gist https://gist.github.com/nilmadhab/a2b9d7e3a20bfeac82606001e8438efc.js %}
We will draw the X and O based on the content array and on the click will trigger the draw function in each block.

Now, let’s define the draw function in the methodsection. If the value of turnis true, we will draw X, else we will draw O and change the value of turn. So, first click we draw X andturn becomes false. So, on the second click, we draw O and turn becomes true and so on..
{% gist https://gist.github.com/nilmadhab/d61b729f6cf2637d51a37d0887374933.js %}
![](https://cdn-images-1.medium.com/max/2000/1*uUMEkDHkuszs9dCgZHAfzQ.png)

## Calculate Winner

Now, after every call in the draw function, we have to calculate if the game is finished or not. If finished, we can find who is the winner and display it. 

We will declare three variables more in the data section.
{% gist https://gist.github.com/nilmadhab/9cc69e4d8016eb8ea4615d158b75a68e.js %}
In the template section, we will add two h2 tags to declare the winner or a tie.
{% gist https://gist.github.com/nilmadhab/ef2f3774a4b60b4dc4a9f3966c0c127b.js %}
Now, we are ready to define calculateWinner function. The logic is if the same row, column or diagonals are occupied by the same player, he/she wins.
{% gist https://gist.github.com/nilmadhab/d5cc96b29d122d861d21c2dd4d8e6a4b.js %}
We call this function, every time we draw.
{% gist https://gist.github.com/nilmadhab/e82ab89af063fac21012925fdd34e6f1.js %}


![](https://cdn-images-1.medium.com/max/2000/1*7TDPy3n98A3AKhzJMv9o8A.png)

## Calculate Tie

Now we will define tie function. The logic is even if there is an empty block, the game is not tied.
{% gist https://gist.github.com/nilmadhab/12be70427dda0221d7bf8dcd1614f179.js %}
We will define this function is method section and call it from draw method.

Entire script section till now.
{% gist https://gist.github.com/nilmadhab/bd66466405a6aa61c68e70aabff6e6b3.js %}
![](https://cdn-images-1.medium.com/max/2000/1*0kSWW3YxhywWnNrrm2UpGw.png)

## Reset Board

Now, when the game is tied or over, we have to show an option to reset the board. 
{% gist https://gist.github.com/nilmadhab/b6aa8e0a0bdd03cc23c9266eadc781dc.js %}
We will define the resetBoard function next. We reset the content array and all the other variables.
{% gist https://gist.github.com/nilmadhab/05db887226a570bd5bee0cae31b9babe.js %}
![reset board](https://cdn-images-1.medium.com/max/2000/1*HfbOGV1R1gv_8ATCS1ZDxQ.png)

Github code till now.
[**GitHub - nilmadhab/tic-tac-toe-youtube at game-logic-implemented**](https://github.com/nilmadhab/tic-tac-toe-youtube/tree/game-logic-implemented)

## Multiplayer mode Using Socket.io

Now, we will integrate the project with Socket.io, so that two players can play the game at the same time. When one player clicks X, it should appear on the second player’s screen and when the second player clicks O, it should appear on the first player’s screen. How to implement it?

Here, [socket.IO](https://socket.io/docs/v3/) comes handy. The documentation says,

![socket.js documentation](https://cdn-images-1.medium.com/max/2148/1*sdrbtVfTRyR7C_px0aJlVA.png)

If you want to watch the video tutorial, you can download the above branch and fast forward the video to 35:42 mins.
{% youtube 7eEDH-qQl8Y %}
## Set up server for socket.io

We will first create a folder outside the Vue project. Create a file server.js inside  the folder. We will create an express server inside the folder. 

Run npm init. It will set apackage.json file.

Then run

npm i socket.io

It will install socket.io in the project.

### server.js

Now. lets create a server and integrate socket.io.
{% gist https://gist.github.com/nilmadhab/03f2547cfa200393e3af083b4c05a642.js %}
We will set cors rule, so that our vue.js project running on port 8080 can access the server.

We will emit an event from the server and our Vue client should listen to it and receive it.

Run the server with

node server.js

### App.vue

Now, we will set up socket.io in client side.

Run

npm i socket.io-client

inside the vue.js project from terminal.

We will import the library by

    import io from ‘socket.io-client’
    const socket = io(“[http://localhost:3000](http://localhost:3000)")

inside the script section.

In the created hook, we will listen to the event.
{% gist https://gist.github.com/nilmadhab/ec16793fef18a71e4a211193027d3212.js %}
You will see “youtube tutorial” will appear in the console.

The client can also talk to the server in the same way.

## Game Logic with Socket.io

 1. After we call the draw function, player 1 client will send the event to the server. 

 2. When the server receives it, it will broadcast it to the player 2. 

 3. Player 2 will then update the grid. 

 4. Then player 2 will click O and call the draw function, it will send the event to the server.

 5. The server will broadcast it to player 1.

 The game will keep going like this.
{% gist https://gist.github.com/nilmadhab/bfead2818daa928485af17831638ce8a.js %}> # We also need to pass a parameter, drawFromOther, in the draw function. Depending upon this flag, we will emit the event again. If the drawFromOther flag is set to false, we will send the play event.

Now, we will update the template. We will send the drawFromOtheras false, which means the event will be sent to the server.
{% gist https://gist.github.com/nilmadhab/e65d7f02dfec5095a944785cb51d7df5.js %}
Server.jswill receive the event and broadcast it.
{% gist https://gist.github.com/nilmadhab/855ee904b93bbe20be5e44b37dca5be5.js %}
Now, the client will receive the event in created hook.
{% gist https://gist.github.com/nilmadhab/8a30317083ff26c16d7023b3cd5be6a8.js %}
It will receive the event and draw at the index, but we pass drawFromOther param as true, so that the event does not again sent to the server.

## Complete code of App.vue
{% gist https://gist.github.com/nilmadhab/f871d8127df8ced07eec94ca3e749649.js %}
That's it. The multiplayer game is ready to be played. Open localhost:8080 in two different browsers and click alternatively. The game should work.

![](https://cdn-images-1.medium.com/max/2886/1*SWKyuI8eXJrBMmBo7crogg.png)