Skip to content
Download all docs .md

Multiplayer Pong Example (JavaScript)

This page builds a two-player Pong game that runs in the browser, from an empty folder to a match against another player. It uses a plain HTML canvas so every line is easy to follow; the last section shows how the same code fits PixiJS, PlayCanvas and BabylonJS.

Before you start

You need:

  • A GameFuse account and a game. The game's page on the dashboard shows its game ID and API token.
  • Multiplayer switched on for the game, and its upload key. Both are on the game's Multiplayer tab.
  • Node.js 20 or later, for the gamefuse command that uploads your room code.

The game has two halves:

Part Runs on What it does
Room code (room.js) GameFuse's multiplayer servers Moves the ball, bounces it, keeps the score, picks the winner. The same file for every engine.
Game client Each player's computer Draws the court, sends where the player's paddle is, shows what the room sends back.

The room owns the ball and the score, so a player cannot cheat by changing them. Each player only sends one thing: where their paddle is.

Make the project

Make an empty folder with two files:

pong/
  index.html
  game.js

Add the GameFuse library

index.html loads the GameFuse JavaScript library and then your game. The library's gameFuseFull.js has the multiplayer client, GameFuseMultiplayer, built in. The address is pinned to one commit so the library cannot change under your game:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Pong</title>
  <style>
    body { margin: 0; background: #0b1024; color: #eef0ff; font-family: sans-serif; text-align: center; }
    canvas { background: #000; max-width: 100%; margin-top: 12px; cursor: none; }
  </style>
</head>
<body>
  <p id="status">Loading...</p>
  <canvas id="court" width="800" height="500"></canvas>

  <script src="https://cdn.jsdelivr.net/gh/GameFuseCo/game-fuse-js@de18168ac13a0c0d699cb1cba5f30e869d7ecd37/gameFuseFull.js"></script>
  <script src="game.js"></script>
</body>
</html>

Use gameFuseFull.js, not the .min.js

At this commit the minified gameFuseFull.min.js does not include GameFuseMultiplayer. You can also load the multiplayer client on its own from V3/gameFuseMultiplayer.js at the same address.

Write the room code

The room code is one JavaScript file that GameFuse runs for every match. It is the same for every engine, so a browser player can play against a browser, Unity or Unreal player.

Install the gamefuse command once:

npm i -g gamefuse

In your project folder, make the room code folder. --game-mode pong is the queue name the game client joins; put in your own game ID:

gamefuse multiplayer init --game-name pong --game-mode pong --game 123

That makes a folder called pong-pong-gamefuse-multiplayer with a starter room.js and a .env file. Replace pong-pong-gamefuse-multiplayer/room.js with this:

// Pong for two players. The room owns the ball and the score, so nobody can cheat;
// each player only sends where their own paddle is.
// This is the room code used by every "Multiplayer Pong Example" page in the docs.

const WIDTH = 800;
const HEIGHT = 500;
const PADDLE_HEIGHT = 90;
const PADDLE_X = 30;      // how far each paddle is from its wall
const BALL_SPEED = 300;   // pixels per second when served
const POINTS_TO_WIN = 5;

export default {
  config: {
    minPlayers: 2,
    maxPlayers: 2,
    tickRate: 30,         // update() runs 30 times a second
    reconnectSeconds: 15, // a dropped player gets 15 seconds to come back
  },

  start(room) {
    const [left, right] = room.players; // the first player in is on the left
    room.state.sides = { [left.id]: 'left', [right.id]: 'right' };
    room.state.paddles = { left: HEIGHT / 2, right: HEIGHT / 2 };
    room.state.score = { left: 0, right: 0 };
    serve(room, 1);

    // Tell each player which side they are on.
    room.send(left, 'start', { side: 'left', width: WIDTH, height: HEIGHT, pointsToWin: POINTS_TO_WIN });
    room.send(right, 'start', { side: 'right', width: WIDTH, height: HEIGHT, pointsToWin: POINTS_TO_WIN });
  },

  update(room, dt) {
    const s = room.state;
    if (!s.ball || s.over) return;
    const ball = s.ball;

    ball.x += ball.vx * dt;
    ball.y += ball.vy * dt;

    // Bounce off the top and bottom walls.
    if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }
    if (ball.y > HEIGHT) { ball.y = HEIGHT; ball.vy = -Math.abs(ball.vy); }

    // Bounce off a paddle. Hitting near the end of a paddle sends the ball off at an angle.
    hitPaddle(ball, PADDLE_X, s.paddles.left, -1);
    hitPaddle(ball, WIDTH - PADDLE_X, s.paddles.right, 1);

    // Past a paddle: a point for the other side.
    if (ball.x < 0) point(room, 'right');
    if (ball.x > WIDTH) point(room, 'left');

    room.broadcast('state', {
      ball: { x: Math.round(ball.x), y: Math.round(ball.y) },
      left: Math.round(s.paddles.left),
      right: Math.round(s.paddles.right),
      score: s.score,
    });
  },

  message(room, player, type, data) {
    if (type !== 'paddle' || !room.state.sides) return;
    const side = room.state.sides[player.id];
    const y = Number(data && data.y);
    if (!side || !Number.isFinite(y)) return;
    room.state.paddles[side] = Math.max(PADDLE_HEIGHT / 2, Math.min(HEIGHT - PADDLE_HEIGHT / 2, y));
  },

  playerLeft(room, player, how) {
    // A player quit, or dropped and did not come back in time: the other one wins.
    if (!room.state.sides || room.state.over) return;
    const other = room.players.find((p) => p.id !== player.id);
    if (other) finish(room, other);
  },

  async gameEnd(room, result) {
    if (result.winnerId) await room.gamefuse.users.addScore(result.winnerId, 1);
  },
};

function serve(room, direction) {
  room.state.ball = {
    x: WIDTH / 2,
    y: HEIGHT / 2,
    vx: BALL_SPEED * direction,
    vy: BALL_SPEED * (Math.random() - 0.5),
  };
}

// side: -1 for the left paddle, 1 for the right. Only bounces a ball moving toward that paddle.
function hitPaddle(ball, paddleX, paddleY, side) {
  const movingToward = side < 0 ? ball.vx < 0 : ball.vx > 0;
  const closeInX = Math.abs(ball.x - paddleX) < 12;
  const closeInY = Math.abs(ball.y - paddleY) < PADDLE_HEIGHT / 2 + 6;
  if (!movingToward || !closeInX || !closeInY) return;
  ball.vx = -ball.vx * 1.05;                  // a little faster every hit
  ball.vy += (ball.y - paddleY) * 5;
}

function point(room, side) {
  const s = room.state;
  s.score[side] += 1;
  room.broadcast('point', { side, score: s.score });

  if (s.score[side] >= POINTS_TO_WIN) {
    const winnerId = Object.keys(s.sides).find((id) => s.sides[id] === side);
    finish(room, room.players.find((p) => String(p.id) === winnerId));
    return;
  }
  serve(room, side === 'left' ? 1 : -1);      // serve toward the player who lost the point
}

function finish(room, winner) {
  room.state.over = true;
  const side = room.state.sides[winner.id];
  room.broadcast('winner', { side, name: winner.name });
  room.end({ winnerId: winner.id });
}

What each part does:

  • config asks for 2 players, runs update 30 times a second, and holds a dropped player's seat for 15 seconds.
  • start runs once both players are in. The first player in plays on the left. Each player is told their side.
  • update moves the ball, bounces it off the walls and paddles, scores points, and sends every player a state message: the ball, both paddles and the score.
  • message takes a player's paddle message and moves only that player's paddle, kept on the court.
  • playerLeft gives the match to the other player if someone quits or does not come back in time.
  • gameEnd adds 1 to the winner's GameFuse score after room.end.

The messages, which every game client below uses:

Message Who sends it Data
start room, to each player { side: "left" or "right", width: 800, height: 500, pointsToWin: 5 }
state room, 30 times a second { ball: { x, y }, left, right, score: { left, right } } (left and right are the middles of the paddles)
point room { side, score }: who scored
winner room { side, name }
paddle each player, up to 20 times a second { y }: the middle of their paddle, 45 to 455

The court is 800 by 500, with (0, 0) at the top left. The paddles are 90 tall and 30 in from each wall.

Upload the room code to GameFuse

Open the .env file that init made in your project folder and put in your upload key from the game's Multiplayer tab:

# .env  (keep it out of git: it holds a secret)
GAMEFUSE_UPLOAD_KEY=mpk_your_upload_key
GAMEFUSE_GAME_ID=123

init already added .env to your .gitignore. Never put the upload key in your game.

Check the room code, then upload it:

gamefuse multiplayer validate
gamefuse multiplayer deploy

validate runs the same check GameFuse's servers run and uploads nothing. deploy checks, uploads and makes it the live version for the pong queue. New matches use it at once.

To see what your room code logs while you play:

gamefuse multiplayer logs --follow

Write the game client

game.js signs the player in as a guest, joins the pong queue, sends the mouse's height as the paddle, and draws whatever the room sends back. Put in your own game ID and API token:

const GAME_ID = 123;                      // your game's ID
const GAME_TOKEN = 'your-game-api-token'; // your game's API token

const canvas = document.getElementById('court');
const draw = canvas.getContext('2d');
const statusText = document.getElementById('status');

let mySide = null;   // 'left' or 'right', from the room's 'start' message
let state = null;    // the latest 'state' message: ball, paddles, score
let myPaddle = 250;  // where my mouse says my paddle is

// The mouse moves my paddle. The canvas can be shown smaller than 800 x 500, so scale to the court.
canvas.addEventListener('mousemove', (event) => {
  const box = canvas.getBoundingClientRect();
  myPaddle = (event.clientY - box.top) * (canvas.height / box.height);
});

async function play() {
  const multiplayer = new GameFuseMultiplayer({ gameId: GAME_ID, gameToken: GAME_TOKEN });

  statusText.textContent = 'Signing in...';
  await multiplayer.signInAsGuest();

  statusText.textContent = 'Waiting for another player...';
  const room = await multiplayer.joinQueue('pong', { clientVersion: '1' });

  room.on('message', (type, data) => {
    if (type === 'start') {
      mySide = data.side;
      statusText.textContent = 'You are on the ' + mySide + '. First to ' + data.pointsToWin + ' wins.';
    }
    if (type === 'state') state = data;
    if (type === 'winner') {
      statusText.textContent = data.side === mySide ? 'You win!' : data.name + ' wins.';
    }
  });

  room.on('reconnecting', () => { statusText.textContent = 'Connection lost. Getting back in...'; });
  room.on('reconnected', () => { statusText.textContent = 'Back in.'; });
  room.on('closed', (reason) => {
    if (reason === 'no_match') statusText.textContent = 'Nobody else is online. Reload to try again.';
  });

  // Send my paddle 20 times a second (the room accepts up to 60 messages a second).
  setInterval(() => {
    if (mySide) room.send('paddle', { y: Math.round(myPaddle) });
  }, 50);
}

function drawCourt() {
  draw.fillStyle = '#000';
  draw.fillRect(0, 0, 800, 500);

  draw.fillStyle = '#333';
  for (let y = 0; y < 500; y += 25) draw.fillRect(399, y, 2, 12); // the dashed middle line

  if (state) {
    // My own paddle follows my mouse at once; the other one is where the room says it is.
    const left = mySide === 'left' ? myPaddle : state.left;
    const right = mySide === 'right' ? myPaddle : state.right;

    draw.fillStyle = '#8f9bff';
    draw.fillRect(24, left - 45, 12, 90);
    draw.fillStyle = '#ff8a4c';
    draw.fillRect(764, right - 45, 12, 90);

    draw.fillStyle = '#fff';
    draw.fillRect(state.ball.x - 5, state.ball.y - 5, 10, 10);

    draw.font = '40px monospace';
    draw.textAlign = 'center';
    draw.fillText(state.score.left, 340, 50);
    draw.fillText(state.score.right, 460, 50);
  }
  requestAnimationFrame(drawCourt);
}

drawCourt();
play().catch((error) => { statusText.textContent = error.message; });

Play it

The page has to be served over http://, not opened as a file. From the pong folder:

npx serve .

Open the address it prints in two different browsers, or in a normal window and a private window. Two tabs of the same browser are the same guest, so they cannot play each other.

Both show "Waiting for another player..." until the second one joins. Then move the mouse up and down over the court. First to 5 wins, and the winner gets 1 point on their GameFuse score.

When it works, put the game online with GameFuse Hosting: gamefuse hosting deploy . from the pong folder.

Using PixiJS, PlayCanvas or BabylonJS

Keep everything in play(): signing in, joining, the messages and sending the paddle. Only the drawing changes. Each frame, put your sprites or meshes where state says:

Thing Where
Ball state.ball.x, state.ball.y (court pixels, 0 to 800 and 0 to 500)
Left paddle x 30, y state.left (or myPaddle if mySide is 'left')
Right paddle x 770, y state.right (or myPaddle if mySide is 'right')
Score state.score.left, state.score.right

In PixiJS, set sprite.position.set(x, y) in app.ticker. In PlayCanvas, add the library under External Scripts (see Getting Started) and move entities in a script's update. In BabylonJS, map the court to world units (for example x / 100) and set mesh.position in scene.onBeforeRenderObservable.

Next