Skip to content

Playtest rules script API ​

A playtest rules script describes a playtest table: which piles (zones) exist and where they sit, who can see them, what you can do to cards and zones, which keys do it, and how a game starts. It returns plain data, never code to call later. Turny.gg's own table engine runs everything the definition describes, which is what makes every action instant, undoable and safe to share.

For a walkthrough of playing, writing and sharing playtest rules, see the playtest guide.

The contract ​

A playtest script defines one function, playtest, and returns a table definition:

js
export default function playtest(deck, cardsById, ctx) {
  const cards = [];

  Object.keys(deck.main).forEach((code) => {
    for (let copy = 0; copy < deck.main[code]; copy += 1) {
      cards.push(code);
    }
  });

  return {
    version: 1,
    table: { columns: 2, rows: 1 },
    zones: [
      {
        id: "deck",
        label: "Deck",
        owner: "side",
        visibility: "hidden",
        layout: "pile",
        area: { row: 0, col: 0 },
        ordered: true,
        defaultFaceDown: true,
        primaryActionId: "draw",
      },
      {
        id: "hand",
        label: "Hand",
        owner: "side",
        visibility: "private",
        layout: "fan",
        area: { row: 0, col: 1 },
        ordered: true,
        defaultFaceDown: false,
      },
    ],
    trackers: [],
    markers: [],
    actions: [
      {
        id: "draw",
        label: "Draw",
        target: "zone",
        zones: ["deck"],
        steps: [{ kind: "draw", from: "deck", to: "hand" }],
      },
    ],
    setup: [{ kind: "shuffle", zone: "deck" }],
    initialZones: { deck: cards },
  };
}

Turny.gg finds the function in one of three ways, in this order:

  1. export default function playtest(...) { ... } (any name, or none, works here).
  2. export default <expression>, where the expression is a function.
  3. A top-level function declared as function playtest(...) { ... }.

The script runs once per game setup, in the same sandbox as custom rulesets and calculators: no network, no timers, no async, and only a short list of built-in globals. See Script sandbox for exactly what is allowed. After that, the table never calls the script again: clicks and shortcuts run the definition's steps directly.

Arguments ​

#ArgumentTypeDescription
1deckPlaytestScriptDeckThe player's deck: card code to number of copies, per deck zone (fields below).
2cardsByIdRecord<string, Card>Every card the table can show, by card code: your deck and, in Versus with a different opponent deck, theirs too. Game-specific fields live on card.game; see the card data reference for your game.
3ctxPlaytestScriptContext | undefinedOptional catalog context (fields below). May be undefined: a script that reads it must work without it.

PlaytestScriptDeck:

The deck argument of a playtest script: card code → copy count per deck zone. Zones a game does not use are empty objects, never absent.

PropertyTypeDescription
mainRecord<string, number>
sideboardRecord<string, number>
commandRecord<string, number>

PlaytestScriptContext:

PropertyTypeDescription
globalsunknownThe game catalog's globals document; its shape is per game.

Things to know about the arguments:

  • They are read-only. deck, cardsById and ctx are frozen copies. Build new arrays and objects instead of changing them.
  • A card can be missing. Guard cardsById[code] before reading from it.
  • Card fields are per game. Everything game-specific lives on card.game. See the card data reference for Cyberpunk TCG, Flesh and Blood, Hearthstone, Legends of Runeterra, Palworld TCG, Pokémon TCG and Riftbound.
  • One definition serves both sides. In Versus the opponent's board uses the same definition. When the opponent plays a different deck, the script runs a second time over that deck and only its initialZones is used, so compute cardTags from cardsById (which covers both decks) rather than from deck.

Return value ​

playtest returns a PlaytestDefinition. Every string value that names an option, such as owner: "side" or kind: "draw", is one of the enum values listed under Enums. Anything else, a missing field, or a reference to something the definition does not declare is rejected with an issue code, and the table is not built.

The table definition ​

How the table is laid out ​

Each side of the table is a grid of table.columns by table.rows cells. A zone's area picks its cells, 0-based. Row 0 borders the middle of the table: your half is drawn below the middle and the opponent's half is its mirror image above it, so row 0 is always the row nearest your opponent.

A zone with owner: "shared" exists once for the whole table and sits in a strip between the two halves. The strip has table.sharedRows rows (1 when any zone is shared and it is not set) and the same columns as each side. Two zones with the same owner may not cover the same cell, and every zone must fit inside its grid.

PlaytestDefinition ​

The manifest a playtest script returns: export default function playtest(deck, cardsById, ctx) runs once per game setup and returns this plain data. The engine never calls back into the script.

PropertyTypeDescription
version1Manifest format version.
tablePlaytestTableDefinitionTable grid size.
zonesPlaytestZoneDefinition[]Every zone on the table.
trackersPlaytestTrackerDefinition[]Numeric counters on sides or the table.
markersPlaytestMarkerDefinition[]Counters and badges placed on cards.
flags?PlaytestFlagDefinition[]On/off card flags that flag steps set. Omitted declares none.
actionsPlaytestActionDefinition[]Everything the player can do.
roundActionId?stringThe action the toolbar Turn button runs (a Game- or Side-target action, usually "New turn"). The button shows the engine's turn counter. A Side action counts turns: in Versus each click starts the next turn for the other side (the side that did not last advance the counter). A Game action counts rounds that advance the whole table at once. Omitted: the button only displays the count, as turns.
setupPlaytestStep[]Steps run for each side on New game, after initialZones is placed.
initialZonesRecord<string, string[]>Where the deck's cards start: zone id → card codes, repeated once per copy. Applied per side from that side's deck.
cardTags?Record<string, string[]>Tags per card code, computed by the script from cardsById; tag predicates read them.
associatedCards?Record<string, string[]>Associated card codes per card code (level-ups, tokens, created cards), computed by the script from cardsById (which includes each deck card's catalog associatedCardRefs). Card params with an associated source read it.

table (PlaytestTableDefinition) ​

The per-side table grid.

PropertyTypeDescription
columnsnumberGrid columns per side; the shared strip uses the same columns.
rowsnumberGrid rows per side.
sharedRows?numberRows of the shared strip between the two halves. Defaults to 1 when any zone is shared.

zones (PlaytestZoneDefinition) ​

One zone (pile) on the table.

PropertyTypeDescription
idstringUnique id within the definition, referenced by steps and predicates.
labelstringDisplay name.
labelKey?stringOptional i18n key under playtest.labels.*; falls back to label.
ownerPlaytestZoneOwnerOnce per side, or once for the table.
visibilityPlaytestZoneVisibilityWho sees card faces.
layoutPlaytestZoneLayoutHow cards are arranged.
areaPlaytestZoneAreaGrid placement. Side zones use the side grid; shared zones use the strip between the halves (table.sharedRows), or the player's side grid when sharedPlacement is PlayerGrid.
sharedPlacement?PlaytestSharedPlacementShared zones only: where the zone renders. Defaults to Strip.
removesCreated?booleanWhen true, created cards (created: true) that enter this zone leave the game instead, e.g. MTG tokens going to the graveyard.
capacity?numberMax cards (or card stacks for Slots). Omitted is unlimited. A capacity step can change it per zone instance during a game.
orderedbooleanWhether card order matters (a deck, a discard pile).
defaultFaceDownbooleanFace state a card takes on entry when the moving step does not set one.
enterState?PlaytestZoneEnterStateState forced on every entering card.
showCount?booleanShows a card-count badge. Defaults to true for Pile layouts.
primaryActionId?stringAction run by clicking the zone itself (e.g. the deck draws). Alt-click runs it on the opponent's zone.
accepts?PlaytestPredicateCards must match this to be dropped or moved in; others are refused.
dropActionId?stringAction run when cards are dropped onto the zone, instead of a plain moveCards. The dropped cards are its targets.

Zone area (PlaytestZoneArea) ​

Where a zone sits in its side's table grid. Cells are 0-based. Row 0 borders the centre of the table; the opponent half renders mirrored, so its row 0 also borders the centre.

PropertyTypeDescription
rownumber0-based row.
colnumber0-based column.
rowSpan?numberRows spanned. Defaults to 1.
colSpan?numberColumns spanned. Defaults to 1.

Zone enter state (PlaytestZoneEnterState) ​

State forced on every card that enters a zone, over the moving step's values.

PropertyTypeDescription
rotation?PlaytestRotationRotation to set, e.g. 0 so a discarded card is ready.
faceDown?booleanFace state to set, e.g. false so a hand never holds face-down cards.
resetCounters?booleanWhen true, clears every marker count on entry.
resetFlags?booleanWhen true, clears every flag on entry.

trackers (PlaytestTrackerDefinition) ​

A numeric counter on a side or on the table (life, prizes, points, mana).

PropertyTypeDescription
idstringUnique id within the definition.
labelstringDisplay name.
labelKey?stringOptional i18n key under playtest.labels.*; falls back to label.
initialnumberValue on New game.
min?numberLowest allowed value.
max?numberHighest allowed value.
ownerPlaytestZoneOwnerOne per side, or one shared.

markers (PlaytestMarkerDefinition) ​

A counter or badge placed on cards (damage, +1/+1, buffs).

PropertyTypeDescription
idstringUnique id within the definition.
labelstringDisplay name.
labelKey?stringOptional i18n key under playtest.labels.*; falls back to label.
stepnumberAmount one +/- click changes it by, e.g. 10 for Pokémon damage.
min?numberLowest allowed count. Defaults to 0.
color?stringCSS color of the badge. Omitted picks a palette color.

flags (PlaytestFlagDefinition) ​

A named on/off state cards can carry ("Stunned", "Doesn't untap", "Ability used"). Declared so the table can label the chips it draws on cards.

PropertyTypeDescription
idstringUnique id within the definition, referenced by steps and predicates.
labelstringDisplay name.
labelKey?stringOptional i18n key under playtest.labels.*; falls back to label.

actions (PlaytestActionDefinition) ​

Something the player can do: a named, triggerable list of steps.

PropertyTypeDescription
idstringUnique id within the definition; the history references it.
labelstringMenu and shortcut-sheet text.
labelKey?stringOptional i18n key under playtest.labels.*; falls back to label.
description?stringOptional plain-language help: what the action does and how to aim it (which card to select or hover). Shown under the label in the shortcut sheet and as the menu entry's tooltip.
targetPlaytestActionTargetWhat the action operates on.
zones?string[]Limits where the action applies: for Card / Selection, cards in these zones; for Zone, these zones. Omitted applies everywhere.
when?PlaytestPredicateFor Card / Selection, every target card must match or the action is hidden and its shortcut does nothing. Ignored for other targets.
triggers?PlaytestActionTrigger[]Pointer inputs that run the action.
menu?booleanLists the action in the target's right-click menu. Defaults to true.
group?stringMenu section heading; actions sharing a group are listed together.
shortcut?stringKeyboard shortcut, matched on physical keys (KeyboardEvent.code), so letters and digits are layout-independent. Grammar: a key ("d"), optionally prefixed by shift+ and/or mod+ (Cmd on macOS, Ctrl elsewhere), e.g. "shift+d", "mod+d". The digit range "1-9" binds every digit and passes the pressed digit as the action's first Number param.

alt is reserved: the same input with Alt held runs the action on the opponent side, so any shortcut containing alt is rejected. The keys in PLAYTEST_RESERVED_SHORTCUTS are also rejected.
params?PlaytestActionParam[]Values the user supplies; steps read them with { param: "<id>" }.
stepsPlaytestStep[]Steps run in order, as one undo unit.

Action params (PlaytestActionParam) ​

A value the user supplies when running an action (draw N, which zone).

PropertyTypeDescription
idstringId steps reference with { param: "<id>" }.
labelstringPrompt text.
labelKey?stringOptional i18n key under playtest.labels.*; falls back to label.
kindPlaytestActionParamKindNumber or choice.
default?number | stringPre-filled value; required for the action to run without a prompt.
min?numberLowest allowed Number value.
max?numberHighest allowed Number value.
options?PlaytestActionParamOption[]The options of a Choice param.
cardSource?PlaytestCardSourceWhere a Card param's candidates come from.

Param options (PlaytestActionParamOption) ​

One selectable option of a Choice param.

PropertyTypeDescription
valuenumber | stringThe value passed to steps.
labelstringDisplay name.
labelKey?stringOptional i18n key under playtest.labels.*; falls back to label.

Card source (PlaytestCardSource) ​

Candidates for a Card param: the target card's associated cards (PlaytestDefinition.associatedCards), optionally narrowed by tags (where may only use tag leaves and all/any/not).

PropertyTypeDescription
kindPlaytestCardSourceKindWhich cards are offered.
where?PlaytestPredicateKeep only candidates whose tags satisfy this predicate.

Enums ​

Scripts write these as plain strings: the Value column is what goes in your script.

PlaytestZoneOwner ​

How many instances of a zone (or tracker) exist.

MemberValueDescription
Side"side"Instantiated once per side (deck, hand, discard, life).
Shared"shared"Exists once for the whole table (Pokémon stadium, Riftbound battlefields).

PlaytestZoneVisibility ​

Who may see the faces of a zone's cards (Cockatrice's three zone types).

MemberValueDescription
Hidden"hidden"Nobody sees faces, the owner included (a deck).
Private"private"The owner sees faces; the other side sees card backs (a hand).
Public"public"Everyone sees faces, except cards that are themselves face-down (a board).

PlaytestZoneLayout ​

How a zone arranges its cards on the table.

MemberValueDescription
Pile"pile"A single stack; only the top card shows.
Fan"fan"Overlapping cards in a fan (a hand).
Row"row"Cards side by side in one line.
Grid"grid"Cards in rows and columns.
Slots"slots"A fixed number of empty spots (capacity), one card stack per spot (a bench).
Freeform"freeform"Cards sit at free x / y positions inside the zone.

PlaytestSharedPlacement ​

Where a Shared zone renders on the table.

MemberValueDescription
Strip"strip"In the strip between the two halves (default).
PlayerGrid"playerGrid"Inside the player's half at the zone's area, beside side zones (e.g. a Pokémon Stadium left of Active). The mirrored opponent half leaves that cell empty.

PlaytestActionTarget ​

What an action operates on.

MemberValueDescription
Card"card"A single card (the clicked, hovered or right-clicked card).
Selection"selection"Every selected card. Falls back to the hovered card when nothing is selected.
Zone"zone"A zone (clicking a deck, a zone's menu).
Side"side"A side as a whole (mulligan, next turn).
Game"game"The whole table (roll a die).

PlaytestActionTrigger ​

Pointer inputs that can run an action (shortcuts are declared separately).

MemberValueDescription
Click"click"A click, or a tap on touch devices.
DoubleClick"doubleClick"
ContextMenu"contextMenu"Listed in the right-click (long-press on touch) menu.
Drop"drop"Cards dropped onto the target.

PlaytestActionParamKind ​

The value type of an PlaytestActionParam.

MemberValueDescription
Number"number"An integer between min and max. The "1-9" shortcut binds the first one.
Choice"choice"One of the listed options.
Card"card"A card code picked from cardSource (e.g. one of the target's associated cards). The picker is skipped when exactly one card qualifies.

PlaytestCardSourceKind ​

Where a Card param's candidates come from.

MemberValueDescription
Associated"associated"The target card's associated cards.

PlaytestZonePosition ​

Where a card goes in, or is taken from, an ordered zone.

MemberValueDescription
Top"top"
Bottom"bottom"
Random"random"A seeded-random position; consumes the game RNG.
Index"index"An explicit 0-based index from the top (see the step's index).

PlaytestAttachMode ​

How an attached card sits relative to its host.

MemberValueDescription
Under"under"Tucked beneath the host, which stays the visible card (energy, equipment).
Over"over"Placed on top of the host and becomes the visible card (evolution).

PlaytestFlagMode ​

What a flag step does to each card.

MemberValueDescription
Set"set"Adds the flag (no-op when the card has it).
Clear"clear"Removes the flag (no-op when the card lacks it).
Toggle"toggle"Adds the flag to cards without it and removes it from cards with it.

PlaytestTrackerRefSide ​

Which instance of a tracker a PlaytestTrackerRef reads.

MemberValueDescription
Self"self"The acting side's instance (inside forEachSide, the side being run).
Other"other"The other side's instance. Resolves to nothing when that side is not in play (Solo).
Shared"shared"The table's instance of a Shared tracker.

PlaytestRotation ​

A card's rotation in degrees, clockwise. 90 is tapped / exhausted; 0 is ready.

Allowed values: 0, 90, 180, 270.

Steps ​

An action's steps (and the definition's setup) are lists of primitive steps. The engine runs them in order. Each step acts for the acting side: the side the action runs for (yours, or the opponent's when you hold Alt). A zone id in a step names the acting side's copy of that zone, unless the zone is shared.

Most card steps act on the action's targets (the card, the selection, or every card in the target zone) unless you give them a cards selector.

Values ​

A literal value, or a reference resolved when the step runs: a PlaytestParamRef for any field, and also a PlaytestTrackerRef for a numeric field.

{ param } (PlaytestParamRef):

PropertyTypeDescription
paramstringId of a param declared in the action's params.

{ tracker } (PlaytestTrackerRef):

A reference to a tracker's current value, usable wherever a step field is typed PlaytestValue<number>. { tracker: "manaGems" } reads the acting side's mana gems when the step runs, so { kind: "tracker", tracker: "mana", set: { tracker: "manaGems" } } refills mana.

Resolution: a Shared tracker always reads the table's value. A Side tracker reads the acting side (self, the default) or the other side (other). A reference to a side that is not in play (other in Solo) resolves to nothing, and a step whose value resolves to nothing is skipped.

PropertyTypeDescription
trackerstringId of a tracker in the definition's trackers.
side?PlaytestTrackerRefSideWhich instance to read. Omitted reads the acting side for a Side tracker and the table for a Shared one. shared only names a Shared tracker; self / other only name Side trackers.

Card selectors ​

Which cards a card-level step acts on when it should not act on the action's targets, e.g. "the top 3 cards of the deck".

PropertyTypeDescription
zonePlaytestValue<string>Zone to take cards from.
count?PlaytestValue<number>How many cards to take. Omitted takes every matching card.
pick?PlaytestZonePositionWhich end to take from (Index is not allowed here). Defaults to Top.
where?PlaytestPredicateOnly cards matching this predicate are taken.

Step kinds ​

One step, discriminated by kind. An action runs its steps in order as a single undo unit. forEachSide and repeatUntil are block steps holding one level of primitive steps.

kindDescription
"move"Move cards to a zone. Acts on cards when given, else on the action's targets (the card, the selection, or every card of the target zone).
"draw"Move the top count cards of one zone to another, one at a time (draw N).
"shuffle"Shuffle a zone with the seeded game RNG (redo reproduces the same order).
"flip"Turn cards face-up or face-down.
"rotate"Rotate cards (tap / exhaust).
"counter"Change a marker's count on cards. Set exactly one of delta and set. The result is clamped to the marker's min.
"attach"Attach cards to a host card. The host is the record's targets.onto (the card a drop landed on). Without one, the last target card is the host and the other targets attach to it. Attached cards move to the host's zone.
"detach"Detach cards from their host. A target that is itself a host detaches everything attached to it. Detached cards stay in their zone unless to is set.
"tracker"Change a tracker's value. Set exactly one of delta, set and toggle. The result is clamped to the tracker's min / max. A Shared tracker changes once per step, whichever side runs it.
"readyAll"Rotate every card in the listed zones back to 0 (untap / ready all). Cards carrying skipFlag stay as they are (MTG's "doesn't untap").
"reveal"Show or hide cards to both sides regardless of zone visibility or face state (reveal the top card, show a hand).
"random"Roll a die with the seeded game RNG and write the result to the log.
"log"Append a line of text to the game log.
"turn"Change the game turn counter (PlaytestGameState.turn). Set exactly one of delta and set; both omitted adds 1.
"flag"Set, clear or toggle a named flag on cards ("Stunned", "Ability used"). Flags are on/off; declare each in the definition's flags.
"clearFlag"Clear a flag on every card in the listed zones, e.g. Pokémon clearing "Ability used" at the start of a turn. Mirrors readyAll.
"capacity"Change a zone instance's capacity for the rest of the game (Pokémon's "Expand bench" to 8). Set exactly one of delta and set. The result is stored in the side (or shared) state's capacities and honoured by every move; it never drops below 0 and never evicts cards already there. delta on a zone without a capacity does nothing. New game resets it.
"forEachSide"A block step: runs steps once per side in play (player first), each time with that side as the acting side. Side zones, side trackers and { tracker } refs resolve against the side being run; the action's targets and params are unchanged. Steps on Shared trackers belong outside the block so they run once: a Game-target "Next round" readies and draws for both sides inside the block and increments a shared round counter after it.
"repeatUntil"A block step: while until is false, runs steps again, at most maxIterations times (a Pokémon mulligan: shuffle the hand back and redraw until it holds a Basic). until is checked before each pass, so a condition that already holds runs nothing. Each pass consumes the seeded RNG, so redo reproduces it, and logs its 1-based iteration.
"create"Create new card instances (a copy of the target, a picked associated card, or a fixed code). New instances carry created: true.
"transform"Change each target's card code in place (e.g. a champion levelling up). Zone, position, counters, flags and attachments are kept.
"remove"Remove created cards (created: true) from the game; other cards are ignored.

kind: "move" ​

Move cards to a zone. Acts on cards when given, else on the action's targets (the card, the selection, or every card of the target zone).

PropertyTypeDescription
cards?PlaytestCardSelectorCards to move. Omitted moves the action's targets.
toPlaytestValue<string>Destination zone id.
position?PlaytestZonePositionWhere the cards go in the destination. Defaults to Top.
index?PlaytestValue<number>0-based index from the top; required when position is Index.
faceDown?booleanFace state after the move. Omitted uses the destination's defaultFaceDown. The destination's enterState still wins.

kind: "draw" ​

Move the top count cards of one zone to another, one at a time (draw N).

PropertyTypeDescription
fromPlaytestValue<string>Zone drawn from (usually the deck).
toPlaytestValue<string>Zone drawn into (usually the hand).
count?PlaytestValue<number>Cards to draw. Defaults to 1; stops early when from runs out.
faceDown?booleanFace state in to. Omitted uses the destination's defaultFaceDown.

kind: "shuffle" ​

Shuffle a zone with the seeded game RNG (redo reproduces the same order).

PropertyTypeDescription
zonePlaytestValue<string>Zone to shuffle.

kind: "flip" ​

Turn cards face-up or face-down.

PropertyTypeDescription
cards?PlaytestCardSelectorCards to flip. Omitted flips the action's targets.
faceDown?booleanThe face state to set. Omitted toggles each card.

kind: "rotate" ​

Rotate cards (tap / exhaust).

PropertyTypeDescription
cards?PlaytestCardSelectorCards to rotate. Omitted rotates the action's targets.
to?PlaytestRotationThe rotation to set. Omitted toggles each card between 0 and 90.

kind: "counter" ​

Change a marker's count on cards. Set exactly one of delta and set. The result is clamped to the marker's min.

PropertyTypeDescription
cards?PlaytestCardSelectorCards to change. Omitted changes the action's targets.
markerstringId of a marker in the definition's markers.
delta?PlaytestValue<number>Amount to add (negative removes).
set?PlaytestValue<number>Absolute count to set. 0 removes the marker.

kind: "attach" ​

Attach cards to a host card. The host is the record's targets.onto (the card a drop landed on). Without one, the last target card is the host and the other targets attach to it. Attached cards move to the host's zone.

PropertyTypeDescription
cards?PlaytestCardSelectorCards to attach. Omitted attaches the action's targets.
modePlaytestAttachModeWhether the cards go under or over the host.

kind: "detach" ​

Detach cards from their host. A target that is itself a host detaches everything attached to it. Detached cards stay in their zone unless to is set.

PropertyTypeDescription
cards?PlaytestCardSelectorCards to detach. Omitted detaches the action's targets.
to?PlaytestValue<string>Optional zone to move the detached cards to.
position?PlaytestZonePositionWhere they go in to. Defaults to Top.

kind: "tracker" ​

Change a tracker's value. Set exactly one of delta, set and toggle. The result is clamped to the tracker's min / max. A Shared tracker changes once per step, whichever side runs it.

PropertyTypeDescription
trackerstringId of a tracker in the definition's trackers.
delta?PlaytestValue<number>Amount to add (negative subtracts).
set?PlaytestValue<number>Absolute value to set.
toggle?trueFlips a 0/1 tracker (an attack token): 0 becomes 1, anything else becomes 0. The tracker must declare min: 0, max: 1.

kind: "readyAll" ​

Rotate every card in the listed zones back to 0 (untap / ready all). Cards carrying skipFlag stay as they are (MTG's "doesn't untap").

PropertyTypeDescription
zonesstring[]Zone ids to ready.
skipFlag?stringId of a flag in the definition's flags; cards with it are not readied.

kind: "reveal" ​

Show or hide cards to both sides regardless of zone visibility or face state (reveal the top card, show a hand).

PropertyTypeDescription
cards?PlaytestCardSelectorCards to reveal. Omitted reveals the action's targets.
revealed?booleanWhether the cards are revealed. Omitted toggles each card.

kind: "random" ​

Roll a die with the seeded game RNG and write the result to the log.

PropertyTypeDescription
diePlaytestValue<number>Number of sides; 2 is a coin flip.
count?PlaytestValue<number>Number of dice to roll. Defaults to 1.

kind: "log" ​

Append a line of text to the game log.

PropertyTypeDescription
messagestringThe text, shown verbatim.

kind: "turn" ​

Change the game turn counter (PlaytestGameState.turn). Set exactly one of delta and set; both omitted adds 1.

PropertyTypeDescription
delta?PlaytestValue<number>Amount to add.
set?PlaytestValue<number>Absolute turn number to set.

kind: "flag" ​

Set, clear or toggle a named flag on cards ("Stunned", "Ability used"). Flags are on/off; declare each in the definition's flags.

PropertyTypeDescription
cards?PlaytestCardSelectorCards to change. Omitted changes the action's targets.
flagstringId of a flag in the definition's flags.
modePlaytestFlagModeWhat to do to each card.

kind: "clearFlag" ​

Clear a flag on every card in the listed zones, e.g. Pokémon clearing "Ability used" at the start of a turn. Mirrors readyAll.

PropertyTypeDescription
flagstringId of a flag in the definition's flags.
zonesstring[]Zone ids to clear.

kind: "capacity" ​

Change a zone instance's capacity for the rest of the game (Pokémon's "Expand bench" to 8). Set exactly one of delta and set. The result is stored in the side (or shared) state's capacities and honoured by every move; it never drops below 0 and never evicts cards already there. delta on a zone without a capacity does nothing. New game resets it.

PropertyTypeDescription
zonePlaytestValue<string>Zone id.
delta?PlaytestValue<number>Amount to add to the current capacity.
set?PlaytestValue<number>Absolute capacity to set.

kind: "forEachSide" ​

A block step: runs steps once per side in play (player first), each time with that side as the acting side. Side zones, side trackers and { tracker } refs resolve against the side being run; the action's targets and params are unchanged. Steps on Shared trackers belong outside the block so they run once: a Game-target "Next round" readies and draws for both sides inside the block and increments a shared round counter after it.

Block steps do not nest, and setup (which already runs once per side) may not use forEachSide.

PropertyTypeDescription
stepsPlaytestStep[]Primitive steps to run per side.

kind: "repeatUntil" ​

A block step: while until is false, runs steps again, at most maxIterations times (a Pokémon mulligan: shuffle the hand back and redraw until it holds a Basic). until is checked before each pass, so a condition that already holds runs nothing. Each pass consumes the seeded RNG, so redo reproduces it, and logs its 1-based iteration.

until has no card to test, so it may only combine zoneHas leaves (with all / any / not). Block steps do not nest.

PropertyTypeDescription
untilPlaytestPredicateStops the loop once true; resolved against the acting side.
stepsPlaytestStep[]Primitive steps run on each pass.
maxIterationsnumberUpper bound on passes, at most PLAYTEST_MAX_REPEAT_ITERATIONS.

kind: "create" ​

Create new card instances (a copy of the target, a picked associated card, or a fixed code). New instances carry created: true.

PropertyTypeDescription
card"target" | PlaytestValue<string>The card to create: "target" copies each target's card code; otherwise a literal card code or { param } (usually a Card param).
to?PlaytestValue<string>Destination zone id. Omitted: each target's own zone (required with no card target).
position?PlaytestZonePositionWhere the cards go in the destination. Defaults to Top; Index is not allowed.
count?PlaytestValue<number>Copies to create: per target when copying "target" or when to is omitted, else once. Defaults to 1, at most PLAYTEST_MAX_CREATE_COUNT.
faceDown?booleanFace state. Omitted uses the destination's defaultFaceDown.

kind: "transform" ​

Change each target's card code in place (e.g. a champion levelling up). Zone, position, counters, flags and attachments are kept.

PropertyTypeDescription
cardPlaytestValue<string>The new card code: a literal or { param } (usually a Card param).

kind: "remove" ​

Remove created cards (created: true) from the game; other cards are ignored.

PropertyTypeDescription
cards?PlaytestCardSelectorCards to remove. Omitted removes the action's targets.

Predicates ​

Predicates are small trees of plain objects that answer yes or no about a card. They decide which cards a zone accepts, when an action shows up (when), which cards a selector picks (where), and when a repeatUntil loop stops (until).

js
// A Pokémon without any damage.
const healthyPokemon = {
  kind: "all",
  all: [
    { kind: "tag", tag: "pokemon" },
    { kind: "not", not: { kind: "counterAtLeast", marker: "damage", n: 1 } },
  ],
};

A tag tests the card code, so a copy matches whatever its original matches. To tell copies and tokens apart from deck cards, use { kind: "created" }, for example as the when of an action that removes them.

A declarative boolean test over one card, discriminated by kind. Used by zone accepts, action when and card selectors' where, and (with zoneHas leaves only) by repeatUntil.

kindDescription
"tag"True when the card's code carries this tag in the definition's cardTags.
"zone"True when the card is currently in this zone.
"faceDown"True when the card's face state equals faceDown.
"rotated"True when the card's rotated state (any rotation but 0) equals rotated.
"counterAtLeast"True when the card holds at least n of a marker.
"flag"True when the card carries this flag.
"created"True when a create step made the card (created: true: a copy, token or created card), false for cards dealt from a deck.
"zoneHas"True when a zone holds at least atLeast cards matching where. It tests the table, not the card being checked: the zone resolves against the acting side (a card check with no acting side uses the card's side). This is the only leaf a repeatUntil condition may use.
"all"True when every child is true (an empty list is true).
"any"True when at least one child is true (an empty list is false).
"not"True when the child is false.

kind: "tag" ​

True when the card's code carries this tag in the definition's cardTags.

PropertyTypeDescription
tagstringTag name.

kind: "zone" ​

True when the card is currently in this zone.

PropertyTypeDescription
zonestringZone id.

kind: "faceDown" ​

True when the card's face state equals faceDown.

PropertyTypeDescription
faceDownbooleanThe face state to match.

kind: "rotated" ​

True when the card's rotated state (any rotation but 0) equals rotated.

PropertyTypeDescription
rotatedbooleanThe rotated state to match.

kind: "counterAtLeast" ​

True when the card holds at least n of a marker.

PropertyTypeDescription
markerstringMarker id.
nnumberMinimum count.

kind: "flag" ​

True when the card carries this flag.

PropertyTypeDescription
flagstringId of a flag in the definition's flags.

kind: "created" ​

True when a create step made the card (created: true: a copy, token or created card), false for cards dealt from a deck.

PropertyTypeDescription

kind: "zoneHas" ​

True when a zone holds at least atLeast cards matching where. It tests the table, not the card being checked: the zone resolves against the acting side (a card check with no acting side uses the card's side). This is the only leaf a repeatUntil condition may use.

PropertyTypeDescription
zonestringZone id.
where?PlaytestPredicateOnly cards matching this count. Omitted counts every card.
atLeast?numberMinimum matching cards. Defaults to 1.

kind: "all" ​

True when every child is true (an empty list is true).

PropertyTypeDescription
allPlaytestPredicate[]Child predicates.

kind: "any" ​

True when at least one child is true (an empty list is false).

PropertyTypeDescription
anyPlaytestPredicate[]Child predicates.

kind: "not" ​

True when the child is false.

PropertyTypeDescription
notPlaytestPredicateThe negated predicate.

Shortcuts ​

An action's shortcut is a key the player can press instead of clicking. A card or selection action runs on the selected cards, or on the card under the pointer when nothing is selected. A zone action runs on the zone under the pointer, or on the first zone in its zones list. A side or game action runs for you.

Two actions may share a key only when they can never apply to the same thing: a card action and a zone action can share a key, and two card actions (or two zone actions) can share one when their zones lists do not overlap. Side and game actions all share one scope, so their keys must be unique. When a card action and a zone action share a key, the card under the pointer wins.

Grammar ​

A shortcut is one key, optionally after mod+ and/or shift+: [mod+][shift+]<key>. mod is Cmd on macOS and Ctrl everywhere else. Letters are case-insensitive, and modifiers may come in any order.

Keys match the physical key pressed (KeyboardEvent.code), not the character it types, so a shortcut works the same on every keyboard layout and with any modifier held.

KeysTokens
Lettersa to z
Digits0 to 9
Digit range1-9
Named keysspace, enter, backspace, delete, arrowup, arrowdown, arrowleft, arrowright
Punctuation- = [ ] ; ' , . / ` \

Alt is the opponent ​

Alt is never part of a script shortcut. Holding Alt with any shortcut or click runs the same input on the opponent's side (in Versus). The table adds that for free, so a script declares each action once, for the acting side. Any shortcut containing alt, option or opt is rejected with shortcut_uses_alt.

Reserved keys ​

The table owns these keys, so a script cannot bind them (shortcut_reserved):

KeyUsed for
mod+zUndo
mod+shift+zRedo
mod+yRedo
?Open the shortcut sheet
escapeClear the selection

Examples ​

ShortcutResultNotes
"d"Binds dThe D key.
"shift+d"Binds shift+dShift and D.
"mod+d"Binds mod+dCmd+D on macOS, Ctrl+D elsewhere.
"Shift+Mod+D"Binds mod+shift+dSame as mod+shift+d: case and modifier order don't matter.
"1-9"Binds 1-9Every digit key; the pressed digit fills the action's first number param.
"alt+d"Rejected: shortcut_uses_altAlt is reserved for the opponent side.
"option+d"Rejected: shortcut_uses_altOption is Alt on macOS.
"ctrl+d"Rejected: invalid_shortcutWrite mod, never ctrl or cmd.
"mod+z"Rejected: shortcut_reservedUndo belongs to the table.
"shift+/"Rejected: shortcut_reservedThe same physical keys as ?.

How actions run ​

  • Every action is one undo step. However many steps an action has, it runs as a single unit: one press of undo reverses all of it. A drag and drop is one undo step too.
  • Randomness is seeded. Shuffles, random picks and dice rolls draw from a seed stored in the game. Undo then redo reproduces the same shuffle, and New random seed in the table menu is the only way to re-roll.
  • Nothing enforces the game's rules. Steps do exactly what they say. The only checks are the ones your definition declares: a zone's accepts, its capacity, and an action's zones and when. A card a move cannot place (a full zone, or a card the zone does not accept) stays where it was and the log says so.
  • A value can come from a param or a tracker. Anywhere a step field is a PlaytestValue, you can write { param: "count" } to use a value the player typed for the action, or { tracker: "mana" } to use a tracker's current value.
  • Alt means the opponent. You never write an opponent version of an action. The same click or key with Alt held runs it for the opponent's side.

Limits ​

Hard caps on a playtest script's PlaytestDefinition. Output past a cap is rejected, never truncated: a partial table is worse than an error.

CapLimitApplies to
maxZones40Zones in zones.
maxActions150Actions in actions.
maxStepsPerAction32Steps in one action's steps, counting the steps inside block steps.
maxSetupSteps64Steps in setup, counting the steps inside block steps.
maxRepeatIterations20A repeatUntil step's maxIterations.
maxMarkers24Markers in markers.
maxTrackers24Trackers in trackers.
maxFlags24Flags in flags.
maxParamsPerAction8Params in one action's params.
maxParamOptions32Options in one choice param.
maxCardInstances500Card instances across every initialZones list (one side's deck).
maxTaggedCards2000Card codes in cardTags.
maxTagsPerCard24Tags on one card code.
maxAssociatedCards2000Card codes in associatedCards.
maxAssociatedPerCard48Associated card codes listed for one card code.
maxCreateCount20A create step's literal count (the engine also clamps to it).
maxPredicateDepth8Nesting depth of one predicate tree.
maxPredicateNodes64Nodes in one predicate tree.
maxTableColumns24table.columns.
maxTableRows12table.rows.
maxSharedRows6table.sharedRows.
maxIdLength64Characters in an id or reference (zone, action, tracker, marker, param, tag).
maxCardCodeLength128Characters in a card code.
maxLabelLength200Characters in a label, label key, group or color.
maxLogMessageLength500Characters in a log step's message.
maxDescriptionLength500Characters in an action's description.

At most 50 issues are reported per run.

Time limit: a script that runs longer than 5 seconds is stopped and the table is not built (script_timeout).

Issue codes ​

A script that fails, or returns a definition that does not fit the shapes above, is rejected with one or more issues. The editor's Validation panel lists them as you type. The troubleshooting section of the guide explains how to fix each one.

CodeShown in the appMeaning
script_unsafeThe rules script uses code that isn't allowed.The static safety gate rejected the source (metadata.safetyCode).
script_errorThe rules script failed to run.The script threw, or did not default-export a function.
invalid_shapeThe rules script returned a table setup with a missing or invalid value.A field is missing, has the wrong type, or holds an unknown value.
unsupported_versionThe rules script returned an unsupported version ({version}).version is not 1.
over_capThe rules script returned more than the allowed {limit}.A list, record, string or number is over its PLAYTEST_DEFINITION_CAPS entry.
invalid_idThe rules script used an invalid id.An id or record key is empty, malformed or an Object.prototype name.
duplicate_zone_idZone "{id}" is declared more than once.Two zones share an id.
duplicate_action_idAction "{id}" is declared more than once.Two actions share an id.
duplicate_tracker_idTracker "{id}" is declared more than once.Two trackers share an id.
duplicate_marker_idMarker "{id}" is declared more than once.Two markers share an id.
duplicate_param_idOption "{id}" is declared more than once.Two params share an id.
duplicate_flag_idFlag "{id}" is declared more than once.Two flags share an id.
unknown_zoneThe rules script refers to an unknown zone, "{zone}".A step, predicate, action, param option or initialZones key names an undeclared zone.
unknown_actionThe rules script refers to an unknown action, "{action}".primaryActionId / dropActionId / roundActionId names an undeclared action.
invalid_round_actionThe Turn button action "{action}" must act on a side or the whole game.roundActionId names an action whose target is not game or side.
unknown_trackerThe rules script refers to an unknown tracker, "{tracker}".A tracker step or a { tracker } value names an undeclared tracker.
unknown_flagThe rules script refers to an unknown flag, "{flag}".A flag / clearFlag step, readyAll.skipFlag or flag predicate names an undeclared flag.
invalid_tracker_refTracker "{tracker}" can't be read from the "{side}" side.A { tracker } value's side does not fit the tracker (shared on a side tracker, or self / other on a shared one).
invalid_tracker_toggleTracker "{tracker}" can only be toggled if it runs from 0 to 1.A tracker step toggles a tracker that is not declared min: 0, max: 1.
nested_block_stepA "{kind}" step can't sit inside another forEachSide or repeatUntil step.A block step (forEachSide, repeatUntil) sits inside another block step.
for_each_side_in_setupSetup already runs once for each side, so it can't use forEachSide.setup uses forEachSide; setup already runs once per side.
condition_needs_zone_hasA repeatUntil condition can only check zones with zoneHas, not "{kind}".A repeatUntil condition tests a card; it may only combine zoneHas leaves.
unknown_markerThe rules script refers to an unknown marker, "{marker}".A counter step or counterAtLeast predicate names an undeclared marker.
unknown_paramThe rules script refers to an unknown option, "{param}".A { param } reference names a param the action does not declare (setup has none).
param_kind_mismatchOption "{param}" can't supply the kind of value used here.A { param } reference's param cannot supply the value type the field needs.
zone_outside_tableZone "{zone}" extends past the edge of the table.A zone's area extends past its grid (table for side and playerGrid zones, the shared strip for other shared ones).
zone_overlapZones "{zone}" and "{otherZone}" overlap on the table.Two zones on the same grid cover the same cell (a playerGrid shared zone sits on the side grid).
invalid_shortcutThe rules script has an invalid keyboard shortcut.A shortcut does not follow the grammar ([mod+][shift+]<key>).
shortcut_uses_altShortcut "{shortcut}" uses Alt, which is reserved for the opponent's side.A shortcut uses alt, which is reserved for acting on the opponent side.
shortcut_reservedShortcut "{shortcut}" is reserved by the playtest table.A shortcut shadows an engine key (PLAYTEST_RESERVED_SHORTCUTS).
shortcut_conflictShortcut "{shortcut}" is bound to more than one action.Two actions in the same target scope share a shortcut.
card_param_needs_sourceCard option "{param}" needs a cardSource to pick cards from.A card param has no cardSource, so it has nothing to pick from.
card_source_needs_tagA card option can only filter cards by tag, not by "{kind}".A cardSource.where tests something other than tags; it may only combine tag leaves.
create_needs_card_targetA create step needs a destination zone, or an action that runs on a card.A create step without to, or copying "target", sits outside a card / selection action, so it has no target card.
script_timeoutThe rules script took too long to run. Check it for an endless loop.The script ran past its budget (almost always an endless loop).
worker_failedThe rules script could not be run. Try reloading the page.The worker crashed, never started, or could not receive the request.

Each issue also carries a path (for example actions[2].shortcut) and an English message for script authors. The editor's Validation panel shows both.

Examples: the default rules ​

Every launched game with a playtest table ships a default rules script, and they are ordinary playtest scripts. Open one to read its full source, then use Fork in Settings to start your own from it.

GameRulesSource
Cyberpunk TCGStandardRead the script
Flesh and BloodStandardRead the script
HearthstoneStandardRead the script
Legends of RuneterraStandardRead the script
Magic: The GatheringStandardRead the script
Magic: The GatheringCommanderRead the script
Palworld TCGStandard gameRead the script
Pokémon TCGStandardRead the script
RiftboundStandardRead the script

Turny.gg documentation