RoomDefinition: onCreate() hook
@irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room hostThe onCreate() hook of a room definition runs once, when the room starts with no room state. It’s where a room sets up what it starts with: a board, a map’s entities, a round timer.
Syntax
defineRoom({
onCreate(room) {},
});
Parameters
room- The new
Room.
Return value
None, or a Promise. The room starts once onCreate has run, or once the promise it returned resolves, and only then do waiting connections join.
Exceptions
If onCreate throws, or its promise rejects, the room stops and its connections close with close code 4007.
Description
A room has no room state the first time it starts, so onCreate runs instead of onWake(). It never runs again for that room: every later start, after a hibernation or a room host restart, runs onWake.
When onCreate runs:
room.tickis 0.room.datais already what the definition’sdatareturned, or{}.room.fromis set when a handoff created the room, and a lobby’s bots are already inroom.bots.
What onCreate writes to entities, room.state and the alarm is room state, so it survives hibernation. What it puts in room.data doesn’t: build that again in onWake.
Examples
Dealing a board
// mines.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";
const Board = entity("board", { width: "u8", height: "u8", mines: "u16" });
const Mine = entity("mine", { x: "u8", y: "u8" }, { hidden: true });
export default defineRoom({
schema: defineSchema({ state: Board, entities: [Mine] }),
onCreate(room) {
Object.assign(room.state, { width: 16, height: 16, mines: 40 });
for (let i = 0; i < 40; i++) {
room.entities.create(Mine, { x: Math.floor(Math.random() * 16), y: Math.floor(Math.random() * 16) });
}
},
});
See also
Runtime availability
| Hosted rooms | irt dev | @irtio/testing | Self-hosted room host | |
|---|---|---|---|---|
onCreate() | 0.1 | 0.1 | 0.1 | 0.1 |