RoomDefinition: onCreate() hook

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The 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.tick is 0.
  • room.data is already what the definition’s data returned, or {}.
  • room.from is set when a handoff created the room, and a lobby’s bots are already in room.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 roomsirt dev@irtio/testingSelf-hosted room host
onCreate()0.10.10.10.1