Multiplayer Pong Example (REST API)¶
This page builds the server side of a two-player Pong game and a computer player that joins matches from the command line, so you can see every API call GameFuse Multiplayer makes. Play against the computer from the JavaScript, Unity or Unreal version: they all join the same rooms.
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
gamefusecommand 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.
How a player gets into a match¶
Getting into a match takes two REST calls and one WebSocket:
| Step | Call | Returns |
|---|---|---|
| 1. Sign in | POST /api/v3/users/guest with { game_id, game_token }, once per player. A player with an account uses the authentication_token from signing in instead. |
{ id, username, authentication_token, guest: true } |
| 2. Get a ticket | POST /api/v3/multiplayer/tickets with the header authentication-token, before every join |
{ ticket, host_url, expires_in: 60 } |
| 3. Join | A WebSocket to host_url, carrying the ticket |
The room's messages |
Try the first two with curl (put in your game ID and API token):
curl -X POST https://gamefuse.co/api/v3/users/guest \
-H 'Content-Type: application/json' \
-d '{"game_id": 123, "game_token": "your-game-api-token"}'
# {"id":4821,"username":"Guest-4821","authentication_token":"Bq7...","guest":true}
curl -X POST https://gamefuse.co/api/v3/multiplayer/tickets \
-H 'authentication-token: Bq7...'
# {"ticket":"eyJhbGciOi...","host_url":"wss://...","expires_in":60}
The ticket lasts 60 seconds and is good for one join. A 403 means Multiplayer is off for the game.
Step 3 uses the Colyseus 0.16 protocol, which the multiplayer servers run on. You do not write that by hand: the GameFuse client libraries do steps 1 to 3 for you and reconnect when a connection drops. This page uses the JavaScript one, gameFuseMultiplayer.js, which runs in Node as well as in browsers. For Unity and Unreal see the client references.
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 command-line player can play against a browser, Unity or Unreal player.
Install the gamefuse command once:
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:
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:
configasks for 2 players, runsupdate30 times a second, and holds a dropped player's seat for 15 seconds.startruns once both players are in. The first player in plays on the left. Each player is told their side.updatemoves the ball, bounces it off the walls and paddles, scores points, and sends every player astatemessage: the ball, both paddles and the score.messagetakes a player'spaddlemessage and moves only that player's paddle, kept on the court.playerLeftgives the match to the other player if someone quits or does not come back in time.gameEndadds 1 to the winner's GameFuse score afterroom.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:
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:
Make the computer player's project¶
Make a folder and download the client library into it. It is one file with no dependencies, pinned to one commit:
mkdir pong-bot && cd pong-bot
curl -o gameFuseMultiplayer.js https://cdn.jsdelivr.net/gh/GameFuseCo/game-fuse-js@de18168ac13a0c0d699cb1cba5f30e869d7ecd37/V3/gameFuseMultiplayer.js
You need Node.js 22 or later, which has fetch and WebSocket built in.
Write the computer player¶
bot.js signs in as a guest (step 1), joins the pong queue (steps 2 and 3), and moves its paddle toward the ball. It plays one match and stops. Put in your own game ID and API token:
// bot.js: a computer Pong player. Run it with: node bot.js
const { GameFuseMultiplayer } = require('./gameFuseMultiplayer.js');
const GAME_ID = 123; // your game's ID
const GAME_TOKEN = 'your-game-api-token'; // your game's API token
const SPEED = 240; // how fast the computer moves its paddle, pixels a second
async function main() {
const multiplayer = new GameFuseMultiplayer({ gameId: GAME_ID, gameToken: GAME_TOKEN });
await multiplayer.signInAsGuest(); // POST /api/v3/users/guest
console.log('Signed in. Waiting for another player in the pong queue...');
// POST /api/v3/multiplayer/tickets, then the WebSocket join
const room = await multiplayer.joinQueue('pong', { clientVersion: '1' });
let mySide = null;
let paddle = 250;
let ballY = 250;
room.on('message', (type, data) => {
if (type === 'start') {
mySide = data.side;
console.log('Match started. I am on the ' + mySide + '.');
}
if (type === 'state') ballY = data.ball.y;
if (type === 'point') console.log('Score: ' + data.score.left + ' - ' + data.score.right);
if (type === 'winner') console.log(data.side === mySide ? 'I won!' : data.name + ' won.');
});
room.on('closed', (reason) => {
console.log('Room closed: ' + reason);
process.exit(0);
});
// 20 times a second: move part of the way toward the ball, and tell the room.
setInterval(() => {
if (!mySide) return;
const step = SPEED / 20;
paddle += Math.max(-step, Math.min(step, ballY - paddle));
room.send('paddle', { y: Math.round(paddle) });
}, 50);
}
main().catch((error) => {
console.error(error.message);
process.exit(1);
});
Play it¶
Start a second one in another terminal and the two computers play each other:
Signed in. Waiting for another player in the pong queue...
Match started. I am on the left.
Score: 1 - 0
...
I won!
Room closed: ended
Each run of node bot.js is a new guest, because Node has no localStorage to remember the first one. To keep one player, save multiplayer.token after signing in and pass it to multiplayer.useToken(token) next time.
Or play the computer yourself: run node bot.js, then open the JavaScript version in a browser with the same game ID.
Next¶
- Play with a friend by code instead of a queue: matchmaking and private room codes.
- Everything room code can do: room code reference.
- What happens when wifi drops: connection drops and rejoining.
- The same game in another engine: JavaScript, Unity C#, Unreal C++, Unreal Blueprints, REST API.