Multiplayer server: runs on GameFuse
// Pong on GameFuse Multiplayer. Runs on GameFuse's servers, one copy per match.
// Two players online. If nobody joins in 20 seconds, you play a bot.
const W = 800, H = 500, PADDLE = 90, SERVE_SPEED = 300, WIN = 5;
export default {
config: { minPlayers: 1, maxPlayers: 2, tickRate: 30, reconnectSeconds: 10, joinAfterStart: true },
start(room) { // the first player is in
const s = room.state;
s.sides = { [room.players[0].id]: 'left' };
s.paddles = { left: H / 2, right: H / 2 };
s.score = { left: 0, right: 0 };
s.cancelBot = room.after(20, () => play(room, 'bot'));
room.broadcast('waiting', { seconds: 20 });
room.gamefuse.leaderboard.get('wins', 5).then((top) => room.broadcast('leaders', top.entries), () => {}); // top 5
},
playerJoined(room, player, { midGame }) { // a second player came in time
if (!midGame || room.state.playing) return;
room.state.cancelBot();
room.state.sides[player.id] = 'right';
play(room, 'player');
},
message(room, player, type, data) { // a player moved their paddle
const side = room.state.sides[player.id];
if (type === 'paddle' && side) room.state.paddles[side] = clamp(Number(data.y) || 0, PADDLE / 2, H - PADDLE / 2);
},
update(room, dt) {
const s = room.state, b = s.ball;
if (!s.playing) return;
if (s.bot) s.paddles.right += clamp(b.y - s.paddles.right, -220 * dt, 220 * dt); // the bot follows the ball, slowly
b.x += b.vx * dt;
b.y += b.vy * dt;
if (b.y < 0 || b.y > H) b.vy = -b.vy;
bounce(b, 30, s.paddles.left, -1);
bounce(b, W - 30, s.paddles.right, 1);
if (b.x < 0) point(room, 'right');
if (b.x > W) point(room, 'left');
room.broadcast('state', { ball: { x: Math.round(b.x), y: Math.round(b.y) }, paddles: s.paddles, score: s.score });
},
playerLeft(room, player) { // someone quit: the other side wins
if (!room.state.playing) return room.end({});
finish(room, room.state.sides[player.id] === 'left' ? 'right' : 'left');
},
async gameEnd(room, result) { // the winner's wins go on the leaderboard
if (!result.winnerId) return;
const { score } = await room.gamefuse.users.addScore(result.winnerId, 1);
await room.gamefuse.leaderboard.add(result.winnerId, 'wins', score);
},
};
function play(room, opponent) {
room.lock();
room.state.playing = true;
room.state.bot = opponent === 'bot';
serve(room, 1);
for (const p of room.players) {
const other = room.players.find((q) => q !== p);
room.send(p, 'start', { side: room.state.sides[p.id], opponent: other ? other.name : 'a bot' });
}
}
function serve(room, direction) {
room.state.ball = { x: W / 2, y: H / 2, vx: SERVE_SPEED * direction, vy: SERVE_SPEED * (room.random() - 0.5) };
}
function bounce(ball, x, paddleY, side) { // side: -1 left paddle, 1 right paddle
const coming = Math.sign(ball.vx) === side;
if (coming && Math.abs(ball.x - x) < 12 && Math.abs(ball.y - paddleY) < PADDLE / 2 + 6) {
ball.vx *= -1.05;
ball.vy += (ball.y - paddleY) * 5;
}
}
function point(room, side) {
room.state.score[side] += 1;
if (room.state.score[side] >= WIN) return finish(room, side);
serve(room, side === 'left' ? 1 : -1);
}
function finish(room, side) {
room.state.playing = false;
const winner = room.players.find((p) => room.state.sides[p.id] === side);
room.broadcast('winner', { side, name: winner ? winner.name : 'The bot' });
room.end({ winnerId: winner && winner.id });
}
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
The game, in the browser
// Pong in the browser. The room on GameFuse runs the ball and the score;
// this file sends your paddle and draws what the room sends back.
const GAME_ID = 9361; // from your GameFuse dashboard
const GAME_TOKEN = 'a6eb4ecd-60b0-41cb-a4f5-2392cef9c273';
const canvas = document.getElementById('court');
const draw = canvas.getContext('2d');
const status = (text) => { document.getElementById('status').textContent = text; };
let side = null, state = null, myY = 250, countdown = 0;
// Arcade login: type a name, press Play. The name becomes a GameFuse player with a random password;
// the browser keeps its login token, so the same name comes back next time.
const form = document.getElementById('login');
const nameBox = document.getElementById('name');
const saved = JSON.parse(localStorage.getItem('pong.player') || 'null');
if (saved) nameBox.value = saved.name;
form.addEventListener('submit', async (e) => {
e.preventDefault();
const name = nameBox.value.trim();
form.hidden = true;
try {
await play(await login(name));
} catch (err) {
localStorage.removeItem('pong.player'); // a saved login that stopped working is forgotten
form.hidden = false;
status(err.message);
}
});
async function login(name) {
if (saved && saved.name === name) return saved.token;
status('Saving your name...');
await call(GameFuse.setUpGame, GAME_ID, GAME_TOKEN);
const password = crypto.randomUUID();
await call(GameFuse.signUp, crypto.randomUUID() + '@arcade.gamefuse.co', password, password, name)
.catch(() => { throw new Error('That name is taken or not allowed. Try another.'); });
const token = GameFuseUser.CurrentUser.getAuthenticationToken();
localStorage.setItem('pong.player', JSON.stringify({ name, token }));
return token;
}
// GameFuse SDK calls end with a callback(message, hasError): make them promises.
function call(fn, ...args) {
return new Promise((ok, fail) => fn.call(GameFuse, ...args, (msg, err) => (err ? fail(new Error(msg)) : ok())));
}
async function play(token) {
const mp = new GameFuseMultiplayer({ gameId: GAME_ID, gameToken: GAME_TOKEN });
mp.useToken(token);
status('Connecting...');
const room = await mp.joinQueue('pong', { clientVersion: '1' });
room.on('message', (type, data) => {
if (type === 'waiting') countdown = data.seconds;
if (type === 'start') { side = data.side; countdown = 0; status('You vs ' + data.opponent + '. First to 5.'); }
if (type === 'state') state = data;
if (type === 'winner') status(data.side === side ? 'You win!' : data.name + ' wins.');
if (type === 'leaders') showLeaders(data);
});
room.on('closed', () => document.getElementById('leaders').insertAdjacentHTML('beforebegin', '<button onclick="location.reload()">Play again</button>'));
setInterval(() => side && room.send('paddle', { y: Math.round(myY) }), 50); // 20 times a second
setInterval(() => countdown > 0 && status('Looking for a player... a bot joins in ' + countdown-- + 's'), 1000);
}
// Top 5 by wins, one line each (a player can be on the board more than once: keep their best).
function showLeaders(entries) {
const best = new Map();
for (const e of entries) if (!best.has(e.username)) best.set(e.username, e.score);
document.getElementById('leaders').textContent =
'Top players: ' + ([...best].map(([name, wins]) => name + ' ' + wins).join(' ยท ') || 'nobody yet');
}
// Mouse or finger: your paddle follows it.
canvas.addEventListener('pointermove', (e) => {
const box = canvas.getBoundingClientRect();
myY = (e.clientY - box.top) * (500 / box.height);
});
function frame() {
draw.fillStyle = '#000';
draw.fillRect(0, 0, 800, 500);
if (state) {
const left = side === 'left' ? myY : state.paddles.left; // your own paddle moves at once
const right = side === 'right' ? myY : state.paddles.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.fillText(state.score.left, 340, 50);
draw.fillText(state.score.right, 440, 50);
}
requestAnimationFrame(frame);
}
frame();
The page the game runs in
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GameFuse Pong</title>
<link rel="icon" href="favicon.png">
<style>
/* Fits any window or frame: the court shrinks so the text above and below always shows. */
body { margin: 0; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center;
background: #0b1024; color: #eef0ff; font: 15px sans-serif; text-align: center; overflow: hidden; }
p { margin: 6px 8px; }
canvas { background: #000; width: auto; height: auto; max-width: 100%; max-height: calc(100vh - 150px); touch-action: none; }
button { margin: 6px; padding: 6px 18px; font: inherit; }
input { padding: 6px 10px; font: inherit; width: 10em; }
#leaders { color: #a3abcb; font-size: 13px; min-height: 1em; margin-bottom: 34px; } /* room for the hosting badge */
</style>
</head>
<body>
<p id="status">Type your name to play.</p>
<form id="login"><input id="name" maxlength="16" placeholder="Your name" required autofocus> <button>Play</button></form>
<canvas id="court" width="800" height="500"></canvas>
<p id="leaders"></p>
<script src="https://cdn.jsdelivr.net/gh/GameFuseCo/game-fuse-js@de18168ac13a0c0d699cb1cba5f30e869d7ecd37/gameFuseFull.js"></script>
<script src="game.js"></script>
</body>
</html>
Puts the server code live
#!/usr/bin/env bash
# Check the room code, then upload it to GameFuse and make it live.
# Needs GAMEFUSE_UPLOAD_KEY and GAMEFUSE_GAME_ID in .env (from the game's Multiplayer tab).
set -e
npx gamefuse multiplayer validate --dir server
npx gamefuse multiplayer deploy --dir server
Builds the game and puts it online
#!/usr/bin/env bash
# Build the game into dist/, then put it online with GameFuse Hosting.
# Uses the same .env as UPLOAD_MULTIPLAYER_CODE.sh.
set -e
rm -rf dist && mkdir dist
cp game/index.html game/favicon.png dist/
npx esbuild game/game.js --minify --outfile=dist/game.js
npx gamefuse hosting deploy dist