playertwo-sdk
v0.2.16
Published
SDK for HTML5 and browser games on PlayerTwo (playertwo.plus): trophies, leaderboards, stats, cloud saves, in-game purchases, donations to the developer, your own events and errors in your analytics, feeds of outside data, calls to outside APIs with a sec
Maintainers
Readme
playertwo-sdk
The game SDK for PlayerTwo, with TypeScript types. Trophies, XP and levels, stats,
leaderboards, cloud saves, presence, invites, add-ons, in-game purchases, donations to you, moments to share, the
player's avatar, travel between games, and multiplayer rooms with no server of your own (voice chat, worlds, replays and your own server code in room.js
included).
PlayerTwo is a game store and a launchpad. Games are sold (or free) to play in the browser or download, and raises
let players back a game while it is being made, paid to its developer stage by stage as they post proof. A web game
hosted on PlayerTwo gets its own address on playertwo.cc and every service below through one account per player.
- Docs: https://playertwo.plus/docs/sdk
- Everything a game gets, with a link to its part of the docs: https://playertwo.plus/llms.txt
- Source of these packages, examples and Markdown docs: https://github.com/TheDudeCommits/playertwo-sdk
Install
npm install playertwo-sdkOr no install at all: the SDK itself is one script.
<script src="https://playertwo.plus/sdk/v1.js"></script>
<script>
PlayerTwo.init().then((p2) => p2.trophies.unlock("first-win")).catch(() => {
/* not on PlayerTwo (e.code "not-on-player-two"): the game plays on without services */
});
</script>On PlayerTwo the script is already in your game's page. init() from the npm package uses that copy, and loads
https://playertwo.plus/sdk/v1.js only when the page doesn't have it (on localhost, say).
Quick start
import { init } from "playertwo-sdk";
const p2 = await init({
// localhost only: the stand-in's trophies (it refuses keys you don't list, as PlayerTwo would)
local: { trophies: [{ key: "first-win", name: "First win", tier: 1 }] },
});
console.log(p2.env, p2.player?.name, p2.player?.level); // env: "p2" | "local" | "disabled"
await p2.trophies.unlock("first-win"); // the player sees the toast
await p2.scores.submit("time-attack", 83400); // a board you made in your studio
await p2.stats.add("duels-won");
await p2.saves.list(); // read before you write over a slot
await p2.saves.put("slot-1", { level: 3 });
const room = await p2.rooms.join({ mode: "arena", size: 16 });
room.on("message:emote", (kind, from) => showEmote(from, kind));
room.send("emote", "wave"); // to everyone else in the room
const sync = room.sync(myMesh, { fields: ["position.x", "position.y", "position.z", "rotation.y"], angles: ["rotation.y"] });
sync.on("join", (id) => sync.bind(id, makeMesh(id))); // everyone else's mesh, moved smoothly
sync.on("leave", (id) => removeMesh(id));
// once a frame, after you move: sync.step();Every call returns a promise. A refusal rejects with an Error that has a code and a status (the codes:
https://playertwo.plus/docs/sdk#call-errors). Off PlayerTwo and off localhost, init() rejects after 1.5 seconds
with code not-on-player-two; with { required: true } the page says "Play this on PlayerTwo" and stops.
What it gives your game
| Feature | Calls | Docs |
| --- | --- | --- |
| Who is playing | p2.player, p2.game, p2.me() | call-me |
| Trophies, XP and levels | p2.trophies.list(), p2.trophies.unlock(key) | call-trophies |
| Leaderboards | p2.scores.submit(board, value), p2.scores.list(board, { around, friends, limit }) | call-scores |
| Stats | p2.stats.get(), .get(key), .set(key, n), .add(key, n?) | call-stats |
| Cloud saves (8 slots, 1 MB each) | p2.saves.list(), .get(slot), .put(slot, data, { version }), .delete(slot) | call-saves |
| Progress from before PlayerTwo (one-time codes) | transfer({ game, local, saves, account }) on your old site, p2.saves.import(code?) in the game | saves-import |
| Add-ons (sold on the game's page) | p2.addons.list(), p2.addons.has(key) | addons |
| In-game purchases | p2.store.list({ coming }), .owned(), .access(), .sold(refs), .buy(key), .pay(chargeId) | purchases |
| Donations to you | p2.donate.available(), .open(), .button({ corner, parent }) | donate |
| Moments to share, on your results screen | p2.moments.offer() | moments |
| Ads PlayerTwo shows over your game: rewarded ones and breaks | p2.ads.available(), .rewarded(), .break(), p2.on("ad", fn) | ads |
| Presence | p2.presence.set(line, { join }) | call-presence |
| Identity and invites | p2.identity(), p2.invite(params), p2.params | call-identity |
| Loading and play events | p2.loading.done(), p2.gameplay.start(), .stop() | call-gameplay |
| Your game's own events, in your studio's analytics | p2.track(name, data) | call-track |
| Its errors, caught by themselves | p2.errors.report(error, where), p2.errors.off() | call-crashes |
| Feeds: outside data PlayerTwo fetches for your game | p2.feeds.get(name) | feeds |
| Calls with a secret: an API PlayerTwo calls for the player, your key never in the build | p2.calls.run(name, data) | secret-calls |
| The overlay, and closing | p2.on("overlay", fn), p2.on("flush", fn) | call-overlay |
| On air in the Plaza | p2.onAir | call-air |
| Test mode and demos | p2.test, p2.demo | test |
| The player's avatar, 2D and 3D | p2.avatar(), p2.items.list() | travel#avatar |
| Travel with the party | p2.travel.to(slug, { params, place }), .home(), .links() | travel#travel |
Multiplayer, through p2.rooms:
| Feature | Calls | Docs |
| --- | --- | --- |
| Matches, private codes, parties | p2.rooms.join({ mode, size, teams, skill, together, code, room }), .create(), .party() | rooms-join |
| Messages and shared state | room.send(type, data, { to, fast }), room.on("message:<type>"), room.set, room.get, room.state | rooms-talk |
| Smooth movement | room.sync(object, options) | rooms-sync |
| Ping, stats, the room's clock | room.ping(), room.stats(), room.now() | rooms-fast |
| Your server code (room.js) | see below | rooms-scripted |
| What each player owns of your store, in room.js | player.owned, room.owned(id), room.owns(id, keyOrRef), onOwned | rooms-scripted |
| Input-run rooms (client prediction, corrected by the server's state) | room.inputs({ state, input, step }) | rooms-inputs |
| Corrections and lag-compensated hits | onSync, room.correct, room.past (room.js); sync.seen(id) | rooms-corrections |
| Server-moved objects | room.objects() (page), room.objects.set (room.js) | rooms-objects |
| Physics engines in WebAssembly | a room/ folder | rooms-engines |
| Outside data, checked (a feed's signed items, or a signed call's answer, relayed by a page) | checkFeedItem(key, item, sig) (room.js) | rooms-feeds |
| Teams and party matches | { teams, together }, room.team(id, n) | rooms-teams |
| Matching by skill (Elo by mode) | { skill: true }, room.result(places) | rooms-matching |
| Ranked boards and server-given trophies | room.score, room.trophy (room.js) | rooms-ranked |
| Watching and replays | p2.rooms.live(), .watch({ room }), .replays(), .replay(id), room.record() | rooms-watch |
| Worlds of up to 256 an area | p2.rooms.world(name, { area }) | rooms-worlds |
| Voice chat (24 a room) | room.voice.join(), .leave(), .mute(), .volume(id, v), .speaking(id) | rooms-voice |
| A bad connection, on purpose | p2.rooms.simulate({ lag, jitter, loss }) or ?p2-net=150,30,0.02 | rooms-simulate |
Rooms are 1 to 64 players (256 in an area of a world) and are for games hosted on PlayerTwo (a build you push, or a game already played from its own site that PlayerTwo serves). A release never mixes versions in a room. All limits: https://playertwo.plus/docs/sdk#rooms-limits.
A room's server: playertwo-sdk/room
Put a room.js (one ES module, up to 1 MB) at the root of the build you push, and every room of that build runs it on
PlayerTwo's servers: a sandbox with no network, 250 ms of CPU a call (over 60 ms is told to the studio as slow), 1 to 60 ticks a second. In a scripted room your
pages' messages go to your code, and only your code writes the shared state, so a player can't fake a hit or a score.
PlayerTwo takes the file out of your build and never serves it to players.
Plain JavaScript with JSDoc types (it is pushed as it is):
// @ts-check
/** @typedef {import("playertwo-sdk/room").Room} Room */
/** @typedef {import("playertwo-sdk/room").Player} Player */
export const tickRate = 20;
/** @param {Room} room @param {Player} player */
export function onJoin(room, player) {
room.state.set("hello", player.handle);
}Bundled from TypeScript into one file, defineRoom types every hook at once:
import { defineRoom } from "playertwo-sdk/room";
export const { tickRate, onCreate, onJoin, onLeave, onMessage, onSync, onTick } = defineRoom<{ coins: number }>({
tickRate: 20,
onCreate(room) { room.data.coins = 8; },
onSync(room, player, values) { return Math.abs(values["position.x"]) < 18 ? values : false; },
});Hooks: onCreate, onStart, onJoin, onLeave, onMessage, onSync, onTick. Everything room has:
room.d.ts.
Outside data in a room
Room code has no network. A feed (set up by your agent: PUT /api/v1/agent/games/<slug>/feeds/<name>) is an https
address PlayerTwo fetches for your game every 60 to 3,600 seconds while it is being opened; with items and signed,
each item of its list comes with sig, the hex HMAC-SHA256 of JSON.stringify(item) keyed with the feed's key (its 64
hex characters, as text, shown once when it is made). A page reads it and relays each item; the room checks it with the
key built into room.js, so a player can't make one up:
// a page
const feed = await p2.feeds.get("x-posts"); // { at, items: [{ item, sig }] }
for (const x of feed.items) room.send("x-post", x);
// room.js
import { checkFeedItem } from "playertwo-sdk/room"; // synchronous, plain JavaScript (no WebCrypto needed)
const FEED_KEY = "9f1c..."; // the feed's key, 64 hex characters
export function onMessage(room, player, type, data) {
if (type === "x-post" && checkFeedItem(FEED_KEY, data?.item, data?.sig)) use(room, data.item);
}A feed is public (anyone can read GET /api/v1/games/<slug>/feeds/<name>); its secret, put into a header's
{{secret}} as it is fetched, never leaves PlayerTwo. A game nobody opened in the last 24 hours has its feeds left
alone until someone does. Every rule: https://playertwo.plus/docs/sdk#feeds-setup.
A call with a secret (PUT /api/v1/agent/games/<slug>/calls/<name>) is made for one player when their page asks,
p2.calls.run(name, data); a signed one's answer carries call, player, at and sig, which the room checks the
same way: const { sig, ...answer } = data; checkFeedItem(CALL_KEY, answer, sig), then that answer.player is the
player who sent it and answer.at is recent. Every rule: https://playertwo.plus/docs/sdk#secret-calls.
Building without PlayerTwo
On localhost, a stand-in answers every call from memory, and two tabs are two players. If your dev server serves
/room.js, the first tab runs it as the room's server. Give the stand-in your trophies, add-ons, products and params
with init({ local: { ... } }) (and what p2.feeds.get answers, local.feeds, and p2.calls.run, local.calls); local: true (or { force: true }) uses it wherever the game runs. There, p2.track and errors are said in the console. Voice needs a
room on PlayerTwo. Docs: https://playertwo.plus/docs/sdk#start-local.
On PlayerTwo you, your team and your playtesters play in test mode (p2.test is true): every call works, nothing is
paid, and what you earn is kept apart. Docs: https://playertwo.plus/docs/sdk#test.
Using the script tag and only want the types of the global PlayerTwo? Add "types": ["playertwo-sdk"] to your
tsconfig.json, or /// <reference types="playertwo-sdk" /> at the top of a file.
In-game purchases
Two ways, and a game can use both: products you make in your studio (p2.store.buy(key)), or charges your own server
makes at its own prices with your game key (p2.store.pay(chargeId)). PlayerTwo's own card takes the player's yes
and the payment from their PlayerTwo balance (one balance, added by card, PayPal or stablecoins), showing the piece's
picture big when you give one. You get 80% of every in-game purchase, PlayerTwo keeps
20% (less your backers' share if your game raised with a share of its sales). Add-ons sold on the game's page are split
as its sales are: PlayerTwo keeps 20%. Every purchase gives your game a signed receipt (a JWT typed p2-buy, RS256,
keys at https://playertwo.plus/.well-known/p2-keys.json) and your studio's webhooks a purchase event.
- Who may buy:
p2.store.access()says where the player stands:owned,free-game,free-period(a paid game played free for a while, withuntil),testornone. Every state butnonemay buy in the game, and what they buy stays theirs. - Counts: each product's
owners("Owned by N players"), andp2.store.sold(refs): how many of your charges were paid with each ref. A paid charge carries itsnumberamong them, for "#12 of Season 1". - Seasons: a product's
onSaleFromandonSaleUntiltake it on and off sale by themselves, and its owners keep it.p2.store.list({ coming: true })lists the ones not on sale yet,coming: true, never buyable. - Packs: a pack can be sold only to a player who owns none of its pieces (
noneOwned). - First purchase: a product can be sold only as a player's first purchase in the game, and so once
(
firstPurchase, a starter pack):list()sayseligiblefor the player, andbuyrejectsbought-beforeonce they've bought anything in the game. - A ready-made shop:
p2.store.open()shows PlayerTwo's own shop screen beside your game, your products in tabs by kind with owned marks, the first-purchase pack and the daily deal, bought on PlayerTwo's card; it resolves with what was bought as the player closes it.p2.store.onTryOn(product => ...)shows what they look at on them in your game (null when the look ends). - A daily deal: turned on in your studio (20% off, or 10 to 90), one product a UTC day at that share off, first in
the shop screen and in
p2.store.deal(); its product'spriceinlist()is the deal's, withdealbeside it. - In a room: each player's
ownedarrives as they take their seat and again when they buy (onOwned);room.owns(id, keyOrRef)refuses a look they don't own.
Docs: https://playertwo.plus/docs/sdk#purchases and https://playertwo.plus/docs/sdk#store-access.
Donations
Players can donate to your studio for your game, even while it's free. Turn donations on in your studio (Sell,
Donations) and pick their one place: your game's PlayerTwo page (PlayerTwo's card, in your words, colour and picture),
or inside the game. Inside the game, your own button calls p2.donate.open() to open PlayerTwo's donation sheet, or
p2.donate.button() puts PlayerTwo's pixel-heart "Support the dev" button in a corner (or inside an element of yours);
p2.donate.available() says whether donations are on inside the game. A press of the player's opens the sheet at once,
however soon after the last (call open() within a second of it); asked without one, it opens at most once every two
minutes (too-soon). The entire donation, minus the transaction fees,
goes to your studio: PlayerTwo takes no cut. A donation buys nothing in the game, and the game never learns who gave
or how much, so it never belongs in your shop. Docs: https://playertwo.plus/docs/sdk#donate.
Your game's own server
A game key (p2g_..., made in your studio) lets your server check a session or a signed identity from
p2.identity(), give server-only trophies, post to trusted leaderboards, read add-ons, make and check charges, use up
consumables and report matches, under https://playertwo.plus/api/v1/sdk/server/.... Docs:
https://playertwo.plus/docs/sdk#server and https://playertwo.plus/docs/sdk/connect (a game already played on its own
site).
Progress from before PlayerTwo
If your game played somewhere else first, bring each player's progress with them. List your old site's origin in your studio (How it's served › Where it played before), then make a one-time code there:
import { transfer } from "playertwo-sdk";
const { code, url } = await transfer({ game: "your-slug", local: true, account: oldPlayerId });
// show the player `url` (opens your game on PlayerTwo with the code) or `code` (ABCD-EFGH) to type inOr from your own server, for progress in your database (Supabase, Firebase...): POST
https://playertwo.plus/api/v1/sdk/server/transfers with your game key. In the game on PlayerTwo:
try {
const got = await p2.saves.import(); // the code from the link, or p2.saves.import("ABCD-EFGH")
// got.saves (each with .json(), .text(), .bytes()) and got.local: write them into your own saves
} catch (e) { /* e.code: no-code, unknown-code, expired, used, account-moved... */ }A code works once, for the first signed-in player who claims it, and is kept 7 days; an account moves to one
PlayerTwo player only. What a browser holds can be edited by its player, so make codes from your server for progress
that matters. Docs: https://playertwo.plus/docs/sdk#saves-import.
Putting it on PlayerTwo
A whole game to start from: npm create playertwo-game@latest my-game (a small multiplayer Three.js game with rooms
and room.js, see create-playertwo-game).
- Submit the game at https://playertwo.plus/submit with its web build: a zip of its folder (up to 5 GB unpacked,
20,000 files, 512 MB a file), sent from your browser a file at a time, or one .html page. That gives it its
address,
your-game. Playing from your own site is closed to new games. - Each update goes up the same way (a zip, from its page's editor in your studio), or pushed: make an agent key in your studio, under Agents.
- Push the build:
curl -fsSLO https://playertwo.plus/cli/p2.mjs
P2_AGENT_KEY=p2_agent_... node p2.mjs push dist --game your-game --version 1.0.0It plays at https://your-game.playertwo.cc/ in PlayerTwo's player, with no code changes. A pushed folder may be up to
5 GB and 20,000 files; only the files PlayerTwo doesn't have yet are sent. Docs: https://playertwo.plus/docs/hosting.
For AI agents: MCP and the agent API
PlayerTwo runs an MCP server (Streamable HTTP) at https://playertwo.plus/api/mcp:
claude mcp add --transport http player-two https://playertwo.plus/api/mcp
claude mcp add --transport http player-two https://playertwo.plus/api/mcp --header "Authorization: Bearer p2_agent_..."The first line is enough for the public tools, which need no key: get_submission_guide and check_game, and
search_games, list_games, get_game_facts, get_sdk_docs and where_to_publish. Tools that change a game
(submit it, edit its page, upload media and web builds, define trophies, leaderboards and products, roll back builds,
post updates, read its rooms) need the player's agent key, made in their studio on playertwo.plus under Agents, or no
key at all in a client that signs in (Claude's and ChatGPT's connectors, Claude Code, Cursor): the first time it calls
one, the player is asked to sign in to PlayerTwo and allow it (OAuth 2.1 with PKCE). Its server card is at
https://playertwo.plus/.well-known/mcp.json.
- The agent API:
GET https://playertwo.plus/api/v1/agent/guideexplains every field; submit withPOST https://playertwo.plus/api/v1/agent/games{ "draft": { ... }, "publish": true }. - OpenAPI 3.1 spec: https://playertwo.plus/openapi.json
- For language models: https://playertwo.plus/llms.txt
- Docs: https://playertwo.plus/docs#agents
License
MIT. Copyright (c) 2026 PlayerTwo.
