Skip to main content

Shared characters

A shared character lives in a persistent multiplayer world. Everyone in that world talks to the same character, and it remembers what happens there across all of its players. Each player still has their own conversation with it: a player sees their own exchanges, not other players' private ones.

Shared characters use the same characterBundle as playthrough characters (see Define characters), but players reach them through the multiplayer connection instead of the Characters module. There are no playthroughs and no resets in a shared world.

Declaring a shared world​

A shared world is a destination: a named route under server.destinations in castle.json, with characters: "shared":

{
"server": {
"main": "server/index.js",
"destinations": [
{
"routeId": "village",
"access": "public",
"selection": "exact",
"persistence": "world",
"characters": "shared",
"maxPlayers": 16
}
]
},
"characterBundle": {
"version": "square-1",
"characters": [
{ "id": "mara", "version": "1", "name": "Mara", "instructions": "You are Mara, who keeps the market stall. Speak warmly and briefly." },
{ "id": "tomas", "version": "1", "name": "Tomas", "instructions": "You are Tomas, the watchman. Careful and dry." }
],
"eventTypes": [],
"beats": [],
"conversation": { "version": 1, "authority": "server", "maxListeners": 1 }
}
}
  • routeId: the route's name, 1 to 64 letters, digits, _ or -.
  • access: who can join. "public" is anyone, "party" is the player's party, and "player" is the player alone.
  • selection must be "exact" and persistence must be "world": players join one particular world, and it keeps its state between sessions.
  • maxPlayers: players in the world's session at once, 1 to 24.

A deck can declare up to 16 destinations.

The bundle needs the conversation block shown above, or every turn is refused. authority must be "server": the deck's server checks every request (see The server decides). maxListeners, 0 to 3, is how many other characters can overhear a turn.

One kind per deck​

The conversation block applies to every character in the bundle, and a deck has only one bundle. So a deck's characters are either all playthrough characters or all shared ones:

  • Without a conversation block, they're playthrough characters. Players talk to them with Characters.send, and a shared world refuses every turn.
  • With the block, they're shared characters. Players talk to them in a shared world, and Characters.send is refused for every one of them with CAULDRON_CHARACTER_INVALID_ARGUMENT and a message about the conversation block.

You can't have a playthrough shopkeeper and a shared villager in the same deck. Make them both shared, so everyone meets them in the world, keep them both playthrough characters, or put the shared world in a second deck.

A minimal shared world​

A shared world needs three things, and a turn fails if any of them is missing:

  1. castle.json: the destination and the characterBundle with its conversation block, as above.
  2. A server at server.main with onWorldCharacterTurn, plus onWorldCharacterRead if the client calls readCharacters and onWorldCharacterCommand if it records events. Castle sends each of those requests to the server first, and one with no callback for it fails with CAULDRON_CHARACTER_TIMEOUT.
  3. A client that joins the destination and sends turns over that connection.

This server/index.js lets turns to the two characters through, lets reads through, and rejects commands:

const CHARACTERS = new Set(["mara", "tomas"]);

export default {
async onWorldCharacterTurn(session, turn) {
if (!CHARACTERS.has(turn.characterId)) return turn.reject("unknown_character");
await turn.send();
},
async onWorldCharacterRead(session, request) {
await request.read();
},
onWorldCharacterCommand(session, request) {
request.reject("no_commands");
},
};

And this client talks to Mara. In a deck made with castle-web init --kit none, it replaces the startGame function in game.js (add the Multiplayer import). It handles the button and the Enter key itself rather than using a <form>, because a form may not submit inside the player's frame:

import { Multiplayer } from "castle-web-sdk";

async function startGame(card) {
card.innerHTML = `
<div style="height: 100%; display: flex; flex-direction: column; color: #fff">
<div><input id="input" maxlength="2000" placeholder="Say something to Mara"> <button id="send">Send</button></div>
<pre id="log" style="flex: 1; min-height: 0; overflow-y: auto; white-space: pre-wrap"></pre>
</div>`;
const input = card.querySelector("#input");
const log = card.querySelector("#log");
let conn = null;

async function talk(text) {
const operationId = crypto.randomUUID();
await conn.requestCharacterTurn({ requestId: crypto.randomUUID(), operationId, characterId: "mara", input: text });
let turn = await conn.getCharacterTurnStatus(operationId);
while (turn.status === "queued" || turn.status === "running") {
await new Promise((resolve) => setTimeout(resolve, 500));
turn = await conn.getCharacterTurnStatus(operationId);
}
log.append(turn.status === "completed" ? `Mara: ${turn.response}\n` : `(no reply: ${turn.status})\n`);
}

function send() {
const text = input.value.trim();
if (!conn || !text) return;
input.value = "";
log.append(`You: ${text}\n`);
talk(text).catch((error) => log.append(`(${error.code ?? error.message})\n`));
}
card.querySelector("#send").addEventListener("click", send);
input.addEventListener("keydown", (event) => {
event.stopPropagation();
if (event.key === "Enter") send();
});

const joined = await Multiplayer.joinDestination({ routeId: "village", slot: "main" })
.catch((error) => ({ status: error.code ?? "unavailable" }));
if (joined.status === "joined" && joined.connection.sharedCharacters) conn = joined.connection;
else log.append(`The village isn't available right now (${joined.status}).\n`);
}

Publish the deck as unlisted or public before you try it: a private deck has no server. The sections below cover each part in more detail, including retries after a lost connection, which this minimal client leaves out.

Joining​

The client joins a world by route and slot. The slot is any name you choose, up to 128 bytes, and each slot is a separate world with its own characters:

import { Multiplayer } from "castle-web-sdk";

async function joinVillage() {
const joined = await Multiplayer.joinDestination({ routeId: "village", slot: "main" });
if (joined.status !== "joined") return showUnavailable(joined.status);
const conn = joined.connection;
if (!conn.sharedCharacters) return showUnavailable("no_characters");
return conn;
}

A join that doesn't succeed has a status of "full", "unavailable", "not_found", "forbidden", "party_required" or "cancelled". conn.sharedCharacters is true when this connection can reach the world's characters. Check it again after a reconnect.

Talking​

conn.requestCharacterTurn sends what the player said to one character:

const operationId = crypto.randomUUID();
const admission = await conn.requestCharacterTurn({
requestId: crypto.randomUUID(),
operationId,
characterId: "mara",
input: text,
});
  • requestId matches this one request on the socket. operationId identifies the message itself. If the request fails with CAULDRON_CHARACTER_TIMEOUT or the connection closes before you hear back, the message may still have arrived. Ask about the same operationId after reconnecting, and don't send it again with a new one.
  • input is 1 to 2,000 characters.
  • The result is { operationId, status, replayed }. status is "queued", "completed" or "interrupted".

Then poll for the reply:

let turn = await conn.getCharacterTurnStatus(operationId);
while (turn.status === "queued" || turn.status === "running") {
showDraft(turn.progress?.response ?? "");
await new Promise((resolve) => setTimeout(resolve, 500));
turn = await conn.getCharacterTurnStatus(operationId);
}
if (turn.status === "completed") showReply(turn.response);

Each player can have one unfinished turn with a character at a time. A character takes one turn at a time and keeps at most two more waiting. Past that, a turn fails with CAULDRON_SHARED_CHARACTER_BUSY, so ask the player to try again in a moment.

Who else is listening​

By default, a turn is between the speaker and the character. audience adds listeners, so the character knows who else heard:

await conn.requestCharacterTurn({
requestId, operationId, characterId: "mara", input: text,
audience: { playerIds: [otherPlayerId], characterIds: ["tomas"], disclosure: "participants" },
});
  • playerIds: up to seven other players in the session, by their connection playerId. They have to be connected.
  • characterIds: other characters who overhear, up to the bundle's conversation.maxListeners.
  • disclosure: "participants" (the default) keeps what was said among the people and characters in the audience. "world" lets it become something the whole world can know.

Showing the exchange to the other players is up to your deck, for example by sending it to them from the server.

Reading​

conn.readCharacters({ requestId, query }) reads what this player may see:

  • { type: "history", characterId, limit, cursor }: the player's past turns with a character, newest first, as { operations, cursor }. Each operation has operationId, characterId, status and, once there's a reply, response. It doesn't include what the player said. limit is 1 to 50, and cursor is null on the last page.
  • { type: "status", operationId }: one operation, like getCharacterTurnStatus. The difference is that readCharacters passes through your server's onWorldCharacterRead, and getCharacterTurnStatus doesn't.
  • { type: "inspect" }: the player's view of the world's characters, with participantId, the player's lasting identity in this world. Unlike playerId, it doesn't change when the player reconnects.

Recording events​

conn.requestCharacterCommand records one of your bundle's events in the world. Here it's a market_opened event type, which the bundle would declare in eventTypes:

const receipt = await conn.requestCharacterCommand({
requestId: crypto.randomUUID(),
operationId,
command: { type: "record_event", eventTypeId: "market_opened" },
});

The receipt is { operationId, status: "applied", replayed, result, worldRevision }. A request Castle refuses throws instead. Like a turn, it goes through your server first, in onWorldCharacterCommand.

The server decides​

Every turn, command and read (except getCharacterTurnStatus) passes through your deck's server before Castle runs it. The server can check game rules, such as whether the player is standing next to the character, and then either let the request through or reject it:

export default {
async onWorldCharacterTurn(session, turn) {
if (!isNear(turn.speaker, turn.characterId)) return turn.reject("too_far");
await turn.send();
},
async onWorldCharacterCommand(session, request) {
if (!allowed(request.speaker, request.command)) return request.reject("not_allowed");
await request.apply();
},
async onWorldCharacterRead(session, request) {
await request.read();
},
};
  • turn has speaker (the player), characterId, input and audience. The server can't change any of them. It can only send the turn as it is or reject it.
  • A callback that returns without calling send, apply/read or reject rejects the request.
  • Only a callback lets a request through, so write the callback for each kind of request your deck uses.

Changing characters​

Publish the deck again to change a shared world's characters. Players don't need to rejoin or move to another slot: the world switches to the new bundle on its next turn and keeps its id.

  • An edited character keeps what it remembers and its conversations, and answers with its new instructions from then on.
  • A character you add can be talked to once the world has switched. A character you remove stops answering from then on; messages still waiting for it are dropped, and the allowance they reserved comes back.
  • A reply that was already being written when you published finishes on the old version.
  • If you change gameplay, the world's game state starts over from the new definition.

Limits​

  • At most 32 different players can take part in one world, and a deck can have at most 32 shared worlds (one per slot).
  • A character's reply is at most 4,000 characters.
  • Each turn uses the speaking player's daily allowance, the same allowance as playthrough characters (see Costs and limits).