🔖 | API Reference

API Reference

insertCoin({ InitOptions }, [onLaunchCallback], [onDisconnectCallback])

Tell Playroom to start! Playroom Kit will then handle room creation, players joining and also let players pick their names, colors and avatars. Once host taps "Launch", the promise resolves (and onLaunchCallback is called if provided). At this point you can start your game.

// Show Playroom UI, let it handle players joining etc and wait for host to tap "Launch"
await insertCoin();
 
// Start your game!

InitOptions is an object with the following properties:

optiontypedefaultexplanation
gameIdstringundefinedThe ID of the game from the Playroom developer portal.
streamModebooleanfalseIf true , Playroom will start in stream mode .
liveModestringfalseIf set to tiktok , Playroom will start in TikTok Live mode.
allowGamepadsbooleanfalseIf true , Playroom will let players play game using gamepads connected to the stream device itself. This requires streamMode to also be true.

The gamepads need to be connected to device where stream screen is running. No phones are required in this mode but are optionally allowed as an alternative controller if there aren't enough physical gamepads in the room. Players who join via phone in this mode see an on-screen Joystick.
baseUrlstringCurrent Page URLThe base URL used for generating room link that host shares with other players.
avatarsArray<string>Default AvatarsAn array of URLs to images that players can pick as their avatar. This will override the default avatars system that Playroom provides.
enableBotsbooleanfalseIf 'true' , Playroom initializes a bot using the provided botOptions.
botOptionsBotOptionsundefinedAn object containing parameters for bot instantiation and configuration.
roomCodestringundefinedOverride the room to join. If this is not set, a random room code is assigned. Do note that if the URL has room #r= param, that is used instead of this.
skipLobbybooleanfalseSkips the Playroom's lobby screen altogether. This is useful if you want to design your own multiplayer lobby.
reconnectGracePeriodnumber0If set, Playroom will wait for the given number of milliseconds for the player to reconnect to the room after a disconnect.

If the player reconnects within the grace period, the player's state is restored. If the player does not reconnect within the grace period, the player is removed from the room and onQuit fires for the player.
maxPlayersPerRoomnumberundefinedIf set, Playroom will set a maximum limit for the number of players per room.

If the room is full and a new player attempts to join, the Playroom will display a default modal with a message stating that the "room is full", and the insertCoin method will throw an error with a message code ROOM_LIMIT_EXCEEDED.

If the room is full, skipLobby is set to true, and a new player is attempting to join the room, Playroom will skip the default modal but will throw an error.
defaultStatesObjectundefinedAn object containing default game states. These states are set when the room is created.
defaultPlayerStatesObjectundefinedAn object containing default player states. These states are set for all players when they join the room.
matchmakingMatchmakingOptions or booleanfalseAn object containing matchmaking options or just true to enable with default options.
discordbooleanfalseEnable Discord mode. See Discord Mode for more information.

maxPlayersPerRoom: number

Sets a maximum limit for the number of players per room.

  try {
    await insertCoin({
      maxPlayersPerRoom: 2, // maximum limit for 2 players per room
    });
  } catch (error) {}

When skipLobby is set to true, Playroom will skip both the default lobby and the "room is full" modal.

  try {
    await insertCoin({
      skipLobby: true,
      maxPlayersPerRoom: 2,
    });
  } catch (error) {
    if (error.message === "ROOM_LIMIT_EXCEEDED") {
      // Here you can display a custom error
    }
  }

getState(key: string): any

Returns the current value of the given key in the game state.

const winnerId = getState('winner');

setState(key: string, value: any, reliable: boolean = true): void

Sets the value of the given key in the game state. If reliable is true, the state is synced reliably to all players via Websockets. This is useful for game state that is critical to the game, like the winner.

If reliable is false, the state is synced via WebRTC, which is faster but less reliable. This is useful for game state that is not critical to the game, like the player's current position (you can always rely on next position update).

setState('winner', 'player1');

resetStates(keysToExclude?: string[]): Promise<void>

Resets all game states to their default values. If keysToExclude is provided, those keys are not reset.

await resetStates();
// or
await resetStates(['winner']);

resetPlayersStates(keysToExclude?: string[]): Promise<void>

Resets all players' states to their default values. If keysToExclude is provided, those keys are not reset.

await resetPlayersStates();
// or
await resetPlayersStates(['score']);

onPlayerJoin(callback)

Register a callback that will be called when a new player joins the room. The callback will be called with the player's PlayerState object.

When you register this callback, it will first run with all existing players and then listen for new players joining the game. This is useful for "catching up" a new player with existing players or getting the full list in a new game scene.

onPlayerJoin((player) => {
  console.log(`${player.id} joined!`);
});

isHost()

Returns true if the current player is the host.

if (isHost()) {
  // Do something only the host should do, like reading player input and setting game state
}

isStreamScreen()

Returns true if the current screen is the stream screen; a non-player screen that is shown when the game is in stream mode .

if (isStreamScreen()) {
  // Do something only the stream screen should do, like showing a countdown
}

getRoomCode()

Returns a 4-letter room code of the current room.

startMatchmaking(): Promise<void>

If you didn't pass matchmaking option in insertCoin, you can start matchmaking manually using this method.

// Insert coin the regular way
await insertCoin({skipLobby: true});
...
// Start matchmaking after all players are in the room
await startMatchmaking();
// Players have joined a public room

onDisconnect(callback)

Register a callback that will be called when the current player disconnects from the room. The callback will also be called when current player is kicked from the room.

onDisconnect((e) => {
  console.log(`Disconnected!`, e.code, e.reason);
});

addBot()

Adds a bot to the room. This is equivalent to pressing the "Add Bot" button in the lobby. Returns a promise that resolves to an instance of the class you provided in botOptions.botClass parameter in insertCoin.

const newBot = await addBot();

myPlayer() or me()

Returns the current player's PlayerState object.

const player = myPlayer();
console.log(`Hello ${player.getProfile().name}!`);

waitForState(stateKey: string, [onStateSetCallback]): Promise<any>

Returns a promise that resolves to the state value only when the game state has the given key set, to any truthy value.

In other words, it waits until a game state is set. This is useful for waiting for the host to set the winner, for example.

Optionally, you can pass a callback that will be called when the state is set.

// Wait for the winner to be set
const winnerId = await waitForState('winner');
// Do something with the winner

waitForPlayerState(player: PlayerState, stateKey: string, [onStateSetCallback]): Promise<any>

Returns a promise that resolves to the state value only when the player state has the given key set, to any truthy value.

In other words, it waits until a player state is set. This is useful for waiting for a player to play their turn, for example.

Optionally, you can pass a callback that will be called when the state is set.

// Wait for the the player to play their turn
const chosenThing = await waitForState(playerState, 'playedTurn');
// Do something with the thing

RPC.register(name: string, callback: (data: any, sender: PlayerState) => Promise<any>)

Register a callback that will be called when a remote procedure call (RPC) with the given name is received from a player. The callback will be called with the data sent by the other player and the PlayerState object of the caller.

RPC.register('playTurn', (data, sender) => {
  console.log(`${sender.id} played their turn!`);
  return 'ok';
});

RPC.call(name: string, data: any, mode?: RPC.MODE, callbackOnResponse?: (data: any) => void): Promise<any>

Call a remote procedure call (RPC) with the given name and data. The mode parameter can be used to specify the mode of the RPC call. The default mode is RPC.Mode.ALL.

RPCs can be triggered in three different modes:

  • RPC.Mode.HOST: The RPC is triggered on the host only.
  • RPC.Mode.ALL: The RPC is triggered on all clients (including the host and the caller).
  • RPC.Mode.OTHERS: The RPC is triggered on all clients except the caller.

The call returns a promise that resolves to the response from the RPC. Optionally, you can instead pass a callback that will be called when the response is received.

 
// Trigger an RPC on the host only
RPC.call('playTurn', { thing: 'rock' }, RPC.Mode.HOST);
 
// Trigger an RPC on all clients (including the host and the caller)
RPC.call('playTurn', { thing: 'rock' }, RPC.Mode.ALL);
 
// Trigger an RPC on all clients except the caller
RPC.call('playTurn', { thing: 'rock' }, RPC.Mode.OTHERS);

PlayerState

A PlayerState object represents a player in the room. It has the following methods and properties:

id: string

The player's unique ID.

console.log(`Player ID: ${player.id}`);

getProfile(): PlayerProfile

Returns the player's profile, which has the following properties:

propertytypeexplanation
namestringThe player's name.
colorColorThe player's color.
photostringThe player's avatar. This is a dataURL to an image.
avatarIndexnumberThe index of the player's picked avatar. This is an index into the avatars array passed to insertCoin. If no avatars array was passed, this is -1.

The Color type is an object with the following properties:

propertytypeexplanation
rnumberThe red component of the color, between 0 and 255.
gnumberThe green component of the color, between 0 and 255.
bnumberThe blue component of the color, between 0 and 255.
hexStringstringThe color as a hex string, e.g. #ff0000 for red.
hexnumberThe color as a hex number, e.g. 0xff0000 for red.

getState(key: string): any

Returns the value of the given key in the player's state.

const score = player.getState('score');

setState(key: string, value: any, reliable: boolean = false)

Sets the value of the given key in the player's state.

If reliable is true, the state is synced reliably to all players via Websockets. This is useful for game state that is critical to the game, like the winner. If reliable is false, the state is synced via WebRTC, which is faster but less reliable. This is useful for game state that is not critical to the game, like the player's current position (you can always rely on next position update).

player.setState('score', 10);

onQuit(callback): unsubscribeCallback

Register a callback that will be called when the player quits the room. The callback will be called with the player's PlayerState object. Returns a function that can be called to unsubscribe the callback.

const unsubscribe = player.onQuit((state) => {
  console.log(`${state.id} quit!`);
});
 
// ...
unsubscribe();

kick(): Promise<void>

Kicks the player from the room. This is equivalent to pressing the "Kick" button in the lobby.

Only the host can kick players.

await player.kick();

isBot(): boolean

Returns true if the player is a bot.

Joystick Controller

Joystick(state: PlayerState, options: JoystickOptions)

A component that renders a joystick controller. The joystick can be used to control the player's position in the game.

import { Joystick, myPlayer } from 'playroomkit';
 
new Joystick(myPlayer(), {
  type: "dpad"
})

JoystickOptions is an object with the following properties:

optiontypedefaultexplanation
typestringangularThe type of output joystick generates. Can be dpad or angular.
buttonsArray<ButtonOptions>[]An array of buttons to render on the joystick. See below for ButtonOptions.
zonesZoneOptionsnullAn object to define custom zones on the 4 sides of the joystick. See below for ZoneOptions.

ButtonOptions is an object with the following properties:

optiontypedefaultexplanation
idstringnullThe ID of the button. This is used to identify the button in the isPressed method.
labelstring""The button can have a text label.
iconstringnullThe button can have an icon. This is a URL to an image.

ZoneOptions let's you define zones on Joystick that are triggered when player drags Joystick in that zone. This behaves same as buttons above, isPressed method can be used to detect if a zone button is active or not. ZoneOptions is an object with the following properties:

optiontypedefaultexplanation
upButtonOptionsnullThe zone on the top side of the joystick.
downButtonOptionsnullThe zone on the bottom side of the joystick.
leftButtonOptionsnullThe zone on the left side of the joystick.
rightButtonOptionsnullThe zone on the right side of the joystick.

isPressed(id: string): boolean

Returns true if the button with the given ID is pressed.

if (joystick.isPressed('jump')) {
  // Jump!
}

isJoystickPressed(): boolean

Returns true if the joystick is pressed.

if (joystick.isJoystickPressed()) {
  // Do something?
}

angle(): float

Returns the angle of the joystick, in radians.

const angle = joystick.angle();

dpad(): { x: string, y: string }

Returns the direction of the joystick, as a string. The string can be one of the following:

  • up
  • down
  • left
  • right

destroy(): void

Destroy and remove the Joystick and its UI.

MatchmakingOptions

The MatchmakingOptions object is used to specify configurations for matchmaking in the game. It consists of the following properties:

PropertyTypeDefaultDescription
waitBeforeCreatingNewRoomnumber5000The time in milliseconds to wait for an existing room before creating a new room.

BotOptions

The BotOptions object is used to specify configurations for bots in the game. It consists of the following properties:

PropertyTypeDescription
botClassa class that extends BotThe class or constructor function used to instantiate a new bot. Should conform to the Bot interface.
botParamsObject (optional)An object of parameters passed to the botClass constructor when creating a new bot instance. Useful for customizing and configuring individual bot behaviors.

Bot

The Bot interface represents an automated player. The Bot and its derived classes will have methods and properties similar to a PlayerState object.

Note: The behavior of a bot, particularly its decision-making and interactions, will heavily depend on its implementation and the given botClass. Ensure the bot's behaviors align with the game's requirements and player expectations.

onTikTokLiveEvent: (event: TiktokLiveEvent) => unsubscribeCallback

Register a callback that will be called when a live event is received from TikTok. Returns a function that can be called to unsubscribe the callback.

const unsubscribe = onTikTokLiveEvent((event) => {
  console.log(`Received live event: ${event.type}`);
});

TiktokLiveEvent

The TiktokLiveEvent interface represents a live event that is sent from Tiktok to the game. It has the following properties:

FieldTypeDescription
type"chat"
"gift"
"like"
Type of the live event (chat, gift, or like)
dataObjectThe data associated with the event
data.tnumberTimestamp of the event
data.msgIdstringMessage ID
data.userIdstringUser ID
data.namestringUser name
data.userPhotoUrlstringURL of the user's photo
data.commentstringComment text, available only when type is chat
data.giftNamestringName of the gift, available only when type is gift
data.giftPhotoUrlstringURL of the gift's photo, available only when type is gift
data.giftIdstringGift ID, available only when type is gift
data.giftDiamondCountnumberDiamond count of the gift, available only when type is gift

openDiscordInviteDialog(): Promise<void>

Opens a dialog to invite players to the current Discord activity. Not available outside of Discord.

getDiscordClient(): DiscordClient

Returns a Discord client that is already authenticated and ready to use. See Embedded SDK Docs (opens in a new tab) for available methods and commands. Not available outside of Discord.

getDiscordAccessToken(): string

Returns the access token of the current Discord user. Not available outside of Discord.

Hooks for React

See the React API here.

Unity (C#) API

See the Unity API here.