Run the story from the server
What characters know about your world comes from your deck's multiplayer server. The server records what happens, decides which characters learn about it, and keeps game state that belongs to the playthrough. None of it runs the model or uses the player's allowance, and a player can't fake it from the client.
A server for a single-player deck
The story calls need a running server, even in a deck for one player. Give the deck a server entry in castle.json, such as "server": { "main": "server/index.js", "maxPlayers": 1, "tickRate": 0 }, and have each player join a room of their own:
import { Multiplayer, User } from "castle-web-sdk";
const { userId } = await User.getCurrent();
const conn = await Multiplayer.join({ mode: "named", key: `windmill-v1-${await hash(userId)}` });
if (conn.isSolo) showUnavailable(conn.soloReason);
hash is any function of yours that turns the user id into a short string, such as a SHA-256 hex digest. The room key only picks the room. The server always takes the player's identity from the player it's given, never from the key or a message.
A private deck gets no server, and Multiplayer.join comes back solo. Use an unlisted or public deck.
Opening the playthrough
On the server, session.storage.playthrough(userId) opens one player's playthrough:
export default {
async onMessage(session, player, data) {
const playthrough = await session.storage.playthrough(player.userId);
if (data.generation !== playthrough.generation) return; // from before a reset
// ...
},
};
Always pass player.userId from the callback, never a user id the client sent.
The client must have opened at least one character with Characters.open before the server works with the playthrough, and again after a reset. That first open admits the player to every character in the bundle.
A playthrough handle has:
generation: the same number as the client handle's. Have the client send its generation with each story action, and ignore actions from an earlier one.characters: the story calls below.get(keys),set(values),remove(keys): game state that belongs to this playthrough. It's cleared along with the characters' memory when the player resets, so keep story flags here rather than insession.storage.user.reset(operationId): resets the player's whole playthrough, like the client'sreset, and returns a handle in the new generation.
Like the client's handle, a playthrough handle stays in its generation. After a reset, writes through the old handle are refused.
Operations
Each story call takes an operationId you choose and returns an operation, just like a client send. A story call can come back queued or running, so wait for it to finish before you use its result:
const DONE = new Set(["completed", "failed", "interrupted"]);
async function finished(characters, op) {
const deadline = Date.now() + 30_000;
while (!DONE.has(op.status)) {
if (Date.now() > deadline) throw new Error("Story action is still running.");
await new Promise((resolve) => setTimeout(resolve, 125));
op = await characters.status(op.operationId);
}
// A finished answer can come back without its result, so fetch it.
if (op.status === "completed" && op.result == null) op = await characters.status(op.operationId);
if (op.status !== "completed" || !op.result) throw new Error(`Story action ${op.status}.`);
return op;
}
Make operation ids stable: build them from a request id the client sends with the action, so that a retried action uses the same id and doesn't happen twice. characters.status(operationId) and characters.history({ limit, cursor }) work as they do on the client. History includes the story operations too, so a server that restarts can rebuild what happened from it.
Recording an event
recordEvent says that an event from your bundle has happened in this playthrough. Each event type happens at most once per playthrough.
const event = await finished(playthrough.characters, await playthrough.characters.recordEvent({
operationId: `fire-${data.requestId}`,
eventTypeId: "windmill_fire",
}));
const eventOccurrenceId = event.result.eventOccurrenceId;
Keep eventOccurrenceId. You need it to tell characters about the event and to complete its beats. Recording an event doesn't tell anyone yet.
Telling characters
deliverKnowledge gives a character some of an event's claims:
await finished(playthrough.characters, await playthrough.characters.deliverKnowledge({
operationId: `witness-${data.requestId}`,
recipientCharacterId: "tomas",
eventOccurrenceId,
claimIds: ["windmill_burned"],
source: { type: "creator_event" },
}));
source says how the character learned it:
{ type: "creator_event" }: the character was there. Only a claim's declared witnesses can learn it this way.{ type: "character", characterId: "tomas" }: another character told them. The teller must already know the same claims from the same event. Use it when your game decides the news has spread:
await finished(playthrough.characters, await playthrough.characters.deliverKnowledge({
operationId: `tell-mara-${data.requestId}`,
recipientCharacterId: "mara",
eventOccurrenceId,
claimIds: ["windmill_burned"],
source: { type: "character", characterId: "tomas" },
}));
Characters remember where they heard something, so Mara knows she heard it from Tomas and didn't see it herself. Nothing spreads by itself. Something a character says in conversation doesn't make it true in the world, and it doesn't reach the other characters unless your server passes it on.
Beats
When a character knows a beat's required claims, its next reply can open with the beat's openingText. The client sees it in the completed send as result.selectedBeat: { beatId, eventOccurrenceId }.
A beat that was delivered isn't finished. When your game decides how the moment ended, the client asks the server, and the server checks the outcome is allowed and completes the beat:
await finished(playthrough.characters, await playthrough.characters.completeBeat({
operationId: `complete-${data.requestId}`,
characterId: "mara",
beatId: "mara_asks_about_fire",
eventOccurrenceId: data.eventOccurrenceId,
outcomeId: "safety_answered",
}));
// Only now change game state that depends on the outcome.
outcomeId must be one of the beat's completionOutcomeIds, and the beat must already have been delivered in a reply. A beat completes once: completing it again with the same outcome returns the same result, and a different outcome is refused.
Resetting from the server
await playthrough.reset(operationId) resets the same player's playthrough. If you don't hear back, open the playthrough again: a higher generation means the reset happened. Otherwise call reset again on the old handle with the same operation id. Then send the client its new story state.