🔖 | API Reference

API Reference

insertCoin({ InitOptions }, [onLaunchCallback])

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
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.

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');

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.

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('playedTurn');
// Do something with the thing

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();

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.

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

Hooks for React

See the React API here.

Unity (C#) API

See the Unity API here.