Room Code Reference¶
Room code is one JavaScript file. It has a default export with a config and some functions. The multiplayer server calls those functions when things happen in a room. Each one is given room, which is how you read the players, send messages and save data.
Only start, update and gameEnd are needed. The rest are optional.
Each room runs on a Colyseus 0.16 room on the multiplayer server, but room code does not use the Colyseus API: you write the plain object below, and GameFuse turns Colyseus's events into these function calls. room.state is yours and is not synced to clients by itself (there is no @colyseus/schema); send players what they need with room.send and room.broadcast.
The whole shape¶
export default {
config: {
minPlayers: 2,
maxPlayers: 2,
tickRate: 60,
reconnectSeconds: 15,
},
start(room) {},
update(room, dt) {},
gameEnd(room, result) {},
playerJoined(room, player, { midGame }) {},
playerDropped(room, player) {},
playerReturned(room, player) {},
playerLeft(room, player, how) {},
message(room, player, type, data) {},
};
config¶
| Setting | Meaning |
|---|---|
minPlayers |
start is called when this many players are in the room. |
maxPlayers |
1 to 32. The room locks when it is full. |
tickRate |
How many times a second update is called, 1 to 60. Use 0 for no loop. |
reconnectSeconds |
How long a dropped player's seat is held for them. |
joinAfterStart |
true or false (the default). Whether players can join a game that has already started. With false, the room locks the moment start runs, and anyone else in the queue goes to another room. With true, players can join until the room is full; see playerJoined. |
matchmaking and findRoom (optional)¶
Next to config, the default export can have matchmaking: { waitSeconds, everySeconds, attributes } and a findRoom(player, lobby) function. They decide which room a player who calls joinQueue goes into, and how long they wait before "No one is online right now. Try again later." (3 minutes by default). Both are optional. See Custom Matchmaking.
Functions the multiplayer server calls¶
start(room)¶
The game begins. Called once, when minPlayers players are in.
start(room) {
room.state.scores = {};
for (const player of room.players) room.state.scores[player.id] = 0;
room.broadcast('start', { players: room.players.map((p) => p.name) });
},
update(room, dt)¶
Called every tick. dt is the time since the last tick, in seconds. Not called when tickRate is 0.
update(room, dt) {
room.state.ball.x += room.state.ball.vx * dt;
room.broadcast('ball', room.state.ball);
},
gameEnd(room, result)¶
Called after you call room.end(result). It is your last chance to save anything.
playerJoined(room, player, { midGame })¶
Optional. A player came into the room.
midGame is false for everyone who joined before start. It is true for a player who joined a game already under way, which only happens when config.joinAfterStart is true. The same thing stays on the player as player.joinedMidGame.
playerJoined(room, player, { midGame }) {
room.broadcast('joined', { name: player.name, seat: player.seat });
},
Players who join mid-game¶
A player who arrives after start missed everything so far, and start will not run again for them. Do for them what start did for everyone else, and send them what they need to draw the game:
config: { minPlayers: 2, maxPlayers: 8, tickRate: 20, joinAfterStart: true },
start(room) {
room.state.scores = {};
for (const p of room.players) room.state.scores[p.id] = 0;
room.state.endsAt = room.time + 180;
},
playerJoined(room, player, { midGame }) {
if (!midGame) return; // start() handles everyone who was there at the beginning
room.state.scores[player.id] = 0; // give them what start() gave the others
room.send(player, 'catchUp', { // and everything they missed
scores: room.state.scores,
secondsLeft: room.state.endsAt - room.time,
});
room.broadcast('joined', { name: player.name }, { except: player });
},
Things to decide for a late player:
- Do they belong? To close the room after a point (for example the last minute of a match), call
room.lock()inupdate. - Their score. GameFuse adds a game round for them to the match's round, so
room.round.gameRoundIds[player.id]works for them ingameEndlike for anyone else. - Fairness. Teams, handicaps or a spectator period are up to you;
player.joinedMidGamelets you tell them apart later.
playerDropped(room, player)¶
Optional. That player's connection was lost. Their seat is held for reconnectSeconds.
playerDropped(room, player) {
room.state.paused = true;
room.broadcast('paused', { waitingFor: player.name });
},
playerReturned(room, player)¶
Optional. A dropped player is back.
playerReturned(room, player) {
room.state.paused = false;
room.send(player, 'catchUp', room.state.scores);
room.broadcast('resumed', {});
},
playerLeft(room, player, how)¶
Optional. The player is gone for good. how is 'quit' when they left on purpose, or 'timeout' when they dropped and did not come back in time.
playerLeft(room, player, how) {
room.log(player.name, 'left:', how);
room.broadcast('left', { name: player.name, how });
},
message(room, player, type, data)¶
Optional. That player's browser sent something with room.send(type, data).
message(room, player, type, data) {
if (type === 'move') {
room.state.positions[player.id] = { x: data.x, y: data.y };
}
},
Treat data as untrusted. It comes from a player's browser. Check it before you use it.
room¶
room.id and room.code¶
room.id is the room's id. room.code is its 6-character code, the one friends type to join a private room. Queue rooms have a code too.
room.players¶
A list of the players: [{ id, name, seat, connected, options }].
| Field | Meaning |
|---|---|
id |
The player's GameFuse user id. |
name |
Their username. |
seat |
0, 1, 2 and so on, in the order they joined. |
connected |
false while they are dropped and their seat is held. |
options |
What their browser passed when joining. |
const host = room.players.find((p) => p.seat === 0);
const online = room.players.filter((p) => p.connected);
room.state¶
A plain object that is yours. Keep the state of the game here. The multiplayer server does not send it anywhere. To tell players something, use room.send or room.broadcast.
room.time¶
Seconds since start.
room.random()¶
A random number from 0 to 1.
room.send(player, type, data)¶
Send a message to one player. Their browser gets it in room.on('message', (type, data) => {}).
room.broadcast(type, data)¶
Send a message to every player. Pass { except: player } to leave one player out.
room.broadcast('scores', room.state.scores);
room.broadcast('moved', { id: player.id, x: data.x, y: data.y }, { except: player });
room.after(seconds, fn)¶
Run a function once, later. Use this instead of setTimeout.
room.broadcast('countdown', { seconds: 3 });
room.after(3, () => {
room.state.playing = true;
room.broadcast('go', {});
});
room.log(...things)¶
Write a line to the log. It shows in the dashboard and in gamefuse multiplayer logs.
room.lock()¶
Nobody else may join this room.
room.kick(player, reason)¶
Remove a player from the room. Their browser gets closed with 'kicked'.
room.end(result)¶
End the game. This calls gameEnd(room, result), tells every browser closed with 'ended', and closes the room. result is whatever you want to hand to gameEnd.
room.broadcast('final', room.state.scores);
room.end({ winnerId: winner.id, scores: room.state.scores });
room.round¶
The GameFuse game round for this game: { multiplayerGameRoundId, gameRoundIds: { [playerId]: id } }. It is made for you when the game starts. Its game type is the queue name, or 'private' for a private room. See saving GameFuse data.
room.gamefuse¶
Your game's GameFuse data: users, scores, credits, attributes, leaderboards, rounds, variables and the store. Every call returns a promise. All of them are listed in saving GameFuse data from room code.
const user = await room.gamefuse.users.get(player.id);
await room.gamefuse.users.addCredits(player.id, 50);
What is not available¶
Room code runs with only what is on this page, plus the JavaScript language itself. These are not available. Calling one throws an error that says what to use instead.
| Not available | Use instead |
|---|---|
setTimeout, setInterval |
room.after(seconds, fn) for something once, later. update(room, dt) for something every tick. |
fetch |
room.gamefuse for your game's GameFuse data. |
require, import() while running |
import at the top of your file. The gamefuse command bundles everything into one file before uploading. |
process |
Nothing. Put settings in your room code, or in your game's GameFuse variables and read them with room.gamefuse.variables.get(). |
| Files | room.state while the room is open. room.gamefuse for anything that must last. |
// Not this:
setTimeout(() => room.broadcast('go', {}), 3000);
// This:
room.after(3, () => room.broadcast('go', {}));
Limits¶
A tick must take under 8 ms on average. A room may use 128 MB and last 60 minutes. See limits for all of them and what happens when one is passed.