DEV Community

Cover image for Multiplayer TicTacToe With Websockets
Luthfi Khusyasy
Luthfi Khusyasy

Posted on

Multiplayer TicTacToe With Websockets

Recently I'm trying to learn about websockets and I decided why not create a Multiplayer TicTacToe game using websocket.

Live Website
Source Code

note: this is an old post (30 May 2022) from my website, posting for archiving purposes

Objectives

Learning more about websockets and how to implement them in a realtime game application. Basically websockets are a way to connect to a server for back and forth communication, this is very useful for realtime applications especially in multiplayer games. Also often used in client side websites.

The goal of this project is:

  1. Create format for websockets.
  2. Implement the server.
  3. Create the game using Vue.

1. Create format for websockets.

Because I am new to websockets, I am trying to understand the format that will be used to communicate with the server, and to be honest I don't find many resources talking about this, so I am going to try to create my own format.

{
  "type": <type of message>,
  "data": {
    <any data that is needed>
  }
}
Enter fullscreen mode Exit fullscreen mode

From the type of message, the data will be used to determine what the server or client should do. For example, if the type is "move", the data will be used to determine which player moved, and where.

{
  "type": "move",
  "data": {
    "user": <user data>,
    "x": <row number>,
    "y": <col number>
  }
}
Enter fullscreen mode Exit fullscreen mode

The message above means that the user has moved to row number x and column number y.

2. Implement the server.

I used express to create the server, and I used express-ws to create the websocket so that I can easily use websockets just like other HTTP requests endpoint in express, as an simple example, the following code is used to create the websocket server.

const express = require('express');
const app = express();
const ws = require('express-ws')(app);

app.ws('/', (ws, req) => {
  ws.on('message', (msg) => {
    const { type, data } = JSON.parse(msg);
    if (type === 'move') {
      // do something with data
    }
  });
});
Enter fullscreen mode Exit fullscreen mode

But for storing Users and Rooms in the server, I used an array... for now. I think it's okay, because I only make this for learning purposes. If I ever need to store more data, I can easily extend this project to use database.

3. Create the game using Vue.

This part is basically creating a TicTacToe game but using Vue. I tried to use a new ui library called Naive UI, I think it looks nice, but I don't know if it's the best way to use the library.

website login page

winning at tictactoe

Top comments (0)