# Turny.gg Docs > Documentation for Turny.gg: custom rulesets, calculators, card search, tournaments and the deck builder. --- url: https://docs.turny.gg/ description: "Documentation for Turny.gg, the multi-game tournament platform. Custom rulesets, calculators, card search, tournaments and the deck builder." --- # Turny.gg Docs Documentation for Turny.gg, the multi-game tournament platform. Custom rulesets, calculators, card search, tournaments and the deck builder. - [Custom rulesets](https://docs.turny.gg/guide/rulesets): Write deck and deck-set rules in JavaScript and run them on every registration. - [Calculators](https://docs.turny.gg/guide/calculators): Turn any deck into odds, curves and stats with the no-code builder or a script. - [Script reference](https://docs.turny.gg/reference/scripting/rulesets): Every argument, return value and sandbox rule your ruleset and calculator scripts can use. - [Tournaments](https://docs.turny.gg/guide/tournaments): Formats, pairings, standings and tiebreakers, with worked examples checked against the engine. - [Deck builder](https://docs.turny.gg/guide/deck-builder): Deck codes and list formats for every game, piles, deck sets and templates. - [Card search](https://docs.turny.gg/reference/search/lor): Find exactly the cards you want with each game's fields, operators and shortcuts.

Every page in plain text

Add `.md` to any page's URL for a plain markdown copy, handy for reading offline or pasting into another tool. The whole site is also bundled as one text file.

--- url: https://docs.turny.gg/guide/ description: "Step-by-step guides for Turny.gg's custom rulesets, calculators, playtest, tournaments, series, communities and deck builder." --- # Guides Guides walk through a feature from start to finish. For the exact shape of every script argument and card field, see the [reference](https://docs.turny.gg/reference/). - [Custom rulesets](https://docs.turny.gg/guide/rulesets): write deck and deck-set rules in JavaScript. - [Calculators](https://docs.turny.gg/guide/calculators): build deck stats with the no-code builder or a script. - [Playtest](https://docs.turny.gg/guide/playtest): play a deck out on a virtual table, and write and share the rules that set it up. - [Tournaments](https://docs.turny.gg/guide/tournaments): formats, pairings, standings, tiebreakers and recurring events. - [Series](https://docs.turny.gg/guide/series): seasons of tournaments with a running points table, for players and organizers. - [Communities](https://docs.turny.gg/guide/communities): one page for a store, play group or team, its staff, and the events it hosts. - [Deck builder](https://docs.turny.gg/guide/deck-builder): deck codes, imports, piles and templates. --- url: https://docs.turny.gg/guide/rulesets description: "Write a custom ruleset: card, deck and deck set rules in JavaScript, from a first ban list to pool filters, sharing and troubleshooting." --- # Custom rulesets A custom ruleset is a short JavaScript function that decides whether a card, a deck or a whole lineup is legal. Turny.gg runs it in the deck builder while players build, and again on the server when a deck is submitted to a tournament. If your community plays a format the built-in rules don't cover, a ruleset is how you enforce it. This guide explains when to use each kind of rule, walks through writing your first one, and covers sharing and troubleshooting. You need a Turny.gg account and a little JavaScript. For the exact contract (every argument, return value and limit), see the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [script sandbox](https://docs.turny.gg/reference/scripting/sandbox). ## What a ruleset is Every ruleset has a **scope**, which decides what it looks at and when it runs: | Scope | Runs | Use it for | | ------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | Card rule | Once per card | Which cards are legal at all: sets, formats, rarities, a ban list. In the deck builder it also hides illegal cards. | | Deck rule | Once per deck | Anything about a single deck: deck size, copy limits, champion limits, bans that depend on how many copies. | | Deck set rule | Once per lineup, with every deck the player brings | Anything that compares decks: no shared champions, no repeated region pairs, one deck per archetype. | Pick the smallest scope that can answer the question. "Is this card allowed?" is a card rule. "Is this deck allowed?" is a deck rule. Only reach for a deck set rule when the answer depends on more than one deck. A tournament always uses exactly one rule of each scope, and so does the deck builder. Each game ships built-in rules (for Legends of Runeterra, for example: the Standard and Eternal card rules, the Riot constructed deck rule and the Riot lock deck set rule). ::: warning Your rule replaces the built-in one Choosing a custom rule for a scope replaces the built-in rule for that scope; it does not add to it. If your deck rule doesn't check deck size, nothing does. The quickest start is often to **Duplicate** a built-in ruleset and edit the copy. ::: ::: tip Just banning cards? Every card rule has a **Direct bans** picker, in every game. Pick cards from a list and they are banned on top of whatever the script allows, no code needed. ::: ## Create a ruleset and use it Rulesets belong to a game, so create them on that game's site: [Legends of Runeterra](https://lor.turny.gg/settings/custom-rulesets), [Pokémon TCG](https://pokemon.turny.gg/settings/custom-rulesets) or [Riftbound](https://riftbound.turny.gg/settings/custom-rulesets). 1. Open **Settings → Custom rulesets** and click **New ruleset**. 2. Enter a **Ruleset name** and pick a **Rule scope**. The **Source code** editor fills in a starter function for that scope. 3. Write your rule, then click **Create**. The script is checked for [unsafe code](https://docs.turny.gg/reference/scripting/sandbox) when you save, and an unsafe script cannot be saved. The list shows your rulesets next to the built-in ones. Built-in and downloaded rulesets are read-only, but you can **View code** or **Duplicate** them. The switch next to each ruleset hides it from every rule picker and legality check without deleting it. **Script API** opens the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) reference in a new tab, and the **Card fields** link under each code editor opens the card data reference for the current game. Your enabled rulesets then show up wherever rules are chosen: - **Deck builder:** deck rules in the rules dropdown above the deck, card rules in the **Card ruleset** filter, and deck set rules in **Multi Pile** mode. - **Tournament create:** the **Deck settings** section has one dropdown per scope (**Deck sets**, **Decks**, **Cards**). **View Decks code** (and its siblings) shows the selected script, read-only. ::: info Tournaments keep a copy When you save a tournament, it stores a copy of each selected script. Editing the ruleset later does not change tournaments that already use it. To move a tournament to your latest version, open it (**Administration → Edit tournament**) and save it again: the form reloads the current code of every saved ruleset it uses. ::: ## Tutorial: your first ruleset This tutorial builds a small Legends of Runeterra format called **Two-of Standard**: at most two copies of any card, two banned cards, and no champion shared between a player's decks. Every step works the same way in the other games; only the card fields change (see the card data pages for [Cyberpunk TCG](https://docs.turny.gg/reference/card-data/cyberpunk), [Flesh and Blood](https://docs.turny.gg/reference/card-data/fab), [Hearthstone](https://docs.turny.gg/reference/card-data/hs), [Legends of Runeterra](https://docs.turny.gg/reference/card-data/lor), [Palworld TCG](https://docs.turny.gg/reference/card-data/palworld), [Pokémon](https://docs.turny.gg/reference/card-data/pokemon) and [Riftbound](https://docs.turny.gg/reference/card-data/riftbound)). ### 1. Write a deck rule Go to [**Settings → Custom rulesets**](https://lor.turny.gg/settings/custom-rulesets), click **New ruleset**, name it `Two-of Standard`, set **Rule scope** to **Deck rule**, and replace the starter code with: ```js // Deck rule: "Two-of Standard". const BANNED = ["01IO049", "01SI001"]; // Deny, Vengeance const MAX_COPIES = 2; const DECK_SIZE = 40; export default function validateDeck(deck, cardsById) { const issues = []; let total = 0; for (const [ref, copies] of Object.entries(deck)) { const name = cardsById[ref]?.name ?? ref; total += copies; if (BANNED.includes(ref)) { issues.push({ code: "banned_card", message: `${name} is banned.` }); } if (copies > MAX_COPIES) { issues.push({ code: "copy_limit", message: `${name}: at most ${MAX_COPIES} copies (found ${copies}).`, }); } } if (total !== DECK_SIZE) { issues.push({ code: "deck_size", message: `Decks need exactly ${DECK_SIZE} cards (found ${total}).`, }); } return { valid: issues.length === 0, issues }; } ``` What it does: - `deck` maps each card's ref to its number of copies (`{ "01IO009": 3 }`). For Legends of Runeterra the ref is the card code. - `cardsById` holds the catalog entry for every card in the deck, so `cardsById[ref].name` is the card's name. The `?.` guards against a ref the catalog doesn't know. - It collects **every** problem instead of stopping at the first, then returns `valid` plus the list. - It checks the deck size because this rule replaces the built-in deck rule, which used to check it. Click **Create**. ### 2. Try it in the deck builder Open the [**Deck Builder**](https://lor.turny.gg/deck-builder) and pick **Two-of Standard** in the rules dropdown above the deck. Paste this deck code into **Import deck code** and click **Import**: ```text CEAQCAICBEAREAICAUDAQDAQCEJBKFY2DMOCIJRKFQYTEAIBAEBDI ``` It is 40 Ionia cards with three copies of Zed and two copies of Deny. A warning icon appears next to the card count; hover it to see your messages: - Zed: at most 2 copies (found 3). - Deny is banned. The deck uses cards that are no longer in Standard, so the builder's default **Standard** card rule adds "Only Standard-legal cards can be submitted" lines too. Switch the **Card ruleset** filter to **Eternal** to see only your rule's issues. ### 3. Add a deck set rule Formats with several decks per player usually need a rule across the lineup. Create a second ruleset named `No shared champions`, with **Rule scope** set to **Deck set rule**: ```js // Deck set rule: "No shared champions". export default function validateDeckset(decks, cardsById) { const firstDeckByChampion = new Map(); const issues = []; decks.forEach((deck, index) => { const deckNumber = index + 1; for (const ref of Object.keys(deck)) { const card = cardsById[ref]; if (card?.game?.supertypeRef !== "Champion") { continue; } const firstDeck = firstDeckByChampion.get(ref); if (firstDeck === undefined) { firstDeckByChampion.set(ref, deckNumber); } else { issues.push({ code: "shared_champion", message: `${card.name} is in deck ${firstDeck} and deck ${deckNumber}.`, }); } } }); return { valid: issues.length === 0, issues }; } ``` `decks` is an array with one deck per entry, in the same shape as the deck rule's `deck`. Champions are found through `card.game.supertypeRef`, which is `"Champion"` in every language (the plain `supertype` is translated, so don't compare against it). To try it, click **Multi Pile** in the deck builder, pick **No shared champions** in the deck set dropdown, click **Add deck** for a second deck, and import one of these codes into each deck (both run two copies of Zed): ```text CEAACFABAICQMCAJBQIBCEQVC4NBWHBEEYVCYMRUGUAA CEAAEAIBAIERGAIEAEBAGBAFAYDQUDANBYHRAEISCMKBKFYA ``` The lineup warning reads "Zed is in deck 1 and deck 2." This rule replaces the built-in Riot lock deck set rule, so the lineup is no longer checked for repeated region pairs. Add that check here if your format needs it. The number of decks a player brings is a stage setting (**Decks to bring**), not part of the ruleset. ### 4. Attach it to a tournament 1. Go to [**Tournaments → Create tournament**](https://lor.turny.gg/tournaments/create) and fill in the basics. 2. In **Deck settings**, set **Deck sets** to `No shared champions`, **Decks** to `Two-of Standard` and **Cards** to `Eternal`. 3. Click **Save as draft** (or create the tournament). The tournament's **Rules** tab now lists both scripts under **Deck rules**, marked **Unverified code** because they are yours rather than built in. Its **Deck Builder** button opens the builder with exactly this tournament's rules, which is the fastest way to check a deck against them. When players submit decks, the server runs the same three rules again and rejects a lineup that fails any of them. ## Reporting good errors Players only see what your rule returns, so the messages are the user interface of your format. - **Return every issue, with a `message`.** The message is shown to the player as written. `code` is a stable, machine-readable id (`copy_limit`, `banned_card`); it is shown only when there is no message, with underscores turned into spaces. - **Name the card and the numbers.** "Zed: at most 2 copies (found 3)." tells the player exactly what to change; "Deck is illegal." does not. - **Don't return a bare `false`.** It fails with a generic fallback ("Saved deck rule rejected this deck.") that doesn't say why. - **Don't number decks in a deck rule.** On submission the server already prefixes each issue with where it came from (`Deck 2: …`, `Lineup: …`, `Card : …`). A deck set rule, which sees every deck at once, should name the decks itself, as the tutorial does. - **Don't throw.** A thrown error is shown as an error instead of your issues, and the script can't create an `Error` object anyway. Return `{ valid: false, issues }` instead. A deck rule written this way reads like a checklist: ```js // Every problem at once, each with a code and a message. export default function validateDeck(deck, cardsById) { const issues = []; const refs = Object.keys(deck); if (refs.length < 10) { issues.push({ code: "too_few_cards", message: `Use at least 10 different cards (found ${refs.length}).`, }); } for (const ref of refs) { if (!cardsById[ref]) { issues.push({ code: "unknown_card", message: `Unknown card ${ref}.` }); } } return { valid: issues.length === 0, issues }; } ``` The full list of accepted return values is on the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets#return-values) page. ## Pool filters A deck rule can also help players build: an optional `resolvePoolFilters` export sets the deck builder's card filters for the deck being edited. The Riftbound built-in rules use it to show only the domains of the Legend you picked. It never runs on submission and never changes whether a deck is legal. Add this below `validateDeck` in the tutorial's deck rule. Once the deck has cards from exactly two regions, the builder's card pool narrows to those two regions: ```js // Builder only: once the deck has two regions, filter the pool to them. export function resolvePoolFilters(input) { const pile = input.lineup.find( (entry) => entry.pileId === input.activePileId, ); if (!pile) { return null; } const regions = new Set(); for (const ref of Object.keys(pile.cards)) { for (const region of input.cardsById[ref]?.game?.regionRefs ?? []) { // Skip Runeterra champion codes such as "06RU006". if (!/^\d/.test(region)) { regions.add(region); } } } return regions.size === 2 ? { regionRefs: [...regions] } : null; } ``` Import the second deck code from step 3 (Zed plus Piltover & Zaun cards) with this rule selected and the card pool switches to Ionia and Piltover & Zaun. How the builder treats the answer: - **It suggests, it doesn't lock.** The player can change the filters afterwards. The builder only reapplies your suggestion when it changes (a card changes the deck's regions) or when the player switches to another deck. - **Return only the filters you mean to set.** A key you leave out keeps the player's current value. `[]` clears that filter. `null` changes nothing. - **Use the game's filter keys and values.** A key the builder doesn't know is dropped silently, so a typo does nothing. The list filters are: | Game | Keys | | -------------------- | ---------------------------------------------------------------------- | | Legends of Runeterra | `regionRefs`, `typeRefs`, `rarityRefs`, `setCodes`, `keywordVocabRefs` | | Pokémon TCG | `cardTypes`, `types`, `stages`, `rarities`, `setCodes` | | Riftbound | `cardTypes`, `domains`, `rarities`, `sets`, `supertypes`, `tags` | Values are the same refs the cards carry: `"Ionia"` and `"PiltoverZaun"` for regions, lowercase `"unit"` for a Riftbound card type. - **It sees the whole lineup.** `input.lineup` has every deck (pile) in the builder, so a rule can read another pile, such as the Legend pile in Riftbound. Only deck rules are asked; card and deck set rules never are. - **Watch for extra refs.** In Legends of Runeterra some cards also list a Runeterra champion's card code (such as `"06RU006"`) in `regionRefs`, next to their real region. That is why the example skips refs that start with a digit. The input fields are listed under [`resolvePoolFilters`](https://docs.turny.gg/reference/scripting/rulesets#resolvepoolfilters) in the reference. ## Sharing rulesets ### Public and private New rulesets are private: only you can see them. Tick **Make public** in the create or edit dialog to share one. A public ruleset appears on the **Rulesets** tab of your profile, grouped into deck set, deck and card rules, where anyone can read its code. Untick it to take it off your profile; copies other players already saved keep working. ### Saving someone else's ruleset There are two places to pick up another player's ruleset: - **A profile's Rulesets tab:** **Save to my account** adds a copy to your custom rulesets, and **Open in deck builder** tries it without saving. - **A tournament's Rules tab:** **Add to saved rulesets** next to each custom rule adds a copy of the exact version that tournament uses. A saved copy is marked **Downloaded**. It is read-only: you can view its code, **Duplicate** it into an editable ruleset of your own, or **Remove** it from your account, which leaves the original untouched. ::: warning Read before you save Custom rules are code written by other players, and Turny.gg does not review it (the Rules tab labels it **Unverified code**). The [sandbox](https://docs.turny.gg/reference/scripting/sandbox) keeps a script away from your account and the page, but a rule can still be wrong or unfair. Read it first. ::: ### Pinned copies and updates A downloaded copy is pinned to the version you saved. When the author edits their ruleset, your copy keeps running the code you saved; nothing changes until you choose to update. That way a rule can't change under a tournament or a deck you already checked. When a copy saved from a tournament's Rules tab falls behind the author's latest version, it shows **Update available** in your custom rulesets. Click **Update** to switch it to the latest version; the copy also takes the author's current name. Copies saved from a profile don't show updates yet: save the ruleset again from the author's profile to get the newest version. ## Troubleshooting ### "This ruleset script uses APIs or syntax that are not allowed." The safety check rejected the script when you saved it. The message doesn't say which line, so look for the usual causes: | You wrote | Write instead | | ----------------------------------- | ------------------------------------------------------------- | | `var total = 0` | `let total = 0` or `const` | | `console.log(…)` | Remove it, or report the value as an issue while debugging | | `throw new Error("…")` | `return { valid: false, issues: ["…"] }` | | `parseInt(x)` | `Number.parseInt(x, 10)` | | `async` / `await`, classes, `this` | Plain synchronous functions | | `import …` or a second named export | One default export (plus `resolvePoolFilters` in a deck rule) | | `delete obj.key` | Build a new object without the key | ```js // Rejected: variable_kind_unsupported, unsafe_global. export default function validateDeck(deck) { var total = 0; console.log(deck); return total === 0; } ``` The [script sandbox](https://docs.turny.gg/reference/scripting/sandbox) lists everything the check allows and every issue code. ### Every deck fails with "Saved deck rule rejected this deck." Your function returned something that isn't a pass: `false`, `undefined` (a missing `return`), or a result object with no `valid: true`. Return `true` or `{ valid: true }` for a legal deck. See [return values](https://docs.turny.gg/reference/scripting/rulesets#return-values). ### The builder shows an error instead of issues The script threw while it ran. The most common cause is reading a field of a card that isn't there, like `cardsById[ref].game.cost` when the ref is unknown. Guard with `?.` and `??`. Writing to the arguments throws too, since they are frozen: build new objects (`{ ...deck }`) instead of changing `deck`. ### It's slow, or stops with a timeout Each check has a time limit (see [time limits](https://docs.turny.gg/reference/scripting/sandbox#time-limits)). A card rule runs once for every card in the catalog when the builder filters the pool, so keep per-card work small and avoid loops inside loops over the whole deck. ### My ruleset isn't in the dropdown Check that it is switched on in **Settings → Custom rulesets** ([Legends of Runeterra](https://lor.turny.gg/settings/custom-rulesets), [Pokémon TCG](https://pokemon.turny.gg/settings/custom-rulesets), [Riftbound](https://riftbound.turny.gg/settings/custom-rulesets)), that it has the scope that dropdown asks for, and that you're on the site of the game you created it for. ### A tournament still runs my old code Tournaments keep the version they were saved with. Edit the tournament and save it to pick up your latest version (see [Create a ruleset and use it](#create-a-ruleset-and-use-it)). ### "Run rules without the sandbox…" Your browser couldn't start the sandbox that runs rule scripts, so the builder can't check legality and saving is disabled. The builder then offers to run deck rules directly in the page instead, with no isolation. It is an explicit opt-in: it applies only to that browser, expires after 30 days, and never affects the server, which always checks submissions in its own sandbox. Only accept it if you trust the rules you use. --- url: https://docs.turny.gg/guide/calculators description: "Build deck calculators with the no-code builder or a compute script, and share them." --- # Calculators A calculator turns a deck into a small stats dashboard: a curve, a type breakdown, opening-hand odds, whatever numbers you care about. Every launched game ships with a ready-made one, and you can build your own in two ways: - **The no-code builder.** Pick widgets from a palette, choose what they measure from your game's card fields, and watch a live preview. - **Code.** Every builder calculator is a short JavaScript function underneath. Open it as code to go past what the builder can do, or write one from scratch. This guide walks through both. For the exact shape of every argument and widget field, see the [calculator script API](https://docs.turny.gg/reference/scripting/calculators). ## Where calculators show up Look for the **Calculators** button (a calculator icon) on any deck: - in the deck builder, next to the deck's other actions, - on a deck page and in the deck preview dialog, - in the action menu of your saved decks. It opens a dialog with a **Calculator** picker at the top. The picker has two groups: **Defaults** (the calculators Turny.gg ships for the game) and **Your calculators** (the ones you made or saved). Pick one and it runs over the deck in front of you. A deck set is counted as one combined deck. Side deck and maybeboard piles are left out; where a deck page offers an **Include sideboard** switch, it adds the sideboard back. In Riftbound, a calculator with a **Draw odds** widget runs over the cards you draw from: the Chosen Champion starts in its own zone, so a 40-card Main Deck gives odds over 39 cards. Runes, the Legend and Battlefields are passed in too, so check `card.game.type` (`rune`, `legend`, `battlefield`) to leave them out of main-deck counts. You manage calculators in **Settings → Calculators** on each game's site: [Legends of Runeterra](https://lor.turny.gg/settings/custom-calculators), [Pokémon TCG](https://pokemon.turny.gg/settings/custom-calculators) or [Riftbound](https://riftbound.turny.gg/settings/custom-calculators). Calculators belong to one game, so the list shows only that game's calculators. From there you can: - switch any calculator on or off; a switched-off calculator is hidden from the picker (it says "Hidden from deck views"), - **View code** of any calculator, including the defaults, - **Duplicate** any calculator into an editable copy of your own, - **Edit** or **Delete** calculators you made. Default calculators are read-only. To change one, duplicate it and edit the copy. ## The default dashboards Every launched game has one default calculator, called **Deck breakdown**. It is on for everyone until you switch it off. | Game | What Deck breakdown shows | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Legends of Runeterra | Mana curve, card types (champions, followers, spells, landmarks, equipment), rarity, regions, average cost, and a units to spells ratio. | | Pokémon TCG | Pokémon / Trainer / Energy breakdown, energy types, mulligan chance, an **Opening Hand Starters** table (the odds each Basic Pokémon starts, and the odds it is your only Basic), retreat cost, and regulation marks. | | Riftbound | Energy curve, domains, card types, average energy, and a unit / spell / gear split. | The defaults are ordinary calculator scripts, and their full source is on the [calculator script API](https://docs.turny.gg/reference/scripting/calculators#examples-the-default-calculators) page. They make good starting points: **Duplicate** one and edit the copy. ## Tutorial: build a dashboard without code This tutorial builds a Pokémon TCG calculator called **Starter check** with two widgets: a retreat cost curve for your Pokémon, and a table of opening-hand starter odds for every Basic Pokémon. The same steps work in every game; only the field names change. ### 1. Start a new calculator 1. Go to [pokemon.turny.gg](https://pokemon.turny.gg) and sign in. 2. Open [**Settings → Calculators**](https://pokemon.turny.gg/settings/custom-calculators) and click **New calculator**. 3. Type `Starter check` in **Calculator name**. The dialog has three parts: - **Sample deck** at the top: the deck the preview runs on. It starts as a popular deck for the game. Click **Change deck** and paste a deck code or deck list to preview against your own deck instead; **Reset to sample** switches back. - **Add a widget**: the palette, with one button per widget type. - **Live preview** on the right, which reruns as you edit. The palette names are friendlier than the widget types in the script API: | Palette button | Widget type | Shows | | -------------- | ---------------- | ------------------------------------------------------------- | | Stat | `stat` | One number, like an average or a count. | | Curve | `histogram` | Bars over a number range, like a mana or energy curve. | | Donut | `donut` | A ring split by category. | | Gauge | `gauge` | A bar split by category. | | Table | `table` | Rows and columns: a grouped count, or one row per card. | | Draw odds | `hypergeometric` | The chance of drawing at least one (or exactly N) of a group. | | Ratio | `ratio` | One count divided by another. | ### 2. Add a retreat cost curve 1. Click **Curve**. A widget card appears and the preview shows a curve right away. 2. Set **Title** to `Retreat cost`. 3. Set **Number field** to **Retreat cost**. Leave **Bucket size** at `1`, **Min** at `0` and **Max** empty (empty means the curve stretches to the highest value in the deck). 4. Under **Filter**, click **Add condition**, then set the condition to **Card type** · **is** · **Pokémon**. The preview now shows one bar per retreat cost, counting only Pokémon. Two settings appear on every widget: - **Count**: **Card copies** counts a 3-of three times; **Distinct cards** counts it once. - **Filter**: which cards the widget looks at. With no conditions, every card counts. With two or more conditions, choose whether a card must **Match all** or **any** of them. Categorical fields (card type, stage, energy type, regulation mark) offer a dropdown of values; others take free text, and **is one of** takes a comma-separated list. ### 3. Add an opening-hand starter table 1. Click **Table**. 2. Set **Title** to `Opening hand starters`. 3. Set **Group by** to **Per card**. The table switches to one row per distinct card, and it comes preset with three columns: **Card** (the card name), **Possible starter** and **Forced starter**, each over **Cards drawn** `7`. 4. Under **Filter**, click **Add condition**, then set it to **Stage** · **is** · **Basic**. The preview now lists each Basic Pokémon with two odds: - **Possible starter**: the chance at least one copy is in your opening 7 cards. - **Forced starter**: the chance it is your _only_ Basic in those 7 cards, so it has to start. The filter defines what counts as "a Basic": every other card that matches the filter competes with it. Use **Stage**, not **Subtype**, for this filter. Basic Energy cards carry a "Basic" subtype too; **Stage** only applies to Pokémon, so energy stays out. Use the arrows on a widget card to reorder widgets and × to remove one. ### 4. Save it Leave **Make public** unchecked for now and click **Create**. **Starter check** appears in your list, switched on and marked **Custom** and **Private**. Open any Pokémon deck, click the Calculators button, and pick **Starter check** under **Your calculators**. To change it later, click **Edit**: a calculator made in the builder reopens in the builder with all its widgets. ::: tip Peek at the code **View compiled script** under the widgets shows the JavaScript the builder generated. You don't need it, but it is the bridge to the next tutorial. ::: ## Tutorial: switch to code and add your own widget The builder covers a lot, but not everything. This tutorial adds a **Mulligan chance** stat to Starter check: the chance your opening 7 cards hold no Basic Pokémon at all. The builder can show the chance of drawing at least one Basic, but it can't show "1 minus that" as a percentage, so this is a job for code. ### 1. Open the builder's code 1. In [**Settings → Calculators**](https://pokemon.turny.gg/settings/custom-calculators), click **Edit** on Starter check. 2. Click **Drop to code** under the widgets. The widget form is replaced by a code editor holding the generated script, with the live preview beside it. The script looks like this, shortened: ```text // @calculator-spec:v1 {"widgets":[{"kind":"histogram","label":"Retreat cost",...}]} // // Generated by the Turny.gg calculator builder. ... export default function compute(pile, cardsById) { // One row per distinct card in the deck: `quantity` copies of `card`. const rows = Object.keys(pile).map((ref) => ({ ... })); // ---- Shared helpers ---- const toNumber = (value) => { ... }; const filterRows = (test) => rows.filter(test); const totalWeight = (selection, weightOf) => ...; const containsValue = (haystack, needle) => { ... }; const roundTo = (value, places) => { ... }; // ...more helpers... const widgets = []; // Widget 1: "Retreat cost" (curve histogram) { ... widgets.push({ kind: "histogram", ... }); } // Widget 2: "Opening hand starters" (distinct-card table) { ... widgets.push({ kind: "table", ... }); } return { widgets: widgets }; } ``` What you get to work with: - `rows`: one entry per distinct card in the deck, with `row.quantity` (copies) and `row.card` (the full card, or `undefined` if the catalog doesn't know it). - The shared helpers, such as `filterRows(test)` (the rows that pass a test), `totalWeight(rows, weightOf)` (add up a number per row), `containsValue(list, value)` and `roundTo(number, places)`. - `widgets`: the array every widget block pushes into. The function ends by returning it. The card fields under `row.card.game` are different in every game; see the card data reference for [Cyberpunk TCG](https://docs.turny.gg/reference/card-data/cyberpunk), [Flesh and Blood](https://docs.turny.gg/reference/card-data/fab), [Hearthstone](https://docs.turny.gg/reference/card-data/hs), [Legends of Runeterra](https://docs.turny.gg/reference/card-data/lor), [Palworld TCG](https://docs.turny.gg/reference/card-data/palworld), [Pokémon TCG](https://docs.turny.gg/reference/card-data/pokemon) and [Riftbound](https://docs.turny.gg/reference/card-data/riftbound). ### 2. Add the widget Put the cursor at the start of the line `return { widgets: widgets };` near the end of the script and paste this block above it: ```js // Mulligan chance (hand-written) { const deckSize = totalWeight(rows, (row) => row.quantity); const basics = totalWeight( filterRows( (row) => row.card?.game?.supertype === "Pokemon" && containsValue(row.card?.game?.subtypes, "Basic"), ), (row) => row.quantity, ); let chance = 0; if (deckSize >= 7 && deckSize - basics >= 7) { chance = 1; for (let i = 0; i < 7; i = i + 1) { chance = (chance * (deckSize - basics - i)) / (deckSize - i); } } widgets.push({ kind: "stat", label: "Mulligan chance", value: roundTo(chance * 100, 1), unit: "%", }); } ``` The chance of no Basic in 7 cards is the chance that each draw in turn is a non-Basic: `(non-Basics / deck) × (non-Basics − 1) / (deck − 1) × ...`, seven times. If there are fewer than 7 non-Basics, a Basic can't be avoided and the chance is 0. The card type check reads `"Pokemon"` without the accent, which is how the catalog spells it. The preview shows a third widget, **Mulligan chance**, under the other two. ### 3. Delete the marker line, then save Look at the first line of the script, the one starting with `// @calculator-spec:v1`. That is the **marker**: the builder's own settings for the calculator, saved as a comment. It has no effect on how the script runs. The builder reads it to reopen the calculator: - While the code is still exactly what the builder generates from the marker, **Back to builder** above the editor works, and you lose nothing by switching back. - As soon as you change the code, **Back to builder** turns off with the note "This script has been edited by hand, so it can no longer open in the builder." Undo your edits and it turns back on. ::: warning Delete the marker when you edit by hand If you save hand-edited code with the marker still in it, the next **Edit** opens the calculator in the builder, rebuilt from the marker. Saving from there replaces your code with the builder's version and your hand edits are lost. So once you edit the code, **delete the whole first line** (the `// @calculator-spec:v1 ...` line) before you click **Save changes**. A script without a marker always opens in the code editor. ::: Delete the marker line and click **Save changes**. Starter check now has three widgets and opens in the code editor from now on. To get back to the builder, make a new calculator. ### Starting from scratch You don't have to start from builder output. **New calculator** → **Drop to code** with no widgets gives you an empty generated script to fill in, and **Duplicate** on a default gives you a hand-written script to adapt. The smallest calculator that works is: ```js export default function compute(pile) { let total = 0; Object.keys(pile).forEach((ref) => { total += pile[ref]; }); return { widgets: [ { kind: "stat", label: "Deck size", value: total, unit: "cards" }, ], }; } ``` `compute` gets two arguments: `pile`, which maps each card ref in the deck to its number of copies, and `cardsById`, which maps each of those refs to its card. The [calculator script API](https://docs.turny.gg/reference/scripting/calculators) also documents a third, `ctx`, with the catalog's globals. Calculators opened on Turny.gg today are called without it, so don't rely on it. ## Widget cookbook One small, complete calculator per widget type, each reading real card fields. Paste one into the code editor to try it, or copy the part you need. Every field of every widget is listed in the [widget reference](https://docs.turny.gg/reference/scripting/calculators#widget-reference), and the [script API page](https://docs.turny.gg/reference/scripting/calculators#widget-examples) has a game-neutral example of each. ::: code-group ```js [stat] // Legends of Runeterra: champion copies in the deck. export default function compute(pile, cardsById) { let champions = 0; Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; if (card && card.game && card.game.supertypeRef === "Champion") { champions += pile[ref]; } }); return { widgets: [ { kind: "stat", label: "Champions", value: champions, unit: "copies" }, ], }; } ``` ```js [histogram] // Riftbound: energy curve, with 7 and up in the last bar. export default function compute(pile, cardsById) { const labels = ["0", "1", "2", "3", "4", "5", "6", "7+"]; const buckets = [0, 0, 0, 0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; const energy = card && card.game ? card.game.energy : undefined; if (typeof energy === "number") { buckets[Math.min(Math.max(energy, 0), 7)] += pile[ref]; } }); return { widgets: [ { kind: "histogram", label: "Energy curve", buckets: buckets, labels: labels, }, ], }; } ``` ```js [donut] // Legends of Runeterra: copies per region. export default function compute(pile, cardsById) { const counts = new Map(); Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; const regions = card && card.game && Array.isArray(card.game.regionRefs) ? card.game.regionRefs : []; regions.forEach((region) => { counts.set(region, (counts.get(region) || 0) + pile[ref]); }); }); const segments = []; counts.forEach((value, region) => { segments.push({ key: region, label: region, value: value, color: "" }); }); return { widgets: [{ kind: "donut", label: "Regions", segments: segments }] }; } ``` ```js [gauge] // Pokémon TCG: Pokémon / Trainer / Energy split as one bar. export default function compute(pile, cardsById) { let pokemon = 0; let trainers = 0; let energy = 0; Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; const supertype = card && card.game ? card.game.supertype : undefined; if (supertype === "Pokemon" || supertype === "Pokémon") { pokemon += pile[ref]; } else if (supertype === "Trainer") { trainers += pile[ref]; } else if (supertype === "Energy") { energy += pile[ref]; } }); return { widgets: [ { kind: "gauge", label: "Deck split", segments: [ { key: "pokemon", label: "Pokémon", value: pokemon, color: "" }, { key: "trainer", label: "Trainer", value: trainers, color: "" }, { key: "energy", label: "Energy", value: energy, color: "" }, ], }, ], }; } ``` ```js [bars] // Riftbound: copies per domain, most first. export default function compute(pile, cardsById) { const counts = new Map(); Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; const domains = card && card.game && Array.isArray(card.game.domains) ? card.game.domains : []; domains.forEach((domain) => { counts.set(domain, (counts.get(domain) || 0) + pile[ref]); }); }); const segments = []; counts.forEach((value, domain) => { segments.push({ key: domain, label: domain, value: value, color: "" }); }); segments.sort((left, right) => right.value - left.value); return { widgets: [{ kind: "bars", label: "Domains", segments: segments }] }; } ``` ```js [table] // Riftbound: units sorted by might. export default function compute(pile, cardsById) { const rows = []; Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; if (card && card.game && card.game.type === "unit") { const might = typeof card.game.might === "number" ? card.game.might : 0; rows.push([card.name, might, pile[ref]]); } }); rows.sort((left, right) => right[1] - left[1]); return { widgets: [ { kind: "table", label: "Units by might", columns: ["Unit", "Might", "Copies"], rows: rows, }, ], }; } ``` ```js [hypergeometric] // Pokémon TCG: odds of at least one Basic Pokémon in the opening 7. export default function compute(pile, cardsById) { let deckSize = 0; let basics = 0; Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; const game = card && card.game ? card.game : {}; deckSize += pile[ref]; if ( game.supertype === "Pokemon" && Array.isArray(game.subtypes) && game.subtypes.indexOf("Basic") !== -1 ) { basics += pile[ref]; } }); return { widgets: [ { kind: "hypergeometric", label: "Basic Pokémon in opening hand", population: deckSize, successCount: basics, draws: 7, exactCounts: [1, 2], }, ], }; } ``` ```js [ratio] // Legends of Runeterra: units per spell. export default function compute(pile, cardsById) { let units = 0; let spells = 0; Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; const type = card && card.game ? card.game.typeRef : undefined; if (type === "Unit") { units += pile[ref]; } else if (type === "Spell") { spells += pile[ref]; } }); return { widgets: [ { kind: "ratio", label: "Units : Spells", numerator: units, denominator: spells, format: "ratio", }, ], }; } ``` ::: A few things these examples do on purpose: - **Guard every card.** `cardsById[ref]` can be `undefined` when the catalog doesn't know a card, so each example checks `card && card.game` before reading fields. - **Use the English `...Ref` fields in Legends of Runeterra.** `typeRef`, `supertypeRef` and `regionRefs` are the same in every language; `type` and `supertype` follow the viewer's language. - **Leave `color` empty** (`""`) to let Turny.gg pick segment colors, or set a CSS color like `"#3a78e8"`. - **Return data, never markup.** Labels and values are drawn as plain text, so HTML in a label shows up as literal text. ## Sharing on your profile Check **Make public** in the calculator dialog (on create or edit) and save. The calculator's badge changes from **Private** to **Public**, and it appears on the **Calculators** tab of your profile (`/users//calculators`), on the game site it belongs to. On your profile, each public calculator shows its name, game and last update. **Show source** expands its full code so other players can read it. A signed-in player can click **Save to my calculators** to add a private copy to their own calculators, marked **Downloaded**. The copy keeps the version they saved: your later edits never change it. Once a player has saved it, the button reads **View in my calculators** (on your own profile it always does). The profile's Calculators tab only appears to other players once you have at least one public calculator. Things to know: - A **duplicate** always starts private, even when you duplicate a public calculator. - Uncheck **Make public** and save to take a calculator off your profile. - Public means the code is public. Don't put anything in a comment or label you wouldn't want others to read. ## Troubleshooting ### The preview or the calculator shows an error The live preview shows the error instead of the dashboard. On a deck, a calculator that fails shows "This calculator could not run. Its script may have an error." Common causes: | Message | Cause | | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | Calculator script source is empty. | The editor is empty. | | Calculator script did not export a compute function. | No `export default function compute(...)`, no `export default` function, and no top-level `function compute(...)`. | | A JavaScript error such as `Cannot read properties of undefined` | The script read a field on a missing card or missing field. Guard with `card && card.game` (or `?.`) first. | ### "This calculator script uses APIs or syntax that are not allowed." Calculators run in the same locked-down sandbox as custom rulesets, and a safety check reads every script before it runs or saves. When it rejects a script, **Save** refuses with this message, and the preview shows the same message followed by what the check found. The usual suspects: - `var` (use `let` or `const`), - globals that aren't on the allowed list, such as `fetch`, `window`, `globalThis` or `eval`, - `async`, `await` and generator functions, - `class`, `this`, `delete` and `import`, - `new` on anything other than `Date`, `Map`, `RegExp` or `Set`, - property names such as `constructor`, `prototype` and `__proto__`, - assigning to a variable you didn't declare. The full rules, with every allowed global and every rejection code, are on the [script sandbox](https://docs.turny.gg/reference/scripting/sandbox) page. ### It runs forever, then fails A calculator that runs longer than **5 seconds** is stopped. On a deck it shows the error message; in the editor the live preview says "This calculator ran for more than 5 seconds and was stopped. Check for a loop that never ends." That almost always means a loop that never ends, such as a `while` whose condition never turns false. The preview runs in the same sandbox with the same limit, so an endless loop can't freeze the page: fix the loop and the preview runs again. Calculators only ever see one deck, so a script that finishes quickly on the sample deck will finish quickly everywhere. ### Some of my output is missing Nothing a calculator returns is drawn as-is. It is checked first, and anything that doesn't fit is repaired or dropped instead of breaking the dashboard: - A widget with an unknown `kind` is dropped; the rest still draw. - Numbers that aren't numbers become `0`. - A widget with nothing to show (no rows, no positive values, a zero denominator) draws "No data". - Output past the caps is cut off: at most 50 widgets, 100 segments per donut or gauge, 200 histogram bars, 200 table rows, 20 table columns, and 200 characters per label or table cell. The exact rules are under [How bad output is handled](https://docs.turny.gg/reference/scripting/calculators#how-bad-output-is-handled) and [Limits](https://docs.turny.gg/reference/scripting/calculators#limits). ### My code edits disappeared The calculator still had its `// @calculator-spec:v1` marker when you saved, so the next **Edit** reopened it in the builder, and saving from the builder wrote the builder's version back. See [Delete the marker line, then save](#_3-delete-the-marker-line-then-save). If you still have your edited code, paste it back, delete the marker line and save. ### The builder offers the wrong fields The fields in the builder come from the game site you are on: Pokémon fields on [pokemon.turny.gg](https://pokemon.turny.gg/settings/custom-calculators), Runeterra fields on [lor.turny.gg](https://lor.turny.gg/settings/custom-calculators), and so on. Calculators are per game, so open Settings on the site for the game you are building for. --- url: https://docs.turny.gg/guide/playtest description: "Goldfish a deck on a virtual table, solo or against a mirrored opponent, and write, share and fix the playtest rules scripts that set the table up." --- # Playtest Playtest puts a deck on a virtual table so you can play it out by hand: draw, play cards, tap them, count damage, take turns. You can play **solo** or against a **mirrored opponent** that you also control. Nothing checks the rules of the game; you move the cards, and every move can be undone. What the table looks like comes from a **playtest rules script**. It lists the piles (zones), where they sit, who can see them, what you can do to cards and piles, and which keys do it. Every launched game with a playtest table ships a default script, and you can fork it, change it and share your version. This guide covers playing first, then writing and sharing rules. For the exact shape of everything a script can return, see the [playtest rules script API](https://docs.turny.gg/reference/scripting/playtest). ## Using Playtest {#using-playtest} ### Where to find it Look for the **Playtest** button (a game controller icon) on any deck: - on a deck page and in the deck preview dialog, - in the deck builder, next to the deck's other actions, - in the action menu of your saved decks. **Playtest** is also its own item in the side navigation, near the bottom, on every game that has playtest rules. Opening it from there starts with no deck picked. ### Pick the rules and a deck Setting up a game takes three steps, and you can go back and **Change** any of them before you start. 1. **Rules.** When only one set of rules is switched on for the game, it is used without asking. With more than one, pick a set; tick **Don't ask again** to always use the last set you picked. You can switch rules on and off in [Settings](#manage-your-rules). 2. **Deck.** The deck you launched Playtest from is already filled in. Otherwise pick one of **Your saved decks** (when signed in) or **Paste a deck code** (anyone can). 3. **Mode.** **Solo** sets up only your side of the table. **Versus** adds a mirrored opponent board that you also control; there is no computer opponent. The opponent plays **the same deck as yours** unless you choose **Use a different deck**. Press **Start** and the table deals itself: the rules' setup runs for each side (usually a shuffle and an opening hand). ### Playing the table The rules decide what each input does, but the inputs are always the same: | Input | What it does | | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Click** a card | Runs the card's click action if the rules give it one; otherwise selects it (click again to deselect). | | **Ctrl-click**, **Cmd-click** or **Shift-click** a card | Adds the card to the selection, or takes it out. Actions on "the selection" then run on every selected card. | | **Double-click** a card | Runs the card's double-click action, such as playing it or taking a prize. | | **Click** a pile | Runs the pile's main action, such as drawing from the deck. | | **Right-click** (or **long-press**) a card or pile | Opens a menu of every action that applies to it. A pile's menu also has **View cards** and **Look at top cards**. | | **View card** in a card's menu | Shows everything stacked on the card, such as attached energy and tools and earlier evolutions. Pick any of them and **Move** them, as in **View cards**: a moved card takes its attachments along, a lone attachment comes off. | | **Drag** a card onto a pile | Moves it there (a dragged card that is part of the selection moves the whole selection). Some rules run an action instead. | | **Drag** a card onto another card | Runs the dragged card's drop action if it has one, such as attaching an energy or evolving a Pokémon. | On a touch screen, tap a card to select it and tap it again to run its main action. In your hand, drag a card upward to pick it up; elsewhere, press and hold, then move. Release a held card without moving to open its menu instead. Some actions create cards that weren't in your deck, such as copies, level-ups and tokens. Created cards carry a small badge. When an action can create more than one kind of card, a picker asks which. The toolbar above the table has **New game**, **Undo** and **Redo**, an **Actions** menu (everything that applies to a side or the whole table, for both sides), the **Turn** button, a **−** and **+** for each tracker such as life or mana, the **Action log** and **Keyboard shortcuts**. In Versus it also has **Reveal opponent hand**, which shows the opponent's private cards to you, and **Flip board**, which swaps which side sits at the bottom. **Turn** shows the current turn, starting at 1. When the rules name a turn action (usually **New turn**), clicking **Turn** runs it, exactly as picking it from the **Actions** menu does, and it undoes the same way; that action's shortcut (`N` in the default rules) does the same as the click. **In Versus the sides take turns**: each click starts the next turn for the other side, start-of-turn draw included, and the button names whose turn it is (**Turn 3 · Opponent**). Rules whose turn action advances the whole table at once, as Legends of Runeterra's does, count **Rounds** instead. Rules without a turn action show the count only. In Versus the **Actions** menu lists your actions and the opponent's under separate headings (**Game · You**, **Game · Opponent**), and the opponent's shortcuts show with Alt. **View cards** opens with **Move to** set to your hand, the usual place to take a card from a deck or discard pile. A pile or a card that refuses a move (a full Bench, a card the zone doesn't accept) keeps the card where it was, and the log says so. ### Acting for the opponent: hold Alt {#alt-for-the-opponent} In Versus, **every input with Alt held acts on the opponent's side instead of yours.** With Legends of Runeterra's default rules, `D` draws for you and `Alt+D` draws for the opponent, and Alt-clicking your deck draws for the opponent too. Actions on cards always act for the card's owner, so Alt matters for piles and for side-wide actions. On a Mac, Alt is the Option key. Because Alt is reserved for this, no rules script can put Alt in a shortcut. ### Undo, redo and rewind {#undo-redo-and-rewind} **Every change to the table can be undone**, including a drag and drop and New game. - **Undo** with `Mod+Z` (Cmd+Z on a Mac, Ctrl+Z elsewhere) or the toolbar button. **Redo** with `Mod+Shift+Z` or `Mod+Y`. - **One action is one undo step.** A compound action such as **New turn** (untap everything, then draw) undoes as a whole. - **Doing something new clears the redo list**, as in a text editor. - **Shuffles repeat exactly.** The table's randomness comes from a seed saved with the game, so undoing a shuffle and redoing it gives the same order. To really re-roll, open **Actions** and pick **New random seed**. - **Rewind from the log.** The **Action log** lists every action in order. Click an entry to **Rewind to this point**; the later actions stay in the redo list until you do something new. Selecting cards, hovering and opening a viewer are not changes to the table, so they are never undone. ### Keyboard shortcuts {#keyboard-shortcuts} Press `?` at any time to see every shortcut the current rules define, grouped as the rules group them. When the rules describe an action, the description under its name says what it does and which card to select or point at. - A shortcut for a **card action** runs on the selected cards, or on the card under the pointer when nothing is selected. - A shortcut that **attaches** cards (an energy, a tool, an evolution) runs on the selected cards and attaches them to the card under the pointer, as long as that card is not selected itself. Right-clicking that card offers the same attach actions in its menu. - A shortcut for a **pile action** runs on the pile under the pointer, or on the pile the action belongs to. - A shortcut for a **side or table action** runs for you (hold Alt for the opponent). - `Escape` clears the selection. Shortcuts match the key you press, not the letter it types, so they work the same on every keyboard layout. ### Your game is saved in this browser The game in progress, including its undo history, is saved automatically in this browser as you play, so a reload doesn't lose it. It is not saved to your account: another browser or device starts fresh, and clearing the site's data deletes it. ## The default rules {#the-default-rules} Each game's default rules are plain playtest scripts. Read their source to see a complete, real table, or fork one as the starting point for your own: | Game | Rules | Source | | --- | --- | --- | | Cyberpunk TCG | Standard | [Read the script](https://cyberpunk.turny.gg/playtest-rules/019a6a4c-7c50-7a01-9c2e-4f1d8b3e7c50) | | Flesh and Blood | Standard | [Read the script](https://fab.turny.gg/playtest-rules/01926f3a-2067-7000-8000-000000000001) | | Hearthstone | Standard | [Read the script](https://hs.turny.gg/playtest-rules/01926f3a-1118-7000-8000-000000000001) | | Legends of Runeterra | Standard | [Read the script](https://lor.turny.gg/playtest-rules/01926f3a-1019-7000-8000-000000000001) | | Magic: The Gathering | Standard | [Read the script](https://mtg.turny.gg/playtest-rules/019a2b40-1022-7a01-8c3e-5d2f7b9e1022) | | Magic: The Gathering | Commander | [Read the script](https://mtg.turny.gg/playtest-rules/019a2b40-1022-7a02-8c3e-5d2f7b9e1022) | | Palworld TCG | Standard game | [Read the script](https://palworld.turny.gg/playtest-rules/01926f3a-9a1d-7000-8000-000000000001) | | Pokémon TCG | Standard | [Read the script](https://pokemon.turny.gg/playtest-rules/019a1f6e-5c3d-7a41-9b2e-6f0d4c8a1020) | | Riftbound | Standard | [Read the script](https://riftbound.turny.gg/playtest-rules/01926f3a-1021-7000-8000-000000000001) | ## Writing playtest rules {#writing-playtest-rules} A playtest rules script is a JavaScript function that runs once when a game starts. It returns plain data describing the table, and the table does the rest. It never runs again during the game, so it cannot react to clicks: instead it declares actions as lists of simple **steps** (move, draw, shuffle, tap, add a counter, ...) that the table runs for you. ### Manage your rules {#manage-your-rules} Playtest rules belong to one game. Manage them in **Settings → Playtest rules** on that game's site, for example [Legends of Runeterra](https://lor.turny.gg/settings/playtest-rules) or [Pokémon TCG](https://pokemon.turny.gg/settings/playtest-rules). The list shows the game's system defaults and your own rules. From there you can: - **switch** any set on or off; a switched-off set is hidden from the rules picker ("Hidden from the rules picker"), - **Try it** to open Playtest with those rules and a sample deck, - **View code** of a system default or a saved copy, - **Fork** any set into a new, editable set of your own, - **Edit**, **Delete** and share the sets you made (see [Sharing](#sharing)). System defaults are read-only. To change one, fork it. ### Tutorial: a three-zone table This tutorial builds a small table from scratch: a deck, a hand and a board. Then it adds actions and shortcuts. #### 1. Start a new set of rules 1. Open **Settings → Playtest rules** and click **New rules**. 2. Type `My first table` in **Name**. 3. Replace the **Rules script** with the script below. The **Validation** panel beside the editor re-checks the script as you type, over a sample deck for the game. It lists any problem with its code (see [Troubleshooting](#troubleshooting)), or counts the zones, actions and shortcuts and lists every shortcut. ```js export default function playtest(deck) { // One entry per copy: a 3-of appears three times. const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) { cards.push(code); } }); return { version: 1, // Each side is 6 columns by 2 rows. Row 0 is nearest the middle. table: { columns: 6, rows: 2 }, zones: [ { id: "board", label: "Board", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [], setup: [], initialZones: { deck: cards }, }; } ``` What each part does: - **`deck`** is the deck being played: `deck.main` maps each card code to its number of copies. The script turns it into a list with one entry per copy. - **`table`** is the grid each side is drawn on. Row 0 borders the middle of the table, so the board sits nearest the opponent and the hand nearest you. - **`zones`** are the piles. `owner: "side"` gives each player their own copy. `visibility` says who sees card faces: nobody (`"hidden"`), only the owner (`"private"`) or everyone (`"public"`). `layout` is how the cards are drawn: a `"pile"`, a `"fan"`, a `"row"`, and more. - **`initialZones`** says where the cards start: the whole deck, face down, in `deck`. Even with no actions, this table already works: drag cards between the three zones, and undo any move. #### 2. Add actions An action is a named list of steps, plus what it runs on (`target`) and how you trigger it. Replace `actions: [],` in the script with: ```js actions: [ // Click the deck to draw a card. { id: "draw", label: "Draw", target: "zone", zones: ["deck"], triggers: ["click"], steps: [{ kind: "draw", from: "deck", to: "hand" }], }, // Double-click a card in hand to play it. { id: "play", label: "Play", target: "selection", zones: ["hand"], triggers: ["doubleClick"], steps: [{ kind: "move", to: "board" }], }, // Double-click a card on the board to tap or untap it. { id: "tap", label: "Tap / untap", target: "selection", zones: ["board"], triggers: ["doubleClick"], steps: [{ kind: "rotate" }], }, ], ``` - `target: "zone"` with `zones: ["deck"]` makes **Draw** an action of the deck. `triggers: ["click"]` runs it when you click the deck. - `target: "selection"` runs on every selected card, or on the card you double-clicked. `zones: ["hand"]` limits **Play** to cards in your hand. - A `rotate` step with no `to` turns each card between upright and tapped. - Every action also appears in the right-click menu of whatever it applies to. Add `menu: false` to leave one out. #### 3. Add shortcuts and a setup Give each action a `shortcut`, add a **Next turn** action that untaps and draws, and a `setup` that shuffles and deals an opening hand. This is the finished script: ```js export default function playtest(deck) { 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: 6, rows: 2 }, zones: [ { id: "board", label: "Board", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, primaryActionId: "draw", }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "draw", label: "Draw", target: "zone", zones: ["deck"], shortcut: "d", steps: [{ kind: "draw", from: "deck", to: "hand" }], }, { id: "play", label: "Play", target: "selection", zones: ["hand"], triggers: ["doubleClick"], shortcut: "p", steps: [{ kind: "move", to: "board" }], }, { id: "tap", label: "Tap / untap", target: "selection", zones: ["board"], triggers: ["doubleClick"], shortcut: "t", steps: [{ kind: "rotate" }], }, { id: "nextTurn", label: "Next turn", target: "side", shortcut: "n", steps: [ { kind: "readyAll", zones: ["board"] }, { kind: "turn" }, { kind: "draw", from: "deck", to: "hand" }, ], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 5 }, ], initialZones: { deck: cards }, }; } ``` What changed: - **Shortcuts.** Press `D` to draw, `P` to play the selected (or hovered) card, `T` to tap it and `N` for the next turn. `Alt+D` draws for the opponent in Versus, with no extra code. Letters are matched case-insensitively; `shift+` and `mod+` (Cmd on a Mac, Ctrl elsewhere) are allowed, `alt+` is not. The full grammar is in the [shortcut reference](https://docs.turny.gg/reference/scripting/playtest#shortcuts). - **`primaryActionId: "draw"`** makes a click on the deck run **Draw**, instead of the `triggers: ["click"]` from step 2. - **Next turn** is a `side` action: it runs for your side (or the opponent's with Alt), readies every card on the board, adds 1 to the turn counter and draws, all as **one undo step**. The toolbar's **Turn** button shows the turn counter; to make it run an action, name it in `roundActionId` as in [Next round for both sides](#recipe-next-round). Add a `description` to any action to explain it under its name in the shortcut sheet (`?`) and as its tooltip in menus. - **`setup`** runs for each side when a game starts, after the cards are placed: shuffle the deck, then draw 5. #### 4. Save and try it Click **Save**. **My first table** appears in your list, switched on. Click **Try it** to open Playtest with it and a sample deck, or start Playtest from any deck and pick **My first table**. ### Tips for writing rules - **Build card tags from `cardsById`.** Steps and zones can't read card fields directly. Compute tags (such as `"unit"` or `"energy"`) from each card's fields once, return them in `cardTags`, and test them with `{ kind: "tag", tag: "energy" }`. See [Card tags from `cardsById`](#card-tags-from-cardsbyid). - **Relate cards with `associatedCards`.** Level-ups, tokens and cards that create other cards come from each card's `game.associatedCardRefs`. Return them in `associatedCards` and let a `card` param pick one. See [Level up via an associated card](#recipe-level-up). - **Guard every card.** `cardsById[code]` can be missing when the catalog doesn't know a card, so check `card && card.game` before reading fields. - **Keep ids short and stable.** Zone, action, tracker and marker ids are how steps refer to each other; labels are only what the player reads. - **Let the table do the bookkeeping.** A zone's `enterState` can untap, turn face up or clear counters on every card that enters it, so each action doesn't have to. ## Cookbook {#cookbook} Small, complete scripts, one per technique. Paste one into the editor to try it, or copy the parts you need. The [default rules](#the-default-rules) use all of them at full size. Each script starts with the same small `cardList` helper, which lists one entry per copy in the deck. ### A hidden prize grid {#recipe-prize-grid} Six face-down Prizes nobody can see, set aside from the top of the deck at setup. Double-click a prize to take it, or press `Shift+P` for a random one. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck) { return { version: 1, table: { columns: 4, rows: 2 }, zones: [ { id: "prizes", label: "Prizes", owner: "side", visibility: "hidden", layout: "grid", area: { row: 0, col: 0, rowSpan: 2 }, ordered: false, defaultFaceDown: true, showCount: true, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 3 }, ordered: true, defaultFaceDown: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 1, colSpan: 3 }, ordered: true, defaultFaceDown: false, enterState: { faceDown: false }, }, ], trackers: [], markers: [], actions: [ { id: "takePrize", label: "Take this prize", target: "card", zones: ["prizes"], triggers: ["doubleClick"], steps: [{ kind: "move", to: "hand" }], }, { id: "takeRandomPrize", label: "Take a random prize", target: "side", shortcut: "shift+p", steps: [ { kind: "move", cards: { zone: "prizes", count: 1, pick: "random" }, to: "hand", }, ], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "move", cards: { zone: "deck", count: 6 }, to: "prizes", faceDown: true, }, ], initialZones: { deck: cardList(deck) }, }; } ``` `visibility: "hidden"` hides the faces from both players, you included. `pick: "random"` uses the game's seeded randomness, so undo and redo take the same prize. ### An attach-under energy drop {#recipe-attach-energy} Drag an Energy card onto a Pokémon and it tucks underneath it, then moves with it from zone to zone. Or use the keyboard: select the Energy, hover the Pokémon and press `Q`. **Detach** on the Pokémon returns everything under it to your hand. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck, cardsById) { const cardTags = {}; Object.keys(cardsById).forEach((code) => { const card = cardsById[code]; const supertype = card && card.game ? card.game.supertype : ""; if (supertype === "Energy") { cardTags[code] = ["energy"]; } }); return { version: 1, table: { columns: 5, rows: 2 }, zones: [ { id: "active", label: "Active", owner: "side", visibility: "public", layout: "slots", area: { row: 0, col: 0, colSpan: 4 }, capacity: 4, ordered: true, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 4 }, ordered: true, defaultFaceDown: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "attach", label: "Attach", target: "selection", when: { kind: "tag", tag: "energy" }, triggers: ["drop"], shortcut: "q", steps: [{ kind: "attach", mode: "under" }], }, { id: "detach", label: "Detach", target: "card", zones: ["active"], steps: [{ kind: "detach", to: "hand" }], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 7 }, ], initialZones: { deck: cardList(deck) }, cardTags: cardTags, }; } ``` `triggers: ["drop"]` runs the action when the selected cards are dropped **onto a card**, which becomes the host. `shortcut: "q"` runs it from the keyboard: the selected cards attach to the card under the pointer, which becomes the host the same way (with nothing hovered, the last selected card is the host). `mode: "under"` keeps the host as the visible card; `mode: "over"` puts the new card on top, like an evolution. `when` hides the action unless every target card (here, every dragged or selected card) is tagged `energy`; the host is never tested. Attached cards skip the host zone's `accepts` and `capacity`. ### A compound "Next turn" {#recipe-next-turn} One key that untaps everything, advances the turn and draws, as a single undo step. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck) { return { version: 1, table: { columns: 6, rows: 2 }, zones: [ { id: "board", label: "Board", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, primaryActionId: "draw", }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "draw", label: "Draw", target: "zone", zones: ["deck"], steps: [{ kind: "draw", from: "deck", to: "hand" }], }, { id: "tap", label: "Tap / untap", target: "selection", zones: ["board"], triggers: ["doubleClick"], shortcut: "t", steps: [{ kind: "rotate" }], }, { id: "nextTurn", label: "Next turn", target: "side", group: "Turn", shortcut: "n", steps: [ { kind: "readyAll", zones: ["board"] }, { kind: "turn" }, { kind: "draw", from: "deck", to: "hand" }, { kind: "log", message: "Untapped and drew for the turn." }, ], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 7 }, ], initialZones: { deck: cardList(deck) }, }; } ``` A `side` action runs for one side: yours, or the opponent's with Alt. `readyAll` turns every card in the listed zones upright; its optional `skipFlag` leaves cards with that [flag](#recipe-next-round) tapped. `group` puts the action under a heading in menus and the shortcut sheet. ### Draw N with the digit keys {#recipe-draw-n} Hover the deck and press `1` to `9` to draw that many cards. From the deck's menu, **Draw N** asks how many. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck) { return { version: 1, table: { columns: 6, 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, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "draw", label: "Draw", target: "zone", zones: ["deck"], steps: [{ kind: "draw", from: "deck", to: "hand" }], }, { id: "drawN", label: "Draw N", target: "zone", zones: ["deck"], shortcut: "1-9", params: [ { id: "count", label: "Cards", kind: "number", min: 1, max: 60 }, ], steps: [ { kind: "draw", from: "deck", to: "hand", count: { param: "count" } }, ], }, ], setup: [{ kind: "shuffle", zone: "deck" }], initialZones: { deck: cardList(deck) }, }; } ``` The shortcut `"1-9"` binds every digit and passes the digit you pressed as the action's first `number` param. `{ param: "count" }` reads that value in a step. From a menu, an action with params always asks for them first; a click or shortcut asks only for params that have no `default`. ### A shared zone {#recipe-shared-zone} A single Stadium for the whole table, between the two halves. Either player can put a Stadium there, but it holds only one card. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck) { return { version: 1, table: { columns: 5, rows: 2, sharedRows: 1 }, zones: [ { id: "stadium", label: "Stadium", owner: "shared", visibility: "public", layout: "slots", area: { row: 0, col: 2 }, capacity: 1, ordered: false, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 4 }, ordered: true, defaultFaceDown: true, }, { id: "discard", label: "Discard", owner: "side", visibility: "public", layout: "pile", area: { row: 0, col: 3 }, ordered: true, defaultFaceDown: false, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "playStadium", label: "Play as Stadium", target: "card", zones: ["hand"], shortcut: "g", steps: [{ kind: "move", to: "stadium" }], }, { id: "discardStadium", label: "Discard Stadium", target: "card", zones: ["stadium"], steps: [{ kind: "move", to: "discard" }], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 7 }, ], initialZones: { deck: cardList(deck) }, }; } ``` A shared zone's `area` is a cell of the strip between the halves, which has `table.sharedRows` rows and the same columns as each side. Card actions always run for the card's owner, so **Discard Stadium** sends the card to its owner's discard pile, whichever side it came from. To place a shared zone inside your half instead, next to your own zones (such as a Stadium left of the Active Pokémon), add `sharedPlacement: "playerGrid"`. Its `area` is then a cell of the side grid (`table.columns` by `table.rows`) and must not cover any side zone; the opponent's mirrored half leaves that cell empty. It is still one zone for the whole table, and either side can play into it. `sharedPlacement` is only allowed on shared zones and defaults to `"strip"`. ### Card tags from `cardsById` {#card-tags-from-cardsbyid} Tag each card from its catalog fields, then let zones and actions test the tags. Here, from Legends of Runeterra's card types: only units may enter the board, and **Cast** only shows up on spells. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck, cardsById) { const cardTags = {}; // Tag every card the table can show, the opponent's deck included. Object.keys(cardsById).forEach((code) => { const card = cardsById[code]; const type = card && card.game ? card.game.typeRef : undefined; if (type === "Unit") { cardTags[code] = ["unit"]; } else if (type === "Spell") { cardTags[code] = ["spell"]; } }); return { version: 1, table: { columns: 6, rows: 2 }, zones: [ { id: "board", label: "Board", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 4 }, ordered: true, defaultFaceDown: false, accepts: { kind: "tag", tag: "unit" }, }, { id: "graveyard", label: "Graveyard", owner: "side", visibility: "public", layout: "pile", area: { row: 0, col: 4 }, ordered: true, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "cast", label: "Cast", target: "selection", zones: ["hand"], when: { kind: "tag", tag: "spell" }, shortcut: "c", steps: [{ kind: "move", to: "graveyard" }], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 4 }, ], initialZones: { deck: cardList(deck) }, cardTags: cardTags, }; } ``` `cardTags` maps a card code to its tags. Tag every code in `cardsById`, not only the ones in `deck`: in Versus with a different opponent deck, `cardsById` covers both decks. A spell dragged onto the board is refused and stays in hand. The card fields differ per game; see the card data reference for [Cyberpunk TCG](https://docs.turny.gg/reference/card-data/cyberpunk), [Flesh and Blood](https://docs.turny.gg/reference/card-data/fab), [Hearthstone](https://docs.turny.gg/reference/card-data/hs), [Legends of Runeterra](https://docs.turny.gg/reference/card-data/lor), [Palworld TCG](https://docs.turny.gg/reference/card-data/palworld), [Pokémon TCG](https://docs.turny.gg/reference/card-data/pokemon) and [Riftbound](https://docs.turny.gg/reference/card-data/riftbound). ### Next round for both sides {#recipe-next-round} A table-wide **Next round**, run by the toolbar's **Turn** button (which reads **Round** for a `game` action), that advances the round once, then refills mana, clears "Stunned" and draws for every side in play. It shows the round action, trackers, tracker values, flags and the `forEachSide` block. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck) { return { version: 1, table: { columns: 6, rows: 2 }, zones: [ { id: "board", label: "Board", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, enterState: { resetFlags: true }, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, }, ], trackers: [ { id: "manaGems", label: "Mana gems", initial: 0, min: 0, max: 10, owner: "side", }, { id: "mana", label: "Mana", initial: 0, min: 0, max: 10, owner: "side" }, ], markers: [], flags: [{ id: "stunned", label: "Stunned" }], actions: [ { id: "stun", label: "Stun", target: "selection", zones: ["board"], shortcut: "s", steps: [{ kind: "flag", flag: "stunned", mode: "toggle" }], }, { id: "nextRound", label: "Next round", target: "game", shortcut: "n", steps: [ { kind: "turn" }, { kind: "forEachSide", steps: [ { kind: "tracker", tracker: "manaGems", delta: 1 }, { kind: "tracker", tracker: "mana", set: { tracker: "manaGems" }, }, { kind: "clearFlag", flag: "stunned", zones: ["board"] }, { kind: "draw", from: "deck", to: "hand" }, ], }, ], }, ], roundActionId: "nextRound", setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 4 }, ], initialZones: { deck: cardList(deck) }, }; } ``` - `roundActionId` names the action the toolbar's **Turn** button runs; it must be a `game` or `side` action. A `game` action, as here, counts **rounds** that advance the whole table at once, so the button reads **Round**. A `side` action counts **turns**: in Versus each click starts the next turn for the other side. Either way the `turn` step advances the table's turn counter once, **outside** the block, so there is no separate round tracker. - A `game` action runs once for the whole table. - `forEachSide` runs its steps once per side in play (you first), each time as that side. Block steps can't be nested, and `setup` can't use `forEachSide` because it already runs once per side. - `{ tracker: "manaGems" }` in a number field reads that tracker's current value when the step runs: here, mana refills to the number of gems. - Flags are on/off marks on cards, declared in `flags` so the table can label them. `enterState: { resetFlags: true }` clears them when a card enters the board. ### Redraw until a condition holds {#recipe-redraw-until} A Pokémon-style opening hand: draw 7, and while the hand has no Basic Pokémon, shuffle it back and draw 7 again. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck, cardsById) { const cardTags = {}; Object.keys(cardsById).forEach((code) => { const game = cardsById[code] && cardsById[code].game; const supertype = game ? String(game.supertype).replace("é", "e") : ""; const subtypes = game && Array.isArray(game.subtypes) ? game.subtypes : []; if (supertype === "Pokemon" && subtypes.indexOf("Basic") !== -1) { cardTags[code] = ["basic"]; } }); const hasBasic = { kind: "zoneHas", zone: "hand", where: { kind: "tag", tag: "basic" }, }; const redraw = [ { kind: "move", cards: { zone: "hand" }, to: "deck" }, { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 7 }, ]; return { version: 1, table: { columns: 6, rows: 1 }, zones: [ { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 0 }, ordered: true, defaultFaceDown: true, enterState: { faceDown: true }, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 0, col: 1, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "mulligan", label: "Mulligan", target: "side", shortcut: "shift+m", steps: redraw.concat([ { kind: "repeatUntil", until: hasBasic, steps: redraw, maxIterations: 20, }, ]), }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 7 }, { kind: "repeatUntil", until: hasBasic, steps: redraw, maxIterations: 20, }, ], initialZones: { deck: cardList(deck) }, cardTags: cardTags, }; } ``` `repeatUntil` checks `until` **before** each pass, so a hand that already has a Basic Pokémon is kept as it is. `maxIterations` caps the passes (at most 20), which stops a deck with no Basic Pokémon at all from looping forever. `until` can only test zones, with `zoneHas` (combined with `all`, `any` and `not` if needed), because there is no single card to test. Every pass is logged, and the whole redraw is still one undo step. ### Create a copy {#recipe-create-copy} Put a copy of a card on the table that was never in the deck, as some cards do in Legends of Runeterra. It shows the `create` and `remove` steps. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck) { return { version: 1, table: { columns: 6, rows: 2 }, zones: [ { id: "board", label: "Board", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [], actions: [ { id: "copy", label: "Create a copy", target: "card", zones: ["board"], shortcut: "c", steps: [{ kind: "create", card: "target" }], }, { id: "copyToHand", label: "Create a copy in hand", target: "card", zones: ["board"], steps: [{ kind: "create", card: "target", to: "hand" }], }, { id: "removeCopy", label: "Remove from game", target: "selection", zones: ["board", "hand"], // Only offered on created cards. when: { kind: "created" }, steps: [{ kind: "remove" }], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 4 }, ], initialZones: { deck: cardList(deck) }, }; } ``` - `card: "target"` copies the card the action runs on. Without `to`, the copy goes into the target's own zone; with `to`, into that zone. `count` makes several copies at once (at most 20). - The copy is a new card marked as **created**. It takes the destination's `defaultFaceDown` and `enterState` like any card moving in, and a full zone refuses it (the log says so). - `remove` takes created cards out of the game. Cards from the deck are never removed: the step skips them and says so in the log. Cards attached to a removed card stay in its zone. - The `created` predicate is true only for created cards, so `when: { kind: "created" }` keeps **Remove from game** off deck cards. A `tag` can't tell them apart: a copy has the same card code as its original. - Undo takes the copy away again, and redo brings it back with the same id. ### Level up via an associated card {#recipe-level-up} A champion levels up by turning into its level 2 card. Catalog cards list their related cards (level-ups, tokens, cards they create) in `card.game.associatedCardRefs`, and the table includes those cards in `cardsById`. Return them in `associatedCards`, and a `card` param picks one of them. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck, cardsById) { const cardTags = {}; const associatedCards = {}; Object.keys(cardsById).forEach((code) => { const card = cardsById[code]; const game = card && card.game ? card.game : {}; if (game.supertypeRef === "Champion") cardTags[code] = ["champion"]; if (Array.isArray(game.associatedCardRefs)) { associatedCards[code] = game.associatedCardRefs; } }); return { version: 1, table: { columns: 6, rows: 2 }, zones: [ { id: "board", label: "Board", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 5 }, ordered: true, defaultFaceDown: false, }, { id: "deck", label: "Deck", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, }, ], trackers: [], markers: [{ id: "damage", label: "Damage", step: 1 }], actions: [ { id: "levelUp", label: "Level up", target: "card", zones: ["board"], when: { kind: "tag", tag: "champion" }, shortcut: "l", params: [ { id: "into", label: "Level up into", kind: "card", cardSource: { kind: "associated", where: { kind: "tag", tag: "champion" }, }, }, ], steps: [{ kind: "transform", card: { param: "into" } }], }, ], setup: [ { kind: "shuffle", zone: "deck" }, { kind: "draw", from: "deck", to: "hand", count: 4 }, ], initialZones: { deck: cardList(deck) }, cardTags: cardTags, associatedCards: associatedCards, }; } ``` - A `card` param's `cardSource` says where its choices come from. `kind: "associated"` lists the target card's `associatedCards`; `where` narrows them by tag. `where` can only test tags (with `all`, `any` and `not`), because the choices are card codes, not cards on the table. - When exactly one card qualifies, Playtest picks it without asking. Here a level 1 champion's associated cards include the spell it creates, so `where` keeps only the champion card. - `transform` changes the card's code in place. It stays where it is, with its damage, flags, rotation and attached cards, so levelling up keeps the board as it was. - A `card` param can also feed `create`: `{ kind: "create", card: { param: "into" }, to: "board" }` puts a new copy of the picked card on the board. ### Tokens that vanish off the battlefield {#recipe-vanishing-tokens} In Magic: The Gathering, a token that leaves the battlefield stops existing. Mark the zones it can't survive in with `removesCreated: true`, and the table takes created cards out of the game when they enter. ```js function cardList(deck) { const cards = []; Object.keys(deck.main).forEach((code) => { for (let copy = 0; copy < deck.main[code]; copy += 1) cards.push(code); }); return cards; } export default function playtest(deck, cardsById) { const cardTags = {}; const associatedCards = {}; Object.keys(cardsById).forEach((code) => { const card = cardsById[code]; const game = card && card.game ? card.game : {}; if (game.layout === "token") cardTags[code] = ["token"]; if (Array.isArray(game.associatedCardRefs)) { associatedCards[code] = game.associatedCardRefs; } }); return { version: 1, table: { columns: 6, rows: 2 }, zones: [ { id: "battlefield", label: "Battlefield", owner: "side", visibility: "public", layout: "row", area: { row: 0, col: 0, colSpan: 4 }, ordered: true, defaultFaceDown: false, }, { id: "graveyard", label: "Graveyard", owner: "side", visibility: "public", layout: "pile", area: { row: 0, col: 4 }, ordered: true, defaultFaceDown: false, removesCreated: true, }, { id: "library", label: "Library", owner: "side", visibility: "hidden", layout: "pile", area: { row: 0, col: 5 }, ordered: true, defaultFaceDown: true, removesCreated: true, }, { id: "hand", label: "Hand", owner: "side", visibility: "private", layout: "fan", area: { row: 1, col: 0, colSpan: 6 }, ordered: true, defaultFaceDown: false, removesCreated: true, }, ], trackers: [], markers: [], actions: [ { id: "makeToken", label: "Create a token", target: "card", zones: ["battlefield"], shortcut: "k", params: [ { id: "token", label: "Token", kind: "card", cardSource: { kind: "associated", where: { kind: "tag", tag: "token" }, }, }, ], steps: [ { kind: "create", card: { param: "token" }, to: "battlefield" }, ], }, { id: "destroy", label: "Destroy", target: "selection", zones: ["battlefield"], shortcut: "x", steps: [{ kind: "move", to: "graveyard" }], }, ], setup: [ { kind: "shuffle", zone: "library" }, { kind: "draw", from: "library", to: "hand", count: 7 }, ], initialZones: { library: cardList(deck) }, cardTags: cardTags, associatedCards: associatedCards, }; } ``` - `removesCreated` applies however a created card gets there: a step, a drag and drop, or a draw. Cards from the deck move in as usual. - A token attached to a deck card leaves with it too: destroying the host sends the host to the graveyard and takes the token out of the game. - The table doesn't know which cards are tokens. The script decides, here from the catalog's `game.layout`; the card data reference for your game lists its fields. ## Sharing {#sharing} Every set of rules you make is **private** until you share it. - **Make public** (a button in **Settings → Playtest rules**, or the **Make public** box in the editor) lists the rules on the **Playtest rules** tab of your profile and lets anyone with the link open them. **Make private** takes them down again. - **Copy link** (public rules only) copies the rules' page link, `/playtest-rules/` on the game's site. Links always show the latest saved version. The rules' page shows their name, owner, version and last update, and **Show source** expands the full script. From there anyone can: - **Playtest with these rules**, which opens Playtest with them already picked, - **Save to account** (when signed in), which adds a **Downloaded** copy to their own Settings list. A saved copy stays on the version it was saved from and never changes by itself. - **Update**, when the owner has saved a newer version since, to move their copy to the latest version. In Settings the copy shows **Update available** and has the same **Update** button. A downloaded copy can be switched on and off, viewed, forked and removed, but not edited. **Fork** it to make changes, which creates a private set of your own. Things to know: - A fork always starts private, even when you fork public rules. - Public means the code is public. Don't put anything in a comment or label you wouldn't want others to read. ## Troubleshooting {#troubleshooting} The **Validation** panel in the editor, and Playtest itself when a game can't start, show each problem the table found with the rules. Every problem has a code, listed below with its fix. Most also name the place in the definition, such as `actions[2].shortcut` (the third action's shortcut). The same codes are in the [issue code reference](https://docs.turny.gg/reference/scripting/playtest#issue-codes). ### The script doesn't run #### `script_unsafe` {#script_unsafe} "The rules script uses code that isn't allowed." Playtest rules run in the same locked-down sandbox as custom rulesets and calculators, and a safety check reads every script before it runs or saves. The usual suspects are `var` (use `let` or `const`), globals that aren't on the allowed list (such as `fetch`, `window` or `eval`), `async` / `await`, `class`, `this` and `import`. The full rules are on the [script sandbox](https://docs.turny.gg/reference/scripting/sandbox) page. #### `script_error` {#script_error} "The rules script failed to run." The script threw an error, or it doesn't export a function. Check that it has `export default function playtest(deck, cardsById, ctx)` (or a top-level `function playtest`), and read the message for the error: `Cannot read properties of undefined` usually means a missing card. Guard with `card && card.game` before reading card fields. #### `script_timeout` {#script_timeout} "The rules script took too long to run." A script that runs longer than 5 seconds is stopped. That almost always means a loop that never ends, such as a `while` whose condition never turns false. #### `worker_failed` {#worker_failed} "The rules script could not be run." The background worker that runs scripts crashed or never started. This is not a problem with your script: reload the page. ### The shape is wrong #### `invalid_shape` {#invalid_shape} A field is missing, has the wrong type, or holds a value that isn't allowed, such as `layout: "stack"` or `owner: "player"`. The message names the field. Compare it with the [definition reference](https://docs.turny.gg/reference/scripting/playtest#the-table-definition); every allowed string is listed under [Enums](https://docs.turny.gg/reference/scripting/playtest#enums). Remember that the script must return the definition, not just build it. #### `unsupported_version` {#unsupported_version} The definition's `version` must be `1`. #### `over_cap` {#over_cap} Something is over its limit: too many zones or actions, too many steps in one action, a label that is too long, and so on. The message names the limit. Every limit is listed under [Limits](https://docs.turny.gg/reference/scripting/playtest#limits). #### `invalid_id` {#invalid_id} Ids must start with a letter and use only letters, digits, `_`, `.`, `:` and `-`, and can't be names like `constructor` or `toString`. The same goes for the keys of `initialZones` and `cardTags`. #### `duplicate_zone_id` {#duplicate_zone_id} Two zones have the same `id`. Every zone needs its own. #### `duplicate_action_id` {#duplicate_action_id} Two actions have the same `id`. When you build actions in a loop, make the id include the loop value (for example `"damage" + n`). #### `duplicate_tracker_id` {#duplicate_tracker_id} Two trackers have the same `id`. #### `duplicate_marker_id` {#duplicate_marker_id} Two markers have the same `id`. #### `duplicate_param_id` {#duplicate_param_id} Two params of the same action have the same `id`. #### `duplicate_flag_id` {#duplicate_flag_id} Two flags have the same `id`. ### Something refers to a thing that doesn't exist #### `unknown_zone` {#unknown_zone} A step, predicate, action `zones` list or `initialZones` key names a zone that isn't in `zones`. Check the spelling: ids are case-sensitive. #### `unknown_action` {#unknown_action} A zone's `primaryActionId` or `dropActionId`, or the definition's `roundActionId`, names an action that isn't in `actions`. #### `invalid_round_action` {#invalid_round_action} "The Turn button action must act on a side or the whole game." `roundActionId` names a `card`, `selection` or `zone` action, which the toolbar's **Turn** button has nothing to run on. Point it at a `side` or `game` action, usually your **New turn**. #### `unknown_tracker` {#unknown_tracker} A `tracker` step, or a `{ tracker: "..." }` value, names a tracker that isn't in `trackers`. #### `unknown_marker` {#unknown_marker} A `counter` step or a `counterAtLeast` predicate names a marker that isn't in `markers`. #### `unknown_flag` {#unknown_flag} A `flag` or `clearFlag` step, a `readyAll` `skipFlag`, or a `flag` predicate names a flag that isn't in `flags`. Declare every flag you use. #### `unknown_param` {#unknown_param} A `{ param: "..." }` value names a param the action doesn't declare in its `params`. `setup` has no params, so it can't use `{ param }` at all. #### `param_kind_mismatch` {#param_kind_mismatch} A `{ param }` value is used where its param can't supply the right kind of value, such as a `choice` param of zone names used as a card count. Use a `number` param for numbers, and a `card` param (or a `choice` param of card codes) for the card of a `create` or `transform` step. #### `invalid_tracker_ref` {#invalid_tracker_ref} A `{ tracker, side }` value names a side that doesn't fit the tracker. A shared tracker (`owner: "shared"`) takes no side or `side: "shared"`; a per-side tracker takes `side: "self"` or `side: "other"`. #### `invalid_tracker_toggle` {#invalid_tracker_toggle} A `tracker` step with `toggle: true` needs a tracker that runs from 0 to 1: declare it with `min: 0, max: 1`. ### Steps are combined in a way that can't work #### `nested_block_step` {#nested_block_step} A `forEachSide` or `repeatUntil` step sits inside another one. Block steps hold one level of plain steps only; move the inner block out, or split the action. #### `for_each_side_in_setup` {#for_each_side_in_setup} `setup` already runs once for each side, so it can't use `forEachSide`. List the steps directly. #### `condition_needs_zone_has` {#condition_needs_zone_has} A `repeatUntil` condition tests a card (with `tag`, `flag`, `faceDown` and so on), but there is no card to test. Wrap the card test in a `zoneHas` predicate, as in [Redraw until a condition holds](#recipe-redraw-until). ### The table layout doesn't fit #### `zone_outside_table` {#zone_outside_table} A zone's `area` reaches past the edge of its grid. Side zones, and shared zones with `sharedPlacement: "playerGrid"`, must fit in `table.columns` by `table.rows`; other shared zones must fit in the shared strip (`table.sharedRows` rows). Remember that rows and columns start at 0, so the last column is `columns - 1`. #### `zone_overlap` {#zone_overlap} Two zones in the same grid cover the same cell. Move one, or shrink its `rowSpan` / `colSpan`. A side zone and a shared strip zone never overlap, because they sit in different grids, but a `"playerGrid"` shared zone sits in the side grid and must fit around the side zones. ### A card option or created card can't work #### `card_param_needs_source` {#card_param_needs_source} "Card option needs a cardSource to pick cards from." A param with `kind: "card"` needs a `cardSource`, such as `{ kind: "associated" }`, so the table knows which cards to offer. See [Level up via an associated card](#recipe-level-up). #### `card_source_needs_tag` {#card_source_needs_tag} A `cardSource`'s `where` tests something other than tags, such as `zone` or `faceDown`. Its choices are card codes, not cards on the table, so it can only use `tag` (combined with `all`, `any` and `not`). Tag the cards from `cardsById` and filter on the tag. #### `create_needs_card_target` {#create_needs_card_target} A `create` step has no `to`, or copies `card: "target"`, but its action doesn't run on a card. Only `card` and `selection` actions have a target card to copy or to put the new card beside; `setup` and `side`, `game` and `zone` actions don't. Name a destination zone with `to` and a card code (or a `{ param }`) with `card`. ### A shortcut can't be used #### `invalid_shortcut` {#invalid_shortcut} The shortcut doesn't follow the grammar `[mod+][shift+]`. Write `mod` instead of `ctrl` or `cmd`, and use a key from the [list of keys](https://docs.turny.gg/reference/scripting/playtest#grammar). A `"1-9"` shortcut also needs the action to have a `number` param to receive the digit. #### `shortcut_uses_alt` {#shortcut_uses_alt} The shortcut uses Alt (or Option). Alt is reserved: the table adds an Alt version of every shortcut that acts for the opponent. Pick another key; you get the opponent version for free. #### `shortcut_reserved` {#shortcut_reserved} The shortcut is one the table itself uses: `Mod+Z` (undo), `Mod+Shift+Z` and `Mod+Y` (redo), `?` (the shortcut sheet) or `Escape` (clear the selection). Pick another key. #### `shortcut_conflict` {#shortcut_conflict} Two actions that can apply to the same thing share a key. Two card actions (or two zone actions) may share a key only when their `zones` lists don't overlap, and every side and game action needs its own key. Change one of the keys, or narrow the actions' `zones`. --- url: https://docs.turny.gg/guide/tournaments description: "How Turny.gg runs tournaments: the formats each game offers, multi-stage events and top cuts, Swiss pairings, byes, late entry, tiebreakers, CSV exports, free-for-all scoring, Riftbound multi-deck lineups, waitlists, your personal calendar, recurring events, venue addresses and map pins, the TV display, printing round sheets, announcements, and judges, penalties and deck checks." --- # Tournaments A Turny.gg tournament is one or more **stages** played in order. Each stage has a format (Swiss, single elimination, and so on) and its own settings, and **advancement rules** decide who moves from one stage to the next. This page describes exactly what the tournament engine does with those settings, so you can predict pairings and standings before your event starts. ## Formats ### What each game offers The create form offers these formats and starts every new stage from these defaults. Everything except the match-win % formula and the two floors can be changed per stage, under the stage's **Advanced settings**. | Setting | Cyberpunk TCG | Flesh and Blood | Hearthstone | Legends of Runeterra | Magic: The Gathering | Palworld TCG | Pokémon TCG | Riftbound | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Formats | Single elimination, Double elimination, Round robin, Swiss | Single elimination, Double elimination, Round robin, Swiss | Single elimination, Double elimination, Round robin, Swiss | Single elimination, Double elimination, Round robin, Swiss | Single elimination, Double elimination, Round robin, Swiss, Cumulative Points (Free-for-All), Threshold Win (Free-for-All) | Single elimination, Double elimination, Round robin, Swiss | Single elimination, Double elimination, Round robin, Swiss | Single elimination, Double elimination, Round robin, Swiss, Cumulative Points (Free-for-All), Threshold Win (Free-for-All) | | Swiss: number of rounds | 5, with a recommendation by player count | 5, with a recommendation by player count | 5, with a recommendation by player count | 5, with a recommendation by player count | 5, with a recommendation by player count | 5, with a recommendation by player count | 5, with a recommendation by player count | 5, with a recommendation by player count | | Swiss: points for a win / draw / loss | 3 / 1 / 0 | 3 / 0 / 0 | 3 / 0 / 0 | 3 / 0 / 0 | 3 / 1 / 0 | 3 / 0 / 0 | 3 / 1 / 0 | 3 / 1 / 0 | | Swiss: allow draws | Yes | Yes | No | No | Yes | No | Yes | Yes | | Swiss: bye handling | Award full points (3) | Award full points (3) | Award full points (3) | No byes | Award full points (3) | Award full points (3) | Award full points (3) | Award full points (3) | | Swiss: pairing style | Random within score groups | Random within score groups | Random within score groups | Random within score groups | Random within score groups | Random within score groups | Random within score groups | Random within score groups | | Swiss: prevent repeat matchups | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Swiss: tiebreakers | Opponent match win percentage, then Game win percentage, then Opponent game win percentage | Cumulative match points, then Match loss percentage (lower is better), then Opponent match loss percentage (lower is better), then Opponent cumulative match points, then Random | Opponent match win percentage, then Game win percentage, then Opponent game win percentage | Buchholz | Opponent match win percentage, then Game win percentage, then Opponent game win percentage | Opponent match win percentage, then Opponent-opponent match win percentage | Opponent match win percentage, then Opponent-opponent match win percentage | Opponent match win percentage, then Game win percentage, then Opponent game win percentage | | Swiss: match-win % formula | Match points | Match points | Not set | Not set | Match points | Match points | Wins over rounds | Match points | | Swiss: opponent match-win floor | 33% | None | 30% | None | 33% | 33% | 25% | 33% | | Swiss: game-win floor | 33% | None | None | None | 33% | 33% | None | 33% | | Round robin: points for a win / draw / loss | 3 / 1 / 0 | 3 / 0 / 0 | 3 / 0 / 0 | 3 / 0 / 0 | 3 / 1 / 0 | 3 / 0 / 0 | 3 / 1 / 0 | 3 / 1 / 0 | | Round robin: tiebreakers | Head-to-head, then Score difference | Head-to-head, then Score difference | Head-to-head, then Score difference | Head-to-head, then Score difference | Head-to-head, then Score difference | Head-to-head, then Score difference | Head-to-head, then Score difference | Head-to-head, then Score difference | ### When to use each - **Swiss**: the default choice for open events. Every player plays every round, paired against players on the same record, for a fixed number of rounds. Pair it with a top cut when you need a single winner. See [Swiss](#swiss). - **Single elimination**: one loss and you are out. Fast and easy to follow, which makes it the usual top cut after Swiss. - **Double elimination**: a player is out after their second loss, dropping to the losers bracket after the first. It takes about twice as many rounds as single elimination, in exchange for one bad match not ending anyone's day. **Grand finals** is either a **Single set**, or a **Bracket reset**: if the losers-bracket player wins the first set, a second set decides the title, since both players then have one loss. **Play both brackets at the same time** (on for new stages) starts each round as soon as all its players are known, so the winners and losers brackets play side by side instead of the whole stage moving one round at a time. When you finalize and publish rounds yourself, you choose which of the ready rounds to finalize or publish each time. - **Round robin**: everyone plays everyone, once or twice (**Round robin cycles**). The fairest format for small groups, but the number of rounds grows with the field. For a big field, split it with **Grouping** (a number of groups, or players per group) under the stage's **Advanced settings**, which every one-on-one format offers. - **Free-for-all** (Magic: The Gathering, Riftbound and Teamfight Tactics; Teamfight Tactics offers only free-for-all): three or more players per game, scored by finishing position. See [Free-for-all scoring](#free-for-all-scoring). For single elimination, **Allow byes** is off by default. With it off, the stage only starts when the player count fills the bracket exactly (4, 8, 16 and so on); turn it on to give the top seeds byes into round two. **Hold third-place match** adds a match between the two semifinal losers. The **Seeding method** of an elimination stage (and the **First-round seeding** of a Swiss stage) is one of **Manual**, **Random**, **Rating** or **Prior stage results**. A tournament's first stage defaults to **Random**; any later stage defaults to **Prior stage results**, so the best finishers of the previous stage get the best seeds. ## Multi-stage events and top cut Add a second stage and an advancement rule to turn a Swiss stage into "Swiss plus a top 8". Each rule reads: - **From stage**: the stage whose results it uses. - **Condition**: a **Placement range** (for example 1 to 8) or a **Points range** (for example 9 points or more). - **Action**: **Advance** to a later stage, or **Eliminate**. A classic top cut is one rule: from the Swiss stage, placements 1 to 8, **Advance** to a single-elimination stage seeded by **Prior stage results**. Swiss 1st then plays 8th, 2nd plays 7th, and so on. Advancement uses the earlier stage's final standings, so it happens once that stage is complete. **Cut tiebreaker** decides what happens when players tied on points and on every tiebreaker straddle the cut line (for example 8th and 9th are exactly equal): - **Better initial seed advances** (the default): the cut stays at exactly the size you set. - **Draw lots**: a random draw picks who advances; the cut stays the same size. - **Advance the whole tie**: everyone in the tie advances, so the next stage can get more players than planned. Give it room, for example single elimination with **Allow byes** on. Two options only appear when they apply: - **Allow early cutoff** (a single or double elimination stage, with a placement range starting at 1): the stage stops as soon as the players in the range are decided, instead of playing on to a single winner. Use it for a day-one bracket that only needs to find a top 8. - **Advance mode: Continue brackets** (double elimination into double elimination): the next stage carries on the same bracket where the first one stopped, so every player keeps their winners or losers bracket position. **Reset bracket** (the default) starts a fresh bracket. A tournament is either all one-on-one stages or all free-for-all stages; the two cannot be mixed in one event. ## Swiss ### Pairing Round 1 orders players by the stage's **First-round seeding**, then pairs them by the **Pairing style**. From round 2 on, the engine: 1. Orders players by the current standings: points, then the stage's tiebreakers, then initial seed. 2. Splits them into score groups: everyone on the same points. 3. Pairs each score group from the top. If a group has an odd number of players, its lowest-ranked player drops down and is paired in the next group. **Pairing style** decides who meets whom inside a score group: - **Random within score groups** (the default): random pairings within the group, as in most trading card game events. - **Fold (top half vs bottom half)**: the top half of the group plays the bottom half, 1st against the first player of the bottom half, and so on, as in chess. - **Adjacent standings order**: 1st plays 2nd, 3rd plays 4th, and so on. With **Prevent repeat matchups** on (the default), a pairing that would repeat an earlier match is replaced by the rematch-free pairing that keeps players closest to their own score group. If no rematch-free pairing exists at all, the next round cannot be generated and the organizer sees an error; turn **Prevent repeat matchups** off for that stage, or change its pairing style, both of which stay editable while the stage runs. In a very large, late round the search can give up, and then the engine uses the plain pairing even if it contains a rematch. A Swiss stage ends after its **Number of rounds**. ### Choosing a round count The engine never picks the round count for you: the stage plays exactly the **Number of rounds** you set (default 5). For Magic: The Gathering and Pokémon TCG, the create form also suggests a count for your **Maximum participants**, with an **Apply** button: the Magic Tournament Rules' count for Magic, and the Play! Pokémon handbook's for Pokémon. As a rule of thumb, with no draws, `n` rounds leave at most one undefeated player out of `2^n`. That count finds a clear winner without a top cut. With a top cut, you can often stop a round or two sooner, since the cut decides the winner. | Players | Rounds for one undefeated player | Cyberpunk TCG recommendation | Flesh and Blood recommendation | Hearthstone recommendation | Legends of Runeterra recommendation | Magic: The Gathering recommendation | Palworld TCG recommendation | Pokémon TCG recommendation | Riftbound recommendation | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 4 | 2 | 3 | 3 | 3 | 3 | 4 | 3 | 3 | 3 | | 5 to 8 | 3 | 3 | 3 | 3 | 3 | 4 | 3 | 3 | 3 | | 9 to 12 | 4 | 4 | 5 | 4 | 4 | 4 | 4 | 4 | 4 | | 13 to 16 | 4 | 4 | 5 | 4 | 4 | 4 | 4 | 5 | 4 | | 17 to 32 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | | 33 to 64 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | | 65 to 128 | 7 | 7 | 7 | 7 | 7 | 7 | 7 | 7 | 7 | | 129 to 224 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | | 225 to 226 | 8 | 8 | 9 | 8 | 8 | 8 | 8 | 8 | 8 | | 227 to 256 | 8 | 8 | 9 | 8 | 8 | 9 | 8 | 9 | 8 | | 257 to 384 | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 9 | | 385 to 409 | 9 | 9 | 10 | 9 | 9 | 9 | 9 | 9 | 9 | | 410 to 512 | 9 | 9 | 10 | 9 | 9 | 10 | 9 | 10 | 9 | | 513 to 1024 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | ### Byes With an odd number of players, one player sits out each round. It is the lowest-ranked player who has not had a bye yet; a player only gets a second bye once everyone has had one. Byes are not opponents: they never count toward Buchholz, opponent win percentages or any other opponent-based tiebreaker. **Bye handling** decides what sitting out is worth: - **Award full points**: the bye counts as a match win worth **Points per bye**. - **Award zero points** or **No byes**: the player still sits out, but gets nothing: no points, and the round is not added to their record. ### Late registrants With **Late entry** on (Swiss only), players can still join an event that has started, up to and including the round set in **Allow late entry through round**. Every round already completed when they join counts as a loss for them: they get the points for a loss (0 by default) and the loss appears in their record, but with no opponent, so it adds nothing to anyone's tiebreakers. It is not a bye, so they can still receive a bye later. They are paired from the next round on, like anyone else on their points. ## Tiebreakers Standings rank players by points first. Players on the same points are compared by each applied tiebreaker in order (the **Applied in order** list in the stage's tiebreaker settings), and if they are still equal, the better initial seed ranks higher. Players equal on points and on every tiebreaker share a placement. Percentages are rounded to four decimal places (0.01%) before they are compared. | Tiebreaker | Value | Available in | How it is computed | | --- | --- | --- | --- | | **Head-to-head** | `head_to_head` | Round robin, Swiss | Among players tied on points, the points each one earned in matches against the others in that tie. A player with no one else on their points total scores 0. | | **Score difference** | `score_difference` | Round robin, Swiss | Games won minus games lost, summed over every match played. | | **Game win percentage** | `game_win_percentage` | Round robin, Swiss | Games won divided by games played. In Swiss, a game-win floor set by the game raises any lower value to the floor. A player with no games played scores 0 (or the floor). | | **Points scored** | `points_scored` | Round robin, Swiss | Total games won, summed over every match played. | | **Buchholz** | `buchholz` | Swiss | The sum of the current points of every opponent played. Byes add nothing. | | **Median Buchholz** | `median_buchholz` | Swiss | Buchholz without the single highest and single lowest opponent. With two or fewer opponents nothing is dropped, so it equals Buchholz. | | **Sonneborn-Berger** | `sonneborn_berger` | Swiss | The current points of every opponent the player beat, plus half the points of every opponent they drew with. Losses add nothing. | | **Opponent match win percentage** | `opponent_match_win_percentage` | Swiss | The average of each opponent's match-win percentage (OMW%). Each opponent's value comes from the stage's win-percentage formula and is raised to the game's floor first, if it has one. Byes are not opponents. | | **Opponent-opponent match win percentage** | `opponent_opponent_match_win_percentage` | Swiss | The average OMW% of the player's opponents (OOMW%), weighted by how many opponents each of them has played. That is the average match-win percentage of the opponents' opponents. | | **Opponent game win percentage** | `opponent_game_win_percentage` | Swiss | The average of each opponent's game-win percentage (OGW%), each raised to the game-win floor first, if the game has one. Byes are not opponents. | | **Cumulative match points** | `cumulative_match_points` | Swiss | Cumulative match points (CMP), higher is better: a value from 0 to 1 that weights each round's win (a bye counts as a win) by 2^R - 2^(r-1), where R is the number of completed rounds and r the round, over the sum of those weights. An early win is worth more than a late one, so the earlier a loss, the lower the CMP (Flesh and Blood Tournament Rules and Policy, Appendix A.4). | | **Match loss percentage (lower is better)** | `match_loss_percentage` | Swiss | Match-loss percentage (MLP), lower is better: losses divided by rounds played. A bye is not a round played and a draw is not a loss. A player with no rounds played scores 0. | | **Opponent match loss percentage (lower is better)** | `opponent_match_loss_percentage` | Swiss | The average match-loss percentage of the player's opponents, lower is better. Byes are not opponents; a player with no opponents scores 0. | | **Opponent cumulative match points** | `opponent_cumulative_match_points` | Swiss | The average cumulative match points of the player's opponents, higher is better. Byes are not opponents; a player with no opponents scores 0. | | **Random** | `random` | Swiss | A random order fixed per stage, so it is the same on every read of the stage and for every viewer. Use it last: it breaks any remaining tie. | ### Worked example Five players play a three-round Swiss with 3 points for a win, 1 for a draw and 0 for a loss, byes worth full points, and best-of-three matches. Scores are games won. | Round | Player | Score | Opponent | | ----- | ------ | ----- | -------- | | 1 | Ana | 2-0 | Ben | | 1 | Cam | 2-1 | Dee | | 1 | Eli | Bye | | | 2 | Ana | 2-1 | Cam | | 2 | Eli | 2-0 | Ben | | 2 | Dee | Bye | | | 3 | Ana | 1-1 | Dee | | 3 | Cam | 2-0 | Eli | | 3 | Ben | Bye | | The final standings, with every tiebreaker computed and Head-to-head applied first. Records are wins, losses and draws, and a bye counts as a win. | Rank | Player | Record | Points | Head-to-head | Score difference | Game win % | Points scored | | ---- | ------ | ------ | ------ | ------------ | ---------------- | ---------- | ------------- | | 1 | Ana | 2-0-1 | 7 | 0 | +3 | 71.43% | 5 | | 2 | Cam | 2-1-0 | 6 | 3 | +2 | 62.5% | 5 | | 3 | Eli | 2-1-0 | 6 | 0 | 0 | 50% | 2 | | 4 | Dee | 1-1-1 | 4 | 0 | -1 | 40% | 2 | | 5 | Ben | 1-2-0 | 3 | 0 | -4 | 0% | 0 | | Player | Buchholz | Median Buchholz | Sonneborn-Berger | OMW% | OOMW% | OGW% | | ------ | -------- | --------------- | ---------------- | ------ | ------ | ------ | | Ana | 13 | 4 | 11 | 50% | 71.43% | 34.17% | | Cam | 17 | 6 | 10 | 66.67% | 57.14% | 53.81% | | Eli | 9 | 9 | 3 | 50% | 70% | 31.25% | | Dee | 13 | 13 | 3.5 | 75% | 58.33% | 66.96% | | Ben | 13 | 13 | 0 | 75% | 50% | 60.71% | The opponent percentages above use no win-percentage formula and no floors (the Legends of Runeterra defaults). Working a few of them through: - **Head-to-head**: Cam and Eli are tied on 6 points and met in round 3, which Cam won. Cam scores the 3 points from that match and Eli scores 0, so Cam ranks above Eli. Ana is alone on 7 points and scores 0. - **Score difference**: Ana won 2-0, 2-1 and drew 1-1: 5 games won, 2 lost, so +3. - **Game win %**: Ana won 5 of her 7 games: 71.43%. Eli won 2 of 4 (the bye adds no games): 50%. - **Points scored**: Ana won 2 + 2 + 1 = 5 games, and so did Cam (2 + 1 + 2). - **Buchholz**: Cam played Dee (4 points), Ana (7) and Eli (6): 4 + 7 + 6 = 17. Eli played only Ben (3) and Cam (6), since the bye is not an opponent: 9. - **Median Buchholz**: Cam drops his best opponent (Ana, 7) and his worst (Dee, 4), leaving Eli's 6. Eli has only two opponents, so nothing is dropped and he keeps 9. In a small event with byes this can favor the players who had one. - **Sonneborn-Berger**: Ana beat Ben (3) and Cam (6) and drew with Dee (half of 4 is 2): 3 + 6 + 2 = 11. Dee's only result that counts is his draw with Ana: half of 7 is 3.5. - **OMW%**: with no formula set, a match-win % is wins plus half of draws over matches, with a full-points bye counting as a won match. Ben (1-2-0) has 33.33%, Cam (2-1-0) 66.67% and Dee (1-1-1) 50%, so Ana's OMW% is (33.33% + 66.67% + 50%) / 3 = 50%. - **OOMW%**: Ana's opponents have OMW% of 75% (Ben, 2 opponents), 66.67% (Cam, 3 opponents) and 75% (Dee, 2 opponents). Weighted by opponents played: (75% × 2 + 66.67% × 3 + 75% × 2) / 7 = 71.43%. - **OGW%**: Ana's opponents won 0% (Ben), 62.5% (Cam) and 40% (Dee) of their games: (0% + 62.5% + 40%) / 3 = 34.17%. ### Match-win formulas and floors OMW% and OOMW% average the opponents' **match-win percentages**, and how a match-win % is worked out from a record is set per game: | Formula | Value | How it is computed | Default for | | --- | --- | --- | --- | | **Not set** | | Wins plus half of draws, divided by matches played. A bye that awards full points counts as a won match. | Hearthstone, Legends of Runeterra | | **Match points** | `match_points` | Match points divided by the points for a win times the matches played (Magic Tournament Rules, Appendix C). With 3 points for a win and 1 for a draw, a draw is worth a third of a win. A bye that awards full points counts as a won match. | Cyberpunk TCG, Flesh and Blood, Magic: The Gathering, Palworld TCG, Riftbound | | **Wins over rounds** | `wins_over_rounds` | Wins divided by rounds played (Play! Pokémon Tournament Rules Handbook, section 5.3.3.1). A draw counts as zero wins, and a bye counts as neither a win nor a round played. | Pokémon TCG | Each player's own match-win % in the worked example, under each formula: | Player | Not set | Match points | Wins over rounds | | ------ | ------- | ------------ | ---------------- | | Ana | 83.33% | 77.78% | 66.67% | | Ben | 33.33% | 33.33% | 0% | | Cam | 66.67% | 66.67% | 66.67% | | Dee | 50% | 44.44% | 0% | | Eli | 66.67% | 66.67% | 50% | The formulas disagree most about byes and draws. Under wins over rounds, Ben's only win was his bye, so he has won 0 of his 2 rounds played; Dee drew and lost his two rounds, also 0%. A **floor** raises any opponent's match-win % below it to the floor before averaging, so a player is not punished too hard for opponents who lost every match or dropped early. The game-win floor does the same for Game win % and OGW%. Pokémon TCG uses a 25% opponent floor, and Magic: The Gathering and Riftbound use 33% for both. With each game's defaults, the OMW% in the worked example becomes (Magic: The Gathering has the same defaults as Riftbound): | Player | Pokémon TCG | Riftbound | | ------ | ----------- | --------- | | Ana | 38.89% | 48.15% | | Cam | 47.22% | 62.96% | | Eli | 45.83% | 50% | | Dee | 66.67% | 72.22% | | Ben | 58.33% | 72.22% | For Ana under the Pokémon TCG defaults, Ben and Dee both have 0% and are raised to 25%, so her OMW% is (25% + 66.67% + 25%) / 3 = 38.89%. Without the floor it would be 22.22%. ## Stats win rates {#stats-win-rates} The win rates on stats pages (the meta page and a tournament's **Stats** tab) measure how decks do against each other. They count individual games wherever the results record them, and matches where they don't: many imported events only list match results. The count column next to the win rate says which it counts, **Games** or **Matches**, and an archetype's detail tabs show both. A stats win rate is wins plus a share of draws, over everything played. The share depends on the game: | Game | A draw counts as | | -------------------------------------------------- | ------------------------------------------------------ | | Pokémon TCG, Riftbound, Lorcana, Palworld | Half a win | | Magic: The Gathering, Cyberpunk | A third of a win | | Legends of Runeterra, Hearthstone, Flesh and Blood | No win, though it still counts toward the games played | In Lorcana, Pokémon TCG, Riftbound and Palworld this differs from Swiss. With 3 points for a win and 1 for a draw, a drawn match gives each player a third of a win's points, and the match-win % above follows those points because standings decide who ranks higher. A stats win rate treats the draw as an even result between the two decks: each side gets half, every match adds up to one win between them, and the field as a whole averages 50%. An archetype above 50% is then beating the field. ## Exports Organizers can download an event's data as CSV files, for prize payouts, a store's own records or an official results submission. Open the event's **Administration** tab and choose **Export** in the console. Exports are open to the event's owner, admins and operators; referees don't see the button. | Export | What's in it | Choose | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | | **Participants** | Every registered player: seed, linked game account, status, approval, check-in and registration times, and registration answers | Nothing | | **Standings** | One stage's rankings: points, wins, losses, draws, byes and each of the stage's tiebreakers | A started stage | | **Pairings** | Every match: stage, round, table, players, scores, winner and result | One round, or all rounds | | **Decklists** | Each player's submitted deck codes for one stage, with when they submitted and its validation status | A stage that collects decks | Each file is named after the event and what it holds, for example `friday-night-swiss-standings-stage-1.csv`. The files are UTF-8, so accented player names open correctly in Excel, Google Sheets and Numbers. An export reflects the event at the moment you download it: during a live event, download again after the last round for final standings. ## Free-for-all scoring Magic: The Gathering and Riftbound offer two free-for-all formats. Players are split into **lobbies** (pods), and every match awards **Placement points** by finishing position in the lobby. - **Cumulative Points**: every lobby plays a fixed **Number of matches**, and final standings are total points. Players on the same total share a placement. - **Threshold Win**: matches continue until a player reaches **Points to win** _and_ finishes at the **Required finish** or better in the match where they get there. If several players qualify in the same match, the one with the most points wins. Set **Maximum matches** to cap the stage; if no one has won by then, **If no one wins** decides it (**Highest points wins**). These are the defaults for a new free-for-all stage: | Setting | Magic: The Gathering | Riftbound | Teamfight Tactics | | --- | --- | --- | --- | | Players per lobby | 4 | 4 | 8 | | Placement points | 1st: 8, 2nd: 7, 3rd: 6, 4th: 5, 5th: 4, 6th: 3, 7th: 2, 8th: 1 | 1st: 3, 2nd: 2, 3rd: 1, 4th: 0 | 1st: 8, 2nd: 7, 3rd: 6, 4th: 5, 5th: 4, 6th: 3, 7th: 2, 8th: 1 | | Tie scoring | Competition | Competition | Competition | | Cumulative Points (Free-for-All): number of games | 3 | 3 | 3 | | Threshold Win (Free-for-All): points to win | 20 | 6 | 20 | | Threshold Win (Free-for-All): required finish | 1st or better | 1st or better | 1st or better | With the Riftbound defaults, a win is worth 3 points and the threshold is 6, so a player needs at least two wins to take the stage. In this four-player pod, Ana reaches 7 points in match 3 but finishes 2nd, so she has not won yet. Ben wins match 4 with 9 points; Ana also has 9, but finished 2nd, so Ben takes the stage. | Match | Ana | Ben | Cam | Dee | Result | | ----- | --- | --- | --- | --- | ------------- | | 1 | 1st | 2nd | 3rd | 4th | No winner yet | | 2 | 2nd | 1st | 3rd | 4th | No winner yet | | 3 | 2nd | 3rd | 1st | 4th | No winner yet | | 4 | 2nd | 1st | 3rd | 4th | Ben wins | **Tie scoring** decides what tied players in a lobby earn. **Competition** (the default) gives each of them the points for the tied place: two players tied for 2nd both get 2nd-place points. **Split** shares the points of the places the tie covers: two players tied for 2nd each get the average of the 2nd- and 3rd-place points. **Elimination points**, if set, add points for each opponent a player eliminates. Lobbies are formed by **Lobby seeding** (initial seed, current standings or random) and **Lobby distribution** (snake by default), and **Reshuffle lobbies** decides whether they are redrawn between matches. ## Riftbound lineups Riftbound has no official format for bringing more than one deck, so Turny has its own. When a stage's **Decks to bring** is 2 or more, the create form switches the deck set rule to **Riftbound lineup**. The single-deck rules are refused for these events: **Riftbound deck set** treats every deck as a pile of one deck, and **Single deck** allows exactly one deck, so both would reject every lineup. Each deck must still pass the deck rule (**Riftbound constructed**) on its own. On top of that, **Riftbound lineup** checks the lineup as a whole: - **One deck per Legend**: no two decks can share a Legend. - **3 copies across the lineup**: no more than 3 copies of a card across every deck's main deck and sideboard combined. Runes and Battlefields don't count, so each deck can run its own 12 Runes and reuse Battlefields. The rule never checks how many decks you bring. That comes from the stage's **Decks to bring**. ## Waitlists {#waitlists} When an event with a player cap fills up, players can join a **waitlist** instead of being turned away. The first player in line gets the next seat that opens before the event starts. ### Turn it on or off {#waitlists-setup} The waitlist is on for every event with a **Max participants** cap. To turn it off, clear **Open a waitlist when the event is full** under **Waitlist** in the admissions section of the create or edit form. Without a cap there is nothing to wait for, so the setting doesn't show. Turning it off keeps anyone already in line, and they still move up as seats open, but no one new can join. ### Joining and leaving {#waitlists-players} Once every seat is taken, the event page shows **Full** beside the player count, and the register button reads **Join waitlist**. A player who joins sees their place in line, such as **You're #3 on the waitlist**, and a **Leave waitlist** button. Leaving gives up their place; joining again puts them at the back of the line. The line is private. The event page never shows how many players are waiting, and waiting players don't appear on the roster. ### When a seat opens {#waitlists-promotion} A seat opens when a registered player withdraws or is removed. The first player in line takes it straight away and gets a notification (and an email, unless they turned those off under **Waitlist updates** in their notification settings). If they have the event open, the page updates to say a seat opened for them. Under manual approval, the promoted player still waits for your approval, like any other registrant. If you raise the cap, the new seats go to the players in line before anyone new can register. When the event starts, the waitlist closes: anyone still in line is taken off it and told no seat opened. Late entry has no waitlist. ### Managing the line {#waitlists-manage} Operators, admins and the owner see a **Waitlist** section on the **Players** tab of a capped event before it starts. It lists the line in order, with when each player joined: - **Promote** gives that player a seat now, out of line order, even when the event is full. - **Remove** takes them off the waitlist. Like a removal from the roster, they can't sign up again on their own. Referees don't see the section. ## Your calendar {#calendar} **Calendar** in the menu (shown once you're signed in) puts every event you care about on one calendar, across every game: - events you registered for, including ones where you're on the waitlist; - events you created or help run as staff; - public events from communities you follow; - public events from recurring events you follow (see [Follow a schedule](#recurring-follow)). **Month** is the landing view. **Week** shows the next seven days, then a **Later** list for about four weeks after that. **Today** and the arrows move the calendar; times show in your own time zone, so a late-night event can land on the next day. Events are coloured by your part in them: **Playing** is gold, **Organizing** is teal, and **Following** is a muted blue. When you have more than one kind, chips with those names at the top hide or show each kind, and your choice stays when you switch between Month and Week. A few rows also carry a word: **Waitlisted**, **Staff** when you help run someone else's event, and **Playing** when you also play in an event you organize. Click an event for its status, start time, player count and a link to the tournament. Events from another game show that game's icon and open on its own site. Past events are dimmed and cancelled ones are struck through. A recurring event's dates further out than it [publishes](#recurring-setup) still show, with a dashed outline and the word **Planned**. They follow the schedule's skipped and moved dates. Click one and **Open schedule** takes you to the run's **Schedule** tab; the event itself, and registration for it, open closer to the day. ## Recurring events {#recurring-events} A weekly store night or a monthly championship doesn't need to be created by hand every time. Set an event to repeat and Turny copies it for each date on the **schedule**, publishing every copy a few weeks before it starts so players can find it and register. ### Set up a schedule {#recurring-setup} There are two ways in: - **When you create an event**: turn on **Repeat this event** under the scheduled start. After you create the event, its **Schedule** tab opens in setup mode, filled in from the event's day, start time and name. - **From an event you already run**: open its **Schedule** tab and choose **Set up a schedule**. Only the event's owner and admins see this tab on an event that doesn't repeat yet. Setup has two parts: - **How it repeats**: **Weekly**, **Every few weeks** (every 2, 3 or 4 weeks) or **Monthly** (the first, second, third, fourth or last given weekday of the month), plus the day, the start time and the time zone. - **Names, publishing and series**: - **Publish each event**: 1 to 8 weeks before it starts (4 by default). Registration still opens and closes the way the original event's does. - **Event name**: the name each new event gets. **Add event number** inserts `#{n}`, which counts up from **Next number**, so a run can continue an existing count (for example from #13). **Add date** inserts the event's date. - **Add each event to a series**: each new event joins that series' current season as its own stop. See [Series](https://docs.turny.gg/guide/series). The calendar beside the form previews the next dates before anything is saved. Choose **Start schedule** to begin: the event you set it up from is the first event of the run, and the next ones are published as they come into the publish window. Every new event copies the original event's settings: format, stages, rules, caps and registration times. Start times follow the schedule's own time zone, so an event at 7:00 PM stays at 7:00 PM local when the clocks change. The calendar marks the day the clocks change. ### The Schedule tab {#recurring-schedule-tab} Every event in a run has a **Schedule** tab, and the event page shows previous and next buttons beside the date, with a calendar button that opens the tab. The tab shows: - A month calendar with each date marked **Played**, **Published**, **Publishing now**, **Planned**, **On hold**, **Skipped** or **Moved**. A moved date shows on its new day, with a dashed marker on the day it left. - A panel for the selected date, with its start time in the schedule's time zone and in yours when they differ. - **Coming up**: the next dates, with when each one is published. Players see the same calendar, read only: published and planned dates, skips and moves, but not your notes or dates on hold while a schedule is paused. ### Follow a schedule {#recurring-follow} Once a run has a public event, its Schedule tab shows a **Follow schedule** button in the header. Follow it and every public event in the run shows up on [your calendar](#calendar), including the ones published later, without registering for each one. Press **Following** to unfollow. You need to be signed in; signed out, the button takes you to sign in first. ### Change a date or the schedule {#recurring-edits} Select a date on the calendar to change it: - **Change date or time**: move this date to another day or start time. - **Skip**: take the date out of the run, with a note for yourself (a holiday, a closed venue). Skipped dates don't use up an event number. - **Change how it repeats**: change the day, start time or cadence. Each change asks which dates it applies to, the way a calendar app does: - **This event only**: a one-off change to that date. Moves and skips can be undone from the same panel with **Undo move** or **Bring back**. - **This and following events**: the change applies from that date on. A skip with this choice ends the schedule before that date. Before you save, the choice shows how many dates change and how many published events and registered players it reaches, and the calendar outlines the dates that move. Published events that move keep their registrations, and registered players are told about the new date. Skipping a published date cancels that event, and so can changing how often it repeats when the new dates leave too few slots for the published events. Admins can move dates, but only the schedule's owner can make a change that cancels a published event. ### Change one event's settings {#recurring-event-settings} Editing an event in a run with the regular edit form asks the same question when you save: - **This event only**: only this event changes. It is marked **Changed for this event only** on the calendar, and later changes to the following events skip it. - **This and following events**: later published events get the same settings (they keep their registrations), and events created later copy this one. ### Pause, settings and delete {#recurring-manage} The Schedule tab's header has: - **Pause** and **Resume**: while a schedule is paused, no new events are published. Events already published still run. Dates that pass while it is paused are not created later. - **Settings**: the schedule's name, how far ahead events are published, the event name pattern, the next number and the series. None of these move a date. - **Delete**: the schedule stops. Events already published stay as normal tournaments, and planned dates go with the schedule. My Tournaments lists your schedules under **Schedules**, with their next dates and a **Pause** or **Resume** button. **Manage** opens the Schedule tab. ## Venue address and map pin {#venue-location} An in-person event takes place at one of your saved venues. Create and edit venues under **Settings > Venues**, then pick one when you set up the event. - **Address**: start typing the street address or the store's name and pick the right suggestion. A suggestion fills in the address, city, region and country, and places the map pin for you. When nothing matches, type the address yourself and drop the pin by hand. - **Address line 2**: the floor, suite or room, so players find the door. - **Map pin**: the venue's exact spot. **Adjust pin** lets you drag it onto the right building. **Drop a pin** opens the map so you can click where the venue is, and **Use my location** places it where you're standing, handy when you set the venue up on site. **Remove pin** clears it. The pin is what makes your events findable nearby. **Near me** and the area search on the tournaments list measure distance from the pin, so an event at a venue without one never shows up there, even though its address still shows on the event page. Set the pin once per venue and every event you run there is covered. Address suggestions are built on OpenStreetMap data, so the event page credits OpenStreetMap under a pinned venue's address. ## TV display The **TV display** button in the organizer console opens a full-screen board for a screen at the venue. Only the event's organizers can open it. Put it on the TV, press **Fullscreen**, and leave it: the board follows the event on its own. ### What the board shows The top bar carries the event name, the format, the round and the field size, the time of day and a live light. Along the bottom, a results crawl lists each result as it is reported. The main panel depends on where the event is: - **During a round**: that round's pairings. Up to 24 pairings are listed by table number. A bigger round lists every player A to Z with their table and opponent, so players look for their own name. - **Between rounds**: the standings, with the finished round's results beside them. - **After the stage**: the final standings. - **Elimination stages**: the round's pairings, like Swiss, with **Up next** beside them showing the next round's matches ("Winner of #3"), which fill in as results arrive. Once the rest of the bracket fits the screen at full size, the bracket replaces the pairings. Lists never scroll. Rows are sized to fit the screen, and when they don't all fit, the list turns pages every few seconds, with a progress bar showing which page is up. The right column holds the round clock, the top of the standings (as many rows as fit) and a QR code that opens each player's own match page on their phone. ### The round clock The clock counts down to the end of the round and is the largest thing on screen. It turns amber in the last 5 minutes. When you pause the round timer from the console, the clock shows **Paused** and holds its time. At zero it turns red and shows **Time** with how far over time the round is. A stage without a round timer shows how many results are in instead. ### The live light The light reads **Live** while the board is connected and receiving updates, and **Reconnecting** as soon as the connection drops. After 15 seconds without a connection it reads **Offline** with the time of the last update, and the clock stops at the last time it was sure of, because a pause or time change made meanwhile can't reach the board. Everything catches up when the connection returns. ### Following the event The board shows the active stage's latest published round. Draft pairings stay off the screen until you publish them. When you publish a new round or start the next stage (a top cut, for example), the board switches to it within a second, with no reload. If you picked an earlier round or another stage from the toolbar, publishing the next round puts the board back on the live one. ### The toolbar Move the mouse over the board to show the toolbar; it hides again after a few seconds. It holds: - **Stage** and **Round**: show another stage or round. - **Pairings**: **Auto** (by table up to 24 pairings, A to Z above that), **By table** or **A to Z**. - **Page every**: how long each page of a long list stays up (8, 12, 20 or 30 seconds). - **Zoom**: makes rows larger or smaller. - **QR card** and **Show QR now**: see below. - **Dark** or **Light**: dark suits a dimmed hall, light a bright one. - **Fullscreen**. The board remembers these settings in the browser it runs in. ### The QR card Every 5 minutes, a full-screen card with a large QR code takes over the board for 15 seconds, with the round clock still on it, so players arriving late can find their match. Change how often it appears under **QR card** (every 2, 5 or 10 minutes, or off), or put it up straight away with **Show QR now**. The card is skipped while the round is over time, when the clock matters more. ## Printing {#printing} The **Printable view** button (the printer icon) in the organizer console opens the **Print kit** in a new tab: the sheets you hand out or pin up at a venue, for one round at a time. Only the event's organizers can open it. The same page is the display page's **Print** mode, next to **TV**. The setup panel walks you through four steps, with a page-accurate preview of every sheet beside it. ### Round {#printing-round} Pick the **Stage** and the **Round** to print. The kit starts on the active stage's latest round. ### Sheets {#printing-sheets} Tick the sheets you need. Each one says who it is for, and how many pages it will print once selected. | Sheet | For | What it is | | --------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Pairings by name** | Post on the wall | Every player A to Z with their table, seat, opponent and points. Players find their name, then their table. Seat A sits on the left, and a star marks a feature table. | | **Pairings by table** | Scorekeeper | Every table in order, with a box to record results called in. | | **Match slips** | Cut and hand out | One slip per match, for the players to fill in game by game and sign. Byes and seats still waiting on a result get no slip; the sheet lists the byes instead. | | **Standings** | Post on the wall | Rank order with the stage's tiebreakers, as of the snapshot. | | **Bracket** | Post on the wall | The elimination tree. A large bracket is scaled down or split into parts, and each part says which rounds it covers. | | **Decklist** | Judges only | One page per player: their seat this round, when they submitted, whether the list passed validation, the deck code and the cards, plus a deck check box for the judge to fill in. | Not every sheet fits every stage. **Standings** is for Swiss and round robin stages only, **Bracket** for elimination stages only, and the two pairing sheets and the match slips for one-on-one stages only, so a free-for-all stage prints standings and decklists. A sheet the stage can't print is greyed out with the reason. **Quick picks** select a set of sheets in one click, keeping only the ones the stage supports: - **Round kit**: pairings by name, pairings by table and match slips. Print it at the start of every round. - **Wall**: pairings by name, plus the standings in a Swiss or round robin stage, or the bracket in an elimination stage. - **Judge pack**: pairings by table, standings and decklists, for the judges' station. ### Report QR {#printing-qr} With match slips or pairings by name selected, a **Report QR** switch appears. When it is on (the default), every match slip carries a code, eight slips to a page, and the pairings by name sheet carries one too ("Scan to report your result"). The code opens the event page, where each player reports from their own match panel. Turn it off for ten slips to a page and no codes. ### Check {#printing-check} Before the **Print** button unlocks, the kit loads every player in the round, then takes a snapshot and shows its time. It warns you when: - the round is still being played, so results reported after the snapshot are not on the sheets; - the round has not started yet; - the round has no physical tables, so sheets show match numbers instead; - some players have no decklist on file, or your staff role cannot read decklists; - results changed after the snapshot. Press **Refresh snapshot** to take a new one. ### Print {#printing-print} Press **Print N pages**. In the browser's print dialog, use Letter or A4 paper, **Default** margins, 100% scale, and turn headers and footers off. Every page carries its own header (event, stage, round and the time it was printed) and page number, so a loose page is never a mystery. The stage, round, sheets and the Report QR setting are kept in the page's address, so a bookmark or a link to a colleague opens the same selection. ## Announcements {#announcements} Organizers can send a short message to the players of an event: a room change, a delayed round, a reminder before check-in closes. Announcements are private. Only the players they go to and the event's staff can read them, so they never appear on the public event page. ### Send an announcement {#announcements-send} Owners, admins and operators find **Send announcement** on the event's **Announcements** tab, right after Overview. Choose who it goes to: - **Players still in** (the default): every registered player who hasn't withdrawn or been disqualified and, once the event is running, isn't knocked out. Before the event starts this is everyone registered. - **All registered players**: includes players already knocked out. - **Specific players**: a private note to the players you pick. Each option shows how many players it reaches right now. Who receives an announcement is fixed when you send it, so a player knocked out later keeps the ones they already got. Every announcement shows up in the app. You also choose: - **Email**: sends a copy to each player who gets announcement emails. - **Post in the event's Discord channel**: shows only when the event has a working Discord webhook, and everyone in that channel can see the post. Not available for specific players. - **Pin it**: keeps it at the top of every player's list. An event has one pinned announcement at a time, so pinning a new one replaces the old pin. Announcements to specific players can't be pinned. An announcement can be up to 1,000 characters. **Review** shows how it will look on the Announcements tab, as a notification and as an email before you send it. ### Read receipts, edits and deletes {#announcements-manage} The Announcements tab lists every announcement the event has sent, with who it went to and how. **Read by N of M** opens the names of the players who haven't read it yet, with a button that sends a new announcement to just those players. - **Edit** changes the text. Edits don't notify anyone again, and emails and Discord posts already sent keep the original text. Players see an **Edited** marker. - **Pin** and **Unpin** move the pin. - **Delete** removes the announcement for every player. Emails and Discord posts already sent stay where they are. ### What players see {#announcements-players} Registered players who still count see the **Announcements** tab, with a badge for unread ones. Spectators don't see the tab. The pinned announcement comes first, then the newest. An announcement counts as read once it has been fully on screen for 8 seconds, and **Mark all read** clears the rest. While a player has unread announcements, the other tabs show a banner that opens them. Each announcement also arrives as a notification. Opening it from the notification bell jumps to that announcement, and reading it in either place marks both read. In-app announcements are always on; players can turn off the email copies under **Organizer announcements** in their notification settings. ## Judges, penalties and deck checks {#judging} Event staff run the floor from **floor mode**, a phone-sized page built for walking between tables. Open it with **Floor mode** in the organizer console. Referees and everyone above them can use it. ### Staff roles on the floor {#judging-roles} - **Referees** issue warnings, game losses and match losses, and run deck checks. They can revoke a penalty they issued themselves, except a disqualification. - **Operators**, **admins** and the **owner** can also disqualify a player and revoke any penalty. - Removing a player from the roster (a drop or a no-show) is separate from a disqualification: it records no penalty and needs an operator or above. ### Floor mode {#judging-floor-mode} Floor mode has four tabs, and each one has its own address, so a judge can keep one open on a phone: - **Tables**: every table of the current round, with both players. A gavel and a count mark a player who already has penalties at this event, a bell marks a table where a player called a judge, and finished tables are dimmed. Type a table number or part of a name into **Table or player** and press **Go** to jump to it. - **Deck checks**: random deck checks for the round (see below). - **Log**: every penalty at the event, newest first and grouped by round. Filter by kind (**W**, **GL**, **ML**, **DQ**) or tap a player's name to see only theirs. Revoked penalties stay in the log, struck through, with who revoked them and why. - **Console**: the full organizer console, the same as the Administration tab. Opening a table shows its score, including any games already given by a penalty, each player's penalties at this event and a **Penalty** button for each player. When a player calls a judge, **Judge call** on the table opens the match chat, and the chat links back to the table in floor mode. ### Issue a penalty {#judging-penalties} **Penalty** opens the penalty form. Earlier penalties for that player at this event are listed at the top. 1. Pick the **Infraction**. The list is the same for every game: tardiness, slow play, procedural error, game rule violation, decklist problem, communication, outside assistance, unsporting conduct, cheating and other. Each one starts at its usual penalty, which you can change. 2. If the player already has an active penalty for the same infraction, a line such as **Repeat of Warning R2** appears with a button for the next penalty up. It is a suggestion only. 3. Pick the **Penalty**: warning, game loss, match loss or disqualification. For a game loss, match loss or disqualification the form shows the match **Score** before and after. 4. Add **Details** the player will see, and an optional **Staff note** that only staff see. For a disqualification the details become the required reason. A match loss and a disqualification need a second tap to confirm. After issuing, a message offers **Undo**, which revokes the penalty straight away. How each penalty changes the match: - A **warning** is recorded and changes nothing else. - A **game loss** gives the opponent the next game of the match, and the match carries on. Players then report only the games they still play: after a game loss, a 2-0 report reads as 2-1 overall. A game loss that brings the opponent to the games needed to win ends the match. - A **match loss** ends the match as a win for the opponent. - A **disqualification** removes the player from the event and forfeits their open matches. - A penalty issued after the match is finished is only recorded; it doesn't change the result. Revoking a game loss or match loss before the next round is paired undoes its effect on the score. After that, revoking only marks it in the log, and staff fix the result with the match override. ### Deck checks {#judging-deck-checks} On the **Deck checks** tab, set how many tables you want and press **Pick N at random**. The pick skips tables whose match is already finished and tables where a player has already been checked at this event, so the same player isn't checked twice. When fewer tables qualify, you get fewer. To check a specific table instead, open it and press **Deck check**; it is recorded as the judge's choice. Tap a player on a picked table to see their registered list next to the verdict: - **OK** records the check. - **Issue** needs a note saying what's wrong. **Issue penalty for this** then opens the penalty form with **Decklist problem** and a game loss already filled in, and links the penalty to the check. Every check at the event is listed below the picked tables, with the round, table, verdict and any linked penalty. ### What players see {#judging-players} Penalties never appear on the public event page. A player sees their own penalties at the event in a **Your penalties** card below **Your match**: the kind, the infraction and the round, and whether it was revoked. They never see the staff note, which judge issued it or why it was revoked. When a game loss or match loss changes a match, both players see one line in their **Your match** card, such as "Game 1 to Zoe Quinn", with the games of the match below it and the penalty game locked. The opponent learns only the effect on the score, never the infraction. --- url: https://docs.turny.gg/guide/series description: "How Turny.gg series work: seasons, stops and divisions, how season points and best-N counting add up, ties and qualifying spots, where series show up, and how organizers run one." --- # Series A **series** ties tournaments together into **seasons**. Each tournament in a season is a **stop**, every finish at a stop earns season points, and a running table shows who leads. A season can build toward a **finale** with qualifying spots, pay out a reward, or simply keep going. A store's weekly league, a community cup and a circuit of official events are all series. ## The parts of a series {#parts} - **Series**: the name, game and organizer. A series belongs to one game, and one organizer runs it. - **Season**: one run of the series with its own schedule, points table and standings. A new season starts the table from zero; earlier seasons stay viewable from the **Season** picker. - **Stop**: one date on a season's schedule. A stop is either a tournament on Turny or an **announced** date with no event on Turny yet. - **Division**: a separate field with its own standings, such as Masters, Seniors and Juniors, or a single Open division. At each stop, every division plays its own tournament. Divisions are always scored separately and never merged; switch between them with the **Division** picker. A tournament can be a stop in more than one series. Each series scores it with its own points table. ## For players ### How points work {#points} The **Scoring** tab shows the season's **Points per finish** table: each finish (for example #1, or #5 to #8) is worth a set number of points. Finishes below the table earn nothing. Some stops are **majors**, marked with a multiplier such as **2x points**. Every finish at a major is worth the table's points times the multiplier, rounded to a whole number. Points only count once a stop is finished. A stop that is live or upcoming adds nothing yet. ### Best results only {#best-results} A season can count only your best few stops, for example "Only your best 4 stops count". Your total is the sum of your best results, and any extra results still show on your **Season path**, struck through and marked **Not counted**. Playing another stop can only raise your total: a weaker finish is simply not counted. If the season counts every stop, every result is added. For example, with best 3 counting, a player who scores 100, 60, 40 and 25 points at four stops has a total of 200. The 25 stays on their path, struck through. ### Standings and ties {#standings} The **Standings** tab ranks every player who has scored in the season. Players are ordered by: 1. Points. 2. Best single finish (a #1 beats a #2). 3. Most stops scored. Players on equal points and an equal best finish share a rank. Click a player to open their season path: their result at every stop, with any points that were not counted. A large series shows the top 100 first. **Show more** loads the next 100, and **Find a player** searches the whole table. Players who entered without a Turny account only score at that one event. Their results at different stops are not added together, even under the same name, so make an account and enter each stop with it. ### Qualifying spots {#qualifying} A season can give the top players of each division a spot, for example "Top 8 qualify" for the finale. Qualifying players are marked **Qualifies** in the standings. If several players share the last qualifying rank, all of them qualify, so a tie is never split. Some seasons have no qualifying spots at all: the table itself is the result. The **Still on the table** figure is the most points one player could still add from the stops left to play. It tells you whether a gap can still be closed. There are no "clinched" or "eliminated" labels: compare the gap with that figure yourself. ### Finales, rewards and open seasons {#season-endings} A season ends in one of three ways: - **Finale**: a closing event, with a name and a date, that the qualifying players are invited to. Once the finale is played on Turny, each player's finale finish shows in the standings. - **Season reward**: a prize instead of a finale, such as store credit or a trophy for the top players. - **Open-ended**: a league with no last stop. The table keeps running as new stops are added, and the season shows its stops "so far" instead of counting down to an end. New seasons start open-ended; the organizer turns that off once the season has a last stop. A season can combine these, for example an open-ended league that still pays out a reward. ### Where you see series {#where} There is no series entry in the menu. You reach a series from the tournaments it covers: - **Tournament page**: a strip above the tournament shows which stop it is, what the winner earns, and a link to the season standings. Its track has a dot for each nearby stop, marked completed, live, announced or cancelled from its event: hover one for its name, date and state, or click it to open that stop's tournament. The flag at the end opens the finale (or the schedule, until the finale event is linked). In a long season, the count at either end of the track opens the full schedule. - **Tournament list**: tournament cards that are stops show the series and stop number. The **Series** button at the top of the list opens the series list. - **Series list**: every public series for the game, with its organizer, current season, stops played, next stop and finale. The series with the soonest next stop or finale comes first. - **Profile**: the **Series** block in a player's **Played** tab shows each series they scored in, with their rank and points. - **Series page**: the **Standings**, **Schedule**, **Calendar** and **Scoring** tabs. **Schedule** lists every stop as **Played**, **Live now**, **Upcoming** or **Announced**, with links to sign up for upcoming events. **Calendar** shows the season's stops month by month. ## For organizers ### Create a series {#create} Start a series from **Your series** on My Tournaments. Give it a name, pick its game and choose who can see it: - **Private**: only you. - **Unlisted**: anyone with the link. - **Public**: it also shows on its tournaments' pages, on the tournament list and in the series list. A new series opens on its **Manage** tab with one **Open** division and a first season. Divisions, stops and seasons are all set up there. Your series are listed under **Your series**, and only the organizer sees **Manage**. ### Divisions and seasons {#divisions-and-seasons} Every series starts with one **Open** division. Under **Divisions** on the **Manage** tab, rename it, add one for each separate field you run (for example Masters, Seniors and Juniors) and put them in order. A stop links one tournament per division, so a stop with Masters and Juniors links two tournaments. Each season has its own settings, top to bottom on **Manage**: - **Stops**: the season's schedule. - **Points table**: finish bands, each worth a number of points. - **Stops that count**: **All of them**, or the best few. - **Open-ended season**: on for a new season. Turn it off once the schedule has a last stop. - **Has a finale**: turn it on to name the finale, give it a date, pick the finale event for each division and set each division's **Qualifying spots**. Turning it off clears all of that. - **Season reward**: a prize, with or without a finale. Start a new season with **New season** when you want a fresh table. Changing the points table or the stops that count updates the standings right away, played stops included. ### Stops {#stops} Under **Stops** on the **Manage** tab, stops are listed in date order. Change a stop's date to move it in the schedule. To add a stop, give it a name, a date and a points multiplier. The multiplier is 1x for a regular stop; raise it for a major. It applies to every division at that stop. A new stop is **announced** until you link its events. On the stop's row, use **Pick an event** for each division and search by name to find the tournament. In a series with one division that is a single tournament; with Masters and Juniors, it is one tournament each. You can add the stop before its events exist on Turny and link them later, once you have created them. You can also link a new event while you create it: in the create form, pick the series and the division under **Part of a series**. The form shows where the event lands in the season and what its winner earns. Once the event is created, it joins the stop on that date if that division's spot is free, or a new stop is added for it. ### Which tournaments you can link {#linkable-tournaments} You can link: - Tournaments you created, or that you are staff on. - Imported official events that are not private. The tournament must be for the series' game. A tournament can only be linked once in a season, but it can be a stop in several different series. ### Choosing a points table {#points-tables} A few tips: - Pay points deep enough to reward a good day, not just the winner. A table that pays the top 8 of a 16-player store event keeps half the field in the race. - Use bands for finishes that are hard to separate, such as #5 to #8 in a top-8 bracket, so a coin-flip quarterfinal does not swing the season. - Use a multiplier for a few bigger stops, rather than a second table. - Count the best few stops in a long season, so missing a week does not knock a player out of the race. --- url: https://docs.turny.gg/guide/communities description: "How Turny.gg communities work: one page for a store, play group or team, the Owner, Admin and Host roles, inviting your staff, hosting tournaments and series under the community's name, and changing or deleting it." --- # Communities A **community** is one page for a store, a play group or a team. It lists the events and series the community hosts, its staff and regulars, its recent champions and its stats. The same page shows on every game site, so a store that runs several games has one address for all of them: `turny.gg/communities/
`. Choose **Follow** on a community's page to hear about its new events. Its public events also show up on [your calendar](https://docs.turny.gg/guide/tournaments#calendar). ## Kinds of community {#kinds} Pick the kind that fits when you create it. You can change it later. - **Store**: a shop with a place to play. A Store can post its **opening hours**, and its page shows whether it's open right now and what's on this week. - **Play group**: friends, a league or a Discord that plays together. - **Team**: a team or org that competes together. ## Start a community {#create} Go to **My Tournaments** and choose **Start a community** in the **Communities** section. Fill in: - **Name** and **Page address**. The address follows the name until you edit it, and the form tells you right away whether it's free. - **Kind** and **Games**. Pick every game you run; players filter the page's events by game. - **Tagline** and **About**, shown in the page header and sidebar. - **Home venue**: one of your saved venues, or none for an online community. Each event still picks its own venue. - **Logo**, **Banner** and **Colour**. Images are uploaded to Turny (JPEG, PNG or WebP, up to 5 MB); links to images on other sites aren't accepted. Without a banner the header uses your colour. - **Links** to your website, Discord, X, Instagram, YouTube and Twitch. A handle like `@arcanegames` or a domain like `discord.gg/yourserver` is turned into a full link. - **Opening hours** (Stores only). Each day is open or closed. Hours use the home venue's time zone, so a Store needs a home venue to post them. A preview beside the form shows the page header and how your events will look in lists. You become the community's **Owner**. ## Roles {#roles} | Role | What they can do | | ----- | -------------------------------------------------------------------------------------------------- | | Owner | Everything: edit the page, manage members (including other Owners), delete the community. | | Admin | Edit the page and the member list. Co-organizer on every event and series the community hosts. | | Host | Host events and series under the community's name, with staff rights only on the ones they create. | Owners and Admins automatically run every event the community hosts as co-organizers, without being added to each event's staff. Only an Owner can add, change or remove an Owner, and a community always keeps at least one Owner. ## Manage a community {#manage} Owners and Admins see a **Manage** tab on the community page. It has three parts: - **Profile**: the same fields as when you created it. Changing the **Page address** keeps the old one working: anyone who opens it lands on the new address, and the form lists your old addresses. An old address stays reserved for your community. - **Members**: invite people, change roles, remove members or cancel invites, and leave. A guide below the list explains each role. - **Delete community** (Owners only): type the community's name to confirm. The page goes away, and its events and series stay up, hosted by the people who created them. ### Invite your staff {#invites} In **Members**, type a username and pick the person from the list, or type an email address to invite someone who doesn't have an account yet. Choose their role and select **Invite**. The invitee gets a notification that opens the community page, where they choose **Accept** or **Decline**. An invite gives no rights until it's accepted. Open invites also show in the **Communities** section of their **My Tournaments**. ## Host under a community {#host} Every member can host under the community's name. On the tournament create form, **Host as** offers **Myself** or any of your communities; **Host an event** from the community page or from **My Tournaments** opens the form with that community already chosen. When a community hosts an event: - the event shows the community's logo and name, and is listed on the community's page; - the community's Owners and Admins can run it with you. To move an existing event, open it in the editor and change **Host as**. Moving an event onto a community needs any role there; taking it off needs the event's Owner or a community Admin. Series work the same way: **Host as** in the new series dialog lists your communities, and the community's Owners and Admins can manage a series it hosts. ## Deleting your account {#account-deletion} If you're the only Owner of a community, your account can be deleted as long as someone else can take over: the longest-standing Admin becomes the Owner. If the community has no Admin, deleting your account is refused until you make someone an Owner or Admin, or delete the community. --- url: https://docs.turny.gg/guide/deck-builder description: "Import and export decks in every format the deck builder reads, organize them into piles and templates, and read its validation messages." --- # Deck builder The deck builder reads the deck codes and text lists players already share, splits a deck into piles when the game has zones, and checks the deck against your rulesets as you build. This page covers every import and export format per game, how piles and templates work, and what the builder's validation messages mean. ## Importing and exporting To import, paste a deck code or a deck list into an empty deck's **Import a deck** box, or press **Import** in the deck panel's footer on a deck that already has cards (on a phone, open the deck with the **Build or Import** button first). The builder tries each format its game accepts, in the order listed below, and reads the first one that works. On an empty deck a clean list imports straight away. On a deck with cards, the import sheet asks what to do: **Replace deck** swaps the deck for the pasted list, and **Add to deck** adds the list's copies to the cards already there. With **Multi Pile** on and the piles set to **Single Deck**, a list that carries zones (a Riftbound deck, an MTG list with a sideboard) is sorted into its piles either way: Replace empties the pile you pasted into and every pile the list fills before importing, and Add puts each zone's cards on top of its pile, so a pasted sideboard still reaches the Sideboard pile. Each option shows the card count the pile is left with. Add keeps the deck's name; Replace takes the pasted deck's name when it has one. A list line the builder cannot read, or a card it cannot find, is skipped, and the sheet lists every skipped line with its line number before you import, so nothing disappears silently. For Pokémon, a line whose exact printing is missing but whose card name matches one card is imported as another printing of that card, and the sheet lists it as `: imported as ` under its own heading. **Edit list** takes you back to the pasted text. If a pasted list reads as a deck list but none of its lines can be imported, the sheet says nothing could be imported and lists every failed line; text that isn't a deck code or list at all shows the general "could not be read" error instead. To export, open **Deck Preview** (the eye button). **Share** copies a link to the deck's page (`//decks/`) built from the game's Turny.gg deck code. Next to it are **Copy deck list** and, for Riftbound, **Copy deck code**. A shared link opens without an account, and **Open in deck builder** on the deck's page loads it back into the builder. The **Maybeboard** pile is never exported. Whether a sideboard keeps its place depends on the format; the notes under each game say which formats carry one. ### Legends of Runeterra The builder reads the standard Legends of Runeterra deck code, the same code the game client and other LoR sites use. ```text CEAQ2AIAAEDASCYMCQKRUJZNFY2TOAABAEAQABY ``` - **Share** links to the deck code, and **Copy deck list** copies the code itself. - The builder also opens a code from its address: `/en/deck-builder/`. - LoR has no sideboard. If a pile is marked **Sideboard**, its cards are added to the shared code with the rest of the deck. ### Pokémon TCG The builder reads two formats, tried in this order: 1. **Turny.gg deck code** (`PTCG1`). Pokémon TCG has no official deck code, so Turny.gg uses its own compact, link-safe one. Cards are grouped by set, and each entry is `x`, or just `` for a single copy. ```text PTCG1.me55:4x66,4x128.sv8:2x76.sv8pt5:4x105.sve:2x4,4x5 ``` 2. **Pokémon TCG Live deck list**: the plain-text list the game client exports, one ` ` line per card. ```text Pokémon: 6 4 Mew ex 30C 66 2 Latias ex SSP 76 Trainer: 8 4 Crispin PRE 105 4 Ultra Ball 30C 128 Energy: 6 4 Basic {P} Energy SVE 5 2 Basic {L} Energy SVE 4 ``` The import is forgiving. Section headers, blank lines and a `Total Cards: 60` line are ignored, and `4x` works as well as `4`. Set codes are the Pokémon TCG Live abbreviations (`PAL`, `SSP`) and are not case-sensitive. Basic Energy lines may leave out the set and number, as Pokémon TCG Live does (`4 Basic {P} Energy` or `4 Basic Psychic Energy`). A list that lost its line breaks on the way (a common phone paste problem) is split back into lines when every card in it can be found. - **Share** links to the `PTCG1` code. **Copy deck list** copies a Pokémon TCG Live list, which pastes straight into the game client. - The builder also opens a code from its address: `/en/deck-builder/`. - Neither format has a sideboard. If a pile is marked **Sideboard**, its cards are added to the shared code with the rest of the deck. ### Riftbound The builder reads four formats, tried in this order: 1. **Turny.gg deck code** (`RIFT1`). The same grammar as `PTCG1`, with upper-case set codes. The Legend, Runes and Battlefields need no zone of their own, since a card's type decides its zone. A `CH` segment names the [Chosen Champion](#riftbound-chosen-champion), a card that is also in the main deck, and is left out when there is none. A `CS` segment after it carries [Neeko's Legends](#riftbound-neeko-legends), left out when there are none. The sideboard follows an `SB` segment at the end. ```text RIFT1.OGN:6x042-298,3x043-298,3x045-298,3x064-298,6x166-298,205-298,259-298,282-298,289-298,293-298.CH.OGN:205-298.SB.OGN:2x050-298 ``` 2. **Piltover Archive deck code**: the community code that [Piltover Archive](https://piltoverarchive.com), Rift Atlas and Tabletop Simulator read. Cards resolve by set and collector number, so any printing of a card loads it. The code carries the Chosen Champion and Neeko's Legends too. ```text CQAAAAAAAAAACAQFAAAQEAIFAAAACAYAAAACWABNABAAAAIFAAAABTIBACBQEAE2AIAKCAQAUUBAAAIBAAAAAMQAAEAAAAGNAE ``` 3. **Piltover Archive deck list**: Piltover Archive's plain-text list, with cards named but not numbered. The card under `Champion:` joins the main deck as your Chosen Champion, and `Sideboard:` goes to the sideboard. ```text Legend: 1 Yasuo, Unforgiven Champion: 1 Yasuo, Windrider MainDeck: 3 Charm 3 Defy 3 Wind Wall Battlefields: 1 Monastery of Hirana 1 Targon's Peak 1 The Grand Plaza Runes: 6 Calm Rune 6 Chaos Rune Sideboard: 2 Rune Prison ``` Names match with either subtitle separator, so `Yasuo, Unforgiven` and `Yasuo - Unforgiven` are the same card. 4. **Turny.gg deck list**: the ` ` list Turny.gg exported before it switched to Piltover Archive's list. It still imports, so older lists keep working, and any printing's set and number loads the card. ```text Main Deck (10) 3 Charm OGN 43 3 Defy OGN 45 3 Wind Wall OGN 64 1 Yasuo - Windrider OGN 205 Runes (12) 6 Calm Rune OGN 42 6 Chaos Rune OGN 166 Legend (1) 1 Yasuo - Unforgiven OGN 259 Battlefields (3) 1 Monastery of Hirana OGN 282 1 Targon's Peak OGN 289 1 The Grand Plaza OGN 293 ``` The four samples above are the same deck; the Turny.gg deck list leaves out the sideboard and the Chosen Champion because it has no place for them. - **Share** links to the `RIFT1` code, sideboard, Chosen Champion and Neeko's Legends included. - **Copy deck list** copies a Piltover Archive list, sideboard included, with the Chosen Champion under `Champion:` and one fewer copy of it under `MainDeck:`. The list has no place for Neeko's Legends, so it leaves them out. - **Copy deck code** copies a Piltover Archive code, sideboard, Chosen Champion and Neeko's Legends included. - The exports carry the champion you starred, or the only candidate when there is just one. A deck with several candidates and none chosen exports without a Chosen Champion. - `RIFT1`, the Piltover Archive code and the Piltover Archive list all carry a sideboard, and on import it lands in the **Sideboard** pile. In a single-deck layout (**Pile View** off) there is no sideboard pile, so the builder leaves the sideboard out and tells you how many cards it skipped. - A Piltover Archive code can name Neeko's Legends for a deck with no Neeko in it. The deck imports without them, and a notice names the Legends it skipped. - Pasting into any pile's **Import a deck** box sorts the cards into the Legend, Rune Deck, Battlefields, Main Deck and Sideboard piles by type, so there is no need to paste into each pile. ## Piles and deck sets A simple deck is one list of cards. Turn on **Multi Pile** to split the builder into several **piles**, and **Pile View** to lay them out side by side in columns. Riftbound opens in Pile View because a Riftbound deck has zones; Legends of Runeterra and Pokémon start as a single deck. ### Pile settings Each pile's settings (the gear on the pile) hold: - **Deck name**: an optional label for the pile. - **Deck rule**: the rule that checks this pile on its own. See [Zone rules and the whole-deck rule](#zone-rules-and-the-whole-deck-rule). - **Role**: at most one of these, or none for an ordinary pile. - **Sideboard**: the pile is the side deck. Its cards are checked as the sideboard, stay out of the main deck count, and go in the deck code's sideboard where the format has one. - **Maybeboard**: a scratch pile. Its cards stay visible but never count toward any rule and are never exported. - **Command zone**: only for games with a commander. - **Placement**: the pile's column and its order in it. Dragging the pile's handle does the same. The pile's panel menu sets its **View options**: the summary strip, the curve and the footer. ### Single Deck or Multi deck With several piles, the header asks what they are: - **Single Deck**: the piles are zones of one deck, like Riftbound's Legend, Rune Deck, Battlefields and Main Deck. The rule next to the toggle checks the whole deck, and the piles save as one deck. - **Multi deck**: every pile is a separate deck, like a lineup of three decks for a best-of-three event. The rule next to the toggle is a **deck set rule** that checks the lineup, and the piles save together as a **deck set**. ### Templates A **template** is a saved builder layout: which piles exist, each pile's deck rule and role, where each pile sits, what each pile shows, which pile the builder opens on, and a card ruleset. A template never holds cards. - **Turny templates** are built in. Riftbound's **Constructed** template opens on the Legend pile, since the Legend decides which domains the rest of the deck can use: | Pile | Role | Checks | | ------------ | ---------- | ------------------------ | | Legend | Main | exactly one Legend | | Rune Deck | Main | 12 runes | | Battlefields | Main | the Battlefields | | Main Deck | Main | the 40-card main deck | | Sideboard | Sideboard | the side deck | | Maybeboard | Maybeboard | nothing; it never counts | Legends of Runeterra and Pokémon have no built-in template yet. - **Switch template** swaps in another layout. It replaces every pile, cards included, so save first if you want to keep the deck. Picking a deck set rule that a template was built for offers to switch to that template. - **Save as Template** saves your own layout. It is offered while every pile is empty, and needs a deck set rule chosen. Saving again with the same name updates that template, and **Also save the card ruleset** pins the current card ruleset to it. - Manage your templates under **Settings → Templates** ([Legends of Runeterra](https://lor.turny.gg/settings/templates), [Pokémon TCG](https://pokemon.turny.gg/settings/templates), [Riftbound](https://riftbound.turny.gg/settings/templates)): rename them, make them public or private, copy a link, hide Turny templates you don't use, or delete your own. Public templates appear on your profile, and a template's link opens the builder with its piles and rules. A template's card ruleset is either **Recommended** or **Pinned**. A Turny template recommends one (Riftbound's recommends Standard): the builder uses it until you pick a card ruleset for that game yourself, and after that leaves your choice alone. A template saved with **Also save the card ruleset** pins it, so that ruleset applies every time the template loads. The active pile also steers the card search. A pile's rule can suggest filters for its zone: the Legend pile shows Legends, and once a Legend is in, the Main Deck pile shows cards in that Legend's domains. You can change or clear the filters at any time. ## Zone rules and the whole-deck rule A multi-pile deck is checked at two levels: - **Zone rules**, one per pile, each checking only its own pile. Riftbound's Legend pile checks for exactly one Legend, the Rune Deck pile for 12 runes, the Main Deck pile for 40 cards. - **The whole-deck rule**, chosen next to the **Single Deck** toggle, which checks the merged deck as a unit. **Riftbound constructed** checks all the zones together, including that you run a champion matching your Legend, that your [Chosen Champion](#riftbound-chosen-champion) is picked when more than one qualifies, that [Neeko's Legends](#riftbound-neeko-legends) follow her rules, and that the sideboard holds at most 10 cards. In a **Multi deck** layout this is the deck set rule instead. On top of both, the **card ruleset** decides which cards are legal at all, for example a format's legal sets and banned cards. ### Riftbound Chosen Champion A Riftbound deck names one Champion unit that matches its Legend as its **Chosen Champion**. It starts the game in the Champion Zone but still counts as one of the 40 main-deck cards, so choosing it changes no counts. - **The star**: in the Main Deck pile, each Champion unit matching your Legend shows a star. There are no stars before you pick a Legend, and none on sideboard or off-Legend champions. - **One candidate**: its star fills on its own. A deck with 3 copies of the same champion needs nothing from you. - **Several candidates**: each shows an outline star until you click one, which fills it. Click another to switch; you can't clear the choice. - **Resets**: the choice resets when the chosen card leaves the main deck or the Legend changes, falling back to the lone candidate or to outline stars. - **Saving and copying** are never blocked. A deck with several candidates and none chosen saves and copies, but shows a message such as "Pick your Chosen Champion: click the star on one of your Yasuo units.", and tournament registration refuses it until you pick one. - **Other rule messages**: the Chosen Champion must be in your main deck, must be a Champion unit, and must match your Legend. These are checked only when the deck has exactly one Legend, and a deck with a single matching champion never fails them. - **Elsewhere**: deck pages, galleries, highlights and tournament deck results show a filled star on the Chosen Champion, listed first after the Legend. The sample hand never draws it, and draw odds count 39 cards. ### Riftbound Neeko's Legends {#riftbound-neeko-legends} Neeko, Blending In lets a deck choose up to 3 more Legends besides its starting Legend. They are not deck cards: they count toward no zone, and the deck's domains, Chosen Champion and Signature cards still follow the starting Legend only. For example, a Yasuo, Unforgiven deck running Neeko can pick Jinx, Loose Cannon, Lee Sin, Blind Monk and Viktor, Herald of the Arcane. Viktor shares no domain with Yasuo, and that is fine: the rest of the deck still has to be Calm and Chaos. - **Choosing**: a **Legends 0 / 3** block sits under Neeko's row in the Main Deck pile, or in the Sideboard pile when she is only there. Click **Edit** and the card pool shows only the Legends you can still pick; a card you click goes to her Legends instead of the deck. **Done** returns the pool to normal, and the **×** next to a pick removes it. - **Limits**: at most 3, each a Legend with a different name, none named like your starting Legend. Extra copies of Neeko share the same 3. With 3 chosen, the block says so until you remove one. - **Removing Neeko**: the Legends belong to her. Take out the last Neeko and they are no longer saved, shared or checked. - **Saving and copying** are never blocked. A deck whose Legends break the rules saves and copies with a message, and tournament registration refuses it. The card ruleset checks them too, so a banned Legend, or one outside Standard, is flagged like any other card. - **Elsewhere**: deck pages, galleries, highlights and tournament deck results list them under Neeko, and the card gallery shows them in their own **Legends** section after the deck's cards. They are part of the decklist, so they are shown and hidden with it. ### Reading validation messages - **On a pile**: the pile's warning icon lists its zone rule's messages and any card-level issues in it. - **For the whole deck**: the builder's warning list repeats every pile's messages, prefixed with the pile's name (`Main Deck: The main deck must contain exactly 40 cards.`), followed by the whole-deck or deck set rule's messages without a prefix. - **On a card**: a warning marker on a card names the problem with that card. "This card is directly banned by the selected ruleset." means the card ruleset bans it. - **When a rule can't run**: if a rule fails to load, or your browser can't start the sandbox that runs rules, the builder says so rather than showing the deck as legal, and saving is turned off until rules can run. A message comes from the rule that raised it. The built-in rules explain themselves; for a custom rule, see [Custom rulesets](https://docs.turny.gg/guide/rulesets) and the [ruleset script reference](https://docs.turny.gg/reference/scripting/rulesets). ## Tips - **Calculators**: the calculator button in the builder header opens stats for the current deck, such as draw odds. See [Calculators](https://docs.turny.gg/guide/calculators). - **Search syntax**: the card search box takes a query language as well as card names, for example `t:unit cost<=3`. Each game has its own fields: [Legends of Runeterra](https://docs.turny.gg/reference/search/lor), [Pokémon TCG](https://docs.turny.gg/reference/search/pokemon), [Riftbound](https://docs.turny.gg/reference/search/riftbound). - **Saving**: **Save** needs you to be signed in. Deck names are unique on your account, so saving with an existing name replaces that deck. Private decks stay out of public areas until you share them, and the save dialog lists the rule warnings the deck still has. - **Reusing a saved deck**: in a multi-pile layout, **Use a saved deck** loads one of your saved decks into a pile. With **Sync** on, the pile stays linked to it: changes to the saved deck show up in the pile, and saving the deck set writes the pile back to the saved deck. - **Sharing a layout**: to share how you build rather than what you built, make a template public and share its link. --- url: https://docs.turny.gg/reference/ description: "Generated reference for Turny.gg scripting, card data and card search, kept in sync with the code that runs the site." --- # Reference Reference pages are generated from Turny.gg's source code, so they always match what the site runs. ## Scripting - [Ruleset script API](https://docs.turny.gg/reference/scripting/rulesets): what a custom ruleset script receives and returns. - [Script sandbox](https://docs.turny.gg/reference/scripting/sandbox): what scripts can and cannot do. - [Calculator script API](https://docs.turny.gg/reference/scripting/calculators): `compute` and every widget it can return. - [Playtest rules script API](https://docs.turny.gg/reference/scripting/playtest): the table a playtest rules script returns, with every step, predicate and shortcut rule. ## Card data The fields a script can read on each game's cards: - [Cyberpunk TCG](https://docs.turny.gg/reference/card-data/cyberpunk) - [Flesh and Blood](https://docs.turny.gg/reference/card-data/fab) - [Hearthstone](https://docs.turny.gg/reference/card-data/hs) - [Legends of Runeterra](https://docs.turny.gg/reference/card-data/lor) - [Magic: The Gathering](https://docs.turny.gg/reference/card-data/mtg) - [Palworld TCG](https://docs.turny.gg/reference/card-data/palworld) - [Pokémon TCG](https://docs.turny.gg/reference/card-data/pokemon) - [Riftbound](https://docs.turny.gg/reference/card-data/riftbound) ## Card search Search syntax for each game: - [Cyberpunk TCG](https://docs.turny.gg/reference/search/cyberpunk) - [Flesh and Blood](https://docs.turny.gg/reference/search/fab) - [Hearthstone](https://docs.turny.gg/reference/search/hs) - [Legends of Runeterra](https://docs.turny.gg/reference/search/lor) - [Magic: The Gathering](https://docs.turny.gg/reference/search/mtg) - [Palworld TCG](https://docs.turny.gg/reference/search/palworld) - [Pokémon TCG](https://docs.turny.gg/reference/search/pokemon) - [Riftbound](https://docs.turny.gg/reference/search/riftbound) ## Script kinds What a saved script is for. | Member | Value | Description | | --- | --- | --- | | `DeckValidation` | `"deck_validation"` | A custom ruleset's deck-settings script: validates decks and deck sets. | | `StatDashboard` | `"stat_dashboard"` | A calculator's `compute` script: turns a deck into dashboard widgets. | | `Playtest` | `"playtest"` | A playtest rules script: declares the playtest table (zones, actions, shortcuts) as a `PlaytestDefinition`. | --- url: https://docs.turny.gg/reference/scripting/rulesets description: "Reference for custom ruleset scripts: entry points, arguments, context and return values." --- # Ruleset script API A custom ruleset can carry up to three scripts, one per scope: a **card** rule, a **deck** rule and a **deck set** rule. Each is a small JavaScript module that Turny.gg runs in the [script sandbox](https://docs.turny.gg/reference/scripting/sandbox) while a deck is built and again when it is submitted. For a walkthrough, start with the [custom rulesets guide](https://docs.turny.gg/guide/rulesets). This page is the exact contract. ## Entry points Each script provides one function. The runner looks for it in this order: 1. **The default export.** `export default function validateDeck(deck) { … }` or `export default (deck) => …`. The function's own name does not matter. 2. **The scope's named fallback.** With no default export, a top-level function (or `const`) with the name below, for example a plain `function validateDeck(deck) { … }`. Do not `export` it by name: the only named export allowed is `resolvePoolFilters`. If neither exists, the script fails with "did not export a function". The default export wins when both are present. | Scope | Named fallback | When it runs | | --- | --- | --- | | Card | `validateCard` | Called once per card, both to validate a submitted card and to filter the deck builder's card pool. | | Deck | `validateDeck` | Called once per deck (or builder pile) with every card the deck references. | | Deck set | `validateDeckset` | Called once with the whole lineup of decks a player submits. | ```ts // Card is the game's card object; see the card data reference. function validateCard(card: Card, context?: DeckSettingsScriptContext): DeckSettingsScriptResult; function validateDeck(deck: DeckSettingsScriptDeck, cardsById: Record, context?: DeckSettingsScriptContext): DeckSettingsScriptResult; function validateDeckset(decks: DeckSettingsScriptDeck[], cardsById: Record, context?: DeckSettingsScriptContext): DeckSettingsScriptResult; function resolvePoolFilters(input: DeckSettingsPoolFiltersInput, context?: DeckSettingsScriptContext): DeckSettingsPoolFiltersPatch; ``` `context` is always the last argument and always optional, so a script written as `validateDeck(deck, cardsById)` keeps working. ### Card scope Called once per card. In the deck builder the card rule also filters the card pool: a card that fails is hidden. A failing card on a submitted deck blocks the submission. ```js // Only cards from two sets are legal. const LEGAL_SETS = ["set1", "set2"]; export default function validateCard(card) { return LEGAL_SETS.includes(card.setCode); } ``` ### Deck scope Called once per deck (in the builder, once per pile) with the deck's card quantities and the catalog entries for every card it references. ```js export default function validateDeck(deck, cardsById) { const total = Object.values(deck).reduce((sum, copies) => sum + copies, 0); if (total !== 40) { return { valid: false, issues: [ { code: "deck_size", message: `Decks need exactly 40 cards (found ${total}).`, }, ], }; } return true; } ``` ### Deck set scope Called once with every deck in the player's lineup. ```js // No card may appear in more than one deck of the lineup. export default function validateDeckset(decks, cardsById) { const seen = new Set(); const issues = []; for (const deck of decks) { for (const ref of Object.keys(deck)) { if (seen.has(ref)) { const name = cardsById[ref]?.name ?? ref; issues.push({ code: "duplicate_card", message: `${name} is in more than one deck.`, }); } seen.add(ref); } } return { valid: issues.length === 0, issues }; } ``` ## Arguments Every argument is a deep copy of plain data, frozen before your script sees it. Writing to it throws, so build new objects instead (`{ ...deck }`, `Object.entries(deck)`). ### `card` and `cardsById` `card` is one catalog entry. `cardsById` maps each card ref in the deck (or lineup) to its catalog entry. Every card has `id`, `name` and `setCode`; the rest is per game: - [Cyberpunk TCG card data](https://docs.turny.gg/reference/card-data/cyberpunk) - [Flesh and Blood card data](https://docs.turny.gg/reference/card-data/fab) - [Hearthstone card data](https://docs.turny.gg/reference/card-data/hs) - [Legends of Runeterra card data](https://docs.turny.gg/reference/card-data/lor) - [Palworld TCG card data](https://docs.turny.gg/reference/card-data/palworld) - [Pokémon TCG card data](https://docs.turny.gg/reference/card-data/pokemon) - [Riftbound card data](https://docs.turny.gg/reference/card-data/riftbound) ### `deck` The `deck` a deck-scope script receives. Usually the flat quantity map; a zone-aware payload nests zones under `main` / `sideboard`. A flat map may also carry a nested `sideboard` record, so read zones defensively and never treat the literal `main` / `sideboard` keys as card refs. #### Zoned deck Zone-aware deck payload (e.g. MTG submissions): card refs nested under `main`, with an optional `sideboard`. | Property | Type | Description | | --- | --- | --- | | `main` | `DeckSettingsScriptCardQuantities` | Main-deck card refs → copies. | | `sideboard?` | `DeckSettingsScriptCardQuantities` | Sideboard card refs → copies, when the game has one. | With each game's default template and built-in rulesets, which is how these decks are usually built: - **Legends of Runeterra** and **Pokémon TCG** pass the flat map. - **Riftbound** passes the flat map too, with the sideboard nested under `deck.sideboard` when the deck has one, and the [Chosen Champion](https://docs.turny.gg/guide/deck-builder#riftbound-chosen-champion)'s card ref as a string under `deck.chosenChampion` when one is set. Cards that another card chooses outside the deck, such as the up to 3 Legends for Neeko, Blending In, sit under `deck.cardSideboards`, keyed by the choosing card's ref and then by each chosen card's ref with its quantity (`{ "": { "": 1 } }`). They are not deck cards. A card that can choose them carries `game.cardSideboard` (`{ maxCards, cardType }`) in its card data. Count only number values, as the helper below does. These are defaults, not limits. Anyone can create their own [rulesets](https://docs.turny.gg/guide/rulesets) and [templates](https://docs.turny.gg/guide/deck-builder#templates) for whatever format they play, so read zones defensively. A helper that reads the main deck from any of these shapes: ```js function mainDeck(deck) { if (deck.main && typeof deck.main === "object") { return deck.main; } const main = {}; for (const [ref, copies] of Object.entries(deck)) { if (typeof copies === "number") { main[ref] = copies; } } return main; } ``` ### `context` Optional catalog context handed to every entry point as its last argument. Always additive: scripts written against the shorter signature keep working, and scripts that read it must tolerate `context` being `undefined` (no catalog globals loaded, inline validation paths). | Property | Type | Description | | --- | --- | --- | | `globals` | `unknown` | The game's catalog globals document (region / keyword / set lookup tables). Its shape is per game; see the card data reference. | The fields of `globals` for each game are on the card data pages linked above. ## Return values What an entry point may return. The runner normalizes it to `{ valid, issues }`; any other value (a number, a string, an array) counts as a failure with the scope's fallback message. | Value | Result | | --- | --- | | `true` | Passes with no issues. | | `false`, `null`, `undefined` | Fails with the scope's fallback message (e.g. "Saved deck rule rejected this deck."). A missing `return` is `undefined`, so it fails too. | | `DeckSettingsScriptResultObject` | Passes when `valid` or `allowed` is exactly `true`, keeping any `issues`. Otherwise fails with `issues`, or the fallback message when there are none. | #### Result object The object form of a result. | Property | Type | Description | | --- | --- | --- | | `valid?` | `boolean` | `true` passes. Anything else (missing, `false`, truthy non-booleans) fails. | | `allowed?` | `boolean` | Alias of `valid`: the result passes when either is exactly `true`. | | `issues?` | `DeckSettingsScriptIssue[]` | Issues to report. Non-array values are ignored; entries that are neither a string nor a usable object are dropped. | | `metadata?` | `DeckSettingsScriptResultMetadata` | Result-level detail; the runner reads only `deckSizeTarget` from it. | #### Result metadata Detail a rule reports about the whole result, beside its verdict. The runner reads only the keys below; any other key is the rule's own and is ignored. | Property | Type | Description | | --- | --- | --- | | `deckSizeTarget?` | `DeckSettingsScriptDeckSizeTarget \| null` | Deck scope: the size the rule holds this deck to, reported on valid and invalid results alike. The deck builder shows it in the pile header as progress ("12 / 30"). `null`, or no bound, shows no target. | The deck size a deck-scope rule holds the deck to. An exact size has `minimum === maximum`; leave a bound out (or `null`) for an open end. | Property | Type | Description | | --- | --- | --- | | `minimum?` | `number \| null` | Fewest main-deck cards the deck may hold (a non-negative integer). | | `maximum?` | `number \| null` | Most main-deck cards the deck may hold (a non-negative integer). | #### Issues One issue: a plain message string, or an object with a `code` and/or `message`. An issue reported as an object. At least one of `code` / `message` must be a non-empty string, or the issue is dropped. | Property | Type | Description | | --- | --- | --- | | `code?` | `string` | Stable machine-readable id, e.g. `deck_size`. Shown (underscores as spaces) when there is no `message`. | | `message?` | `string` | Human-readable text shown to the player. Trimmed. | | `metadata?` | `DeckSettingsScriptIssueMetadata` | Scalar details for the UI. Kept by the in-browser validator only; non-scalar entries are dropped. | ### How issues are shown - **In the browser**, each issue shows its `message`, or its `code` with underscores as spaces when there is no message. - **On submission**, the server prefixes each issue with where it came from: `Card : …` for the card rule, `Deck 2: …` for the deck rule (decks are numbered from 1) and `Lineup: …` for the deck set rule. - A passing result can still carry issues. They are returned alongside the pass and do not make the check fail. ```js export default function validateDeck(deck) { const issues = []; if (Object.keys(deck).length < 10) { issues.push("Use at least 10 different cards."); } if (!Object.keys(deck).some((ref) => ref.startsWith("champ_"))) { issues.push({ code: "missing_champion" }); } return { valid: issues.length === 0, issues }; } ``` ## `resolvePoolFilters` A deck rule may also `export function resolvePoolFilters(input, context)`. The deck builder calls it to suggest the card-pool filters for the pile being edited; it never runs on submission and has no effect on validity. - **Deck scope only.** The builder only asks deck rules. The export is allowed by the safety check anywhere, but card and deck set scripts never have it called. - **An omitted key means no suggestion** for that filter, and the user's current value stays. - **`[]` is a suggestion of "nothing selected"** and clears that filter. Choose between omitting and `[]` deliberately. - **Keys must be the game's own filter keys** (for Riftbound, `cardTypes` and `domains`). Unknown keys are dropped, so a typo silently does nothing. Values must match what the catalog emits, such as Riftbound's lowercase card types. - **Returning `null`** (or anything that is not a plain object) makes no suggestion at all. - The hook sees the **whole lineup**, so a rule can read another pile, for example the Legend in the Legend pile. ```js export default function validateDeck(deck) { return true; } export function resolvePoolFilters(input, context) { const active = input.lineup.find( (pile) => pile.pileId === input.activePileId, ); if (active && active.role === "sideboard") { return null; } return { cardTypes: ["unit", "spell", "gear"] }; } ``` #### Input First argument of `resolvePoolFilters`. `filters` is the game's own filter model (e.g. `RiftboundCardFiltersModel` keys for Riftbound); the hook answers with a partial patch in that same vocabulary, or `null`. | Property | Type | Description | | --- | --- | --- | | `lineup` | `DeckSettingsPoolFilterLineupPile[]` | Every pile in the builder, the active one included. | | `activePileId` | `string` | The pile whose card pool is being filtered. | | `cardsById` | `Record` | Catalog entries for every card in the lineup. | | `filters` | `Record` | The builder's current filter model. | #### Lineup pile One pile of the builder lineup handed to `resolvePoolFilters`. The hook sees the whole lineup, not just the active pile, so e.g. a Main Deck rule can find the Legend sitting in the Legend pile. | Property | Type | Description | | --- | --- | --- | | `pileId` | `string` | Builder pile id; compare with `activePileId`. | | `name` | `string` | Display name of the pile. | | `role` | `DeckSettingsPoolFilterPileRole \| null` | Builder role, or `null` for a pile with no special role. | | `deckRuleId` | `string \| null` | Null when the pile runs with no deck rule (unresolvable template rule). | | `cards` | `Record` | The pile's card refs → copies. | Pile roles: `"main"`, `"sideboard"`, `"maybeboard"`, `"commander"`. Builder role of a lineup pile as seen by `resolvePoolFilters`. `commander` is the command-zone pile, so a hook can find commanders by role rather than by the pile's deck rule id (which the user may clear or a template may leave unset). #### Patch What `resolvePoolFilters` may answer: a partial filter-model patch, or `null` for no suggestion. An omitted key leaves that filter alone; `[]` clears it. Keys outside the game's filter model are dropped; any non-object answer counts as `null`. ## See also - [Script sandbox](https://docs.turny.gg/reference/scripting/sandbox): allowed globals, rejected syntax, time limits and safety issue codes. - [Custom rulesets guide](https://docs.turny.gg/guide/rulesets) --- url: https://docs.turny.gg/reference/scripting/sandbox description: "What custom scripts can and cannot do: the sandbox, its limits and the static safety checks." --- # Script sandbox [Ruleset scripts](https://docs.turny.gg/reference/scripting/rulesets) and [calculator scripts](https://docs.turny.gg/reference/scripting/calculators) share one sandbox. Both go through the same static safety check and run in the same kind of isolated runtime, so everything on this page applies to both. ## How a script runs 1. **Static safety check.** The source is parsed as a JavaScript module and every statement and expression is checked against the allowlists below. Any issue rejects the whole script and nothing runs. Rulesets are checked when they are saved, so an unsafe ruleset cannot be saved. Calculators are checked before every run. 2. **A fresh sandbox per run.** Each run gets a new [SES](https://github.com/endojs/endo/tree/master/packages/ses) `Compartment` with no extra globals. The script sees only the frozen JavaScript built-ins and the arguments it is called with. Nothing carries over between runs, and one script cannot see another. 3. **Plain, frozen inputs.** Arguments are rebuilt as plain objects and arrays (no prototypes, no functions) and deep-frozen. Writing to them throws. 4. **Checked output.** What the script returns is normalized before anything uses it: ruleset results as described under [return values](https://docs.turny.gg/reference/scripting/rulesets#return-values), calculator dashboards by the calculator renderer's own limits. Scripts run in two places: - **In the browser**, inside a Web Worker: the deck builder, card legality checks and calculators. If the sandbox worker cannot start on a device, the site offers (only after the failure) an opt-in to run deck rules outside the sandbox on that device. The opt-in expires after 30 days. - **On the server**, when a deck is submitted: a separate worker process re-runs the card, deck and deck set rules. A tournament's banned cards are rejected before any script runs. Because a script is parsed as a module, it is always in strict mode. ## Allowed globals Globals a script may reference. Every other free identifier is rejected. | Global | `new` allowed | | --- | --- | | `Array` | | | `Boolean` | | | `Date` | Yes | | `Infinity` | | | `JSON` | | | `Map` | Yes | | `Math` | | | `NaN` | | | `Number` | | | `Object` | | | `RegExp` | Yes | | `Set` | Yes | | `String` | | | `undefined` | | The only constructors `new` may call (and only when not shadowed locally). Everything else is rejected as `unsafe_global`, including some common names: - `Error` (`new Error(…)` fails as `new_expression_unsupported`): to fail a check, return `false` or `{ valid: false, issues }` instead of throwing. - `parseInt` / `parseFloat`: use `Number.parseInt` / `Number.parseFloat`. - `console`, `Promise`, `Symbol`, `WeakMap`, `globalThis`, `eval`, `Function`, `fetch` and timers. ```js // Passes: only allowed globals, let/const and plain functions. export default function validateDeck(deck) { const copies = new Map(Object.entries(deck)); const most = Math.max(0, ...copies.values()); return most <= Number.parseInt("3", 10); } ``` ## Blocked properties Property names a script may not read or write, as `obj.name` or `obj["name"]`. They reach prototypes, constructors or the call stack. `__defineGetter__`, `__defineSetter__`, `__lookupGetter__`, `__lookupSetter__`, `__proto__`, `arguments`, `callee`, `caller`, `constructor`, `prototype` The check only sees names written literally (`card.constructor`, `card["constructor"]`). A computed key such as `card[key]` is not checked statically; the frozen runtime is what contains it. ```js // Rejected: property_access_blocked. export default function validateCard(card) { return card.constructor === Object; } ``` ## Exports A script has one default export. See [entry points](https://docs.turny.gg/reference/scripting/rulesets#entry-points) for how the runner finds the function. The only named exports a script may carry beside its default: the optional deck-scope pool-filter hook `export function resolvePoolFilters(input, context)`. Re-exports, `export { … }` lists, exported variables and any other exported function name stay rejected. Allowed named exports: `resolvePoolFilters`. ## Rejected syntax The syntax rules are written into the checker itself (`packages/game-adapters/src/tournament-create/script-safety.ts`): the statement and expression visitors (`visitStatement`, `visitExpression`) reject anything not on their list, plus dedicated checks for `var` (`visitVariableDeclaration`), `async` and generators (`visitFunctionLike`) and getters and setters (`visitObjectExpression`). Rejected: - `import` declarations, dynamic `import()` and `import.meta`. - `export * from …`, `export { … }` lists, exported variables and any named export except `resolvePoolFilters`. - Classes (declarations and expressions), `this` and `super`. - `var`. Use `let` or `const`. - `async` functions, `await`, generator functions and `yield`. - `delete`. - Labeled statements and `debugger`. - Getters and setters in object literals (`{ get total() { … } }`). - Tagged templates. Plain template literals are fine. - Assigning to anything the script did not declare, such as a global. - `new` on anything but `Date`, `Map`, `RegExp` or `Set`. - Anything the parser rejects in strict mode, such as `with` or legacy octal literals (`010`). These fail as `invalid_syntax`. ```js // Rejected: variable_kind_unsupported, unsafe_global. export default function validateDeck(deck) { var total = 0; fetch("https://example.com"); return total === 0; } ``` ```js // Rejected: new_expression_unsupported (Error is not a constructor you may call). export default function validateDeck(deck) { throw new Error("Not allowed"); } ``` ```js // Rejected: async_unsupported, syntax_unsupported. export default async function validateDeck(deck) { return this.check(deck); } ``` ## Time limits | Where | Limit | | --- | --- | | Browser: one card, deck or deck set check | 2s | | Browser: a card rule over the whole card pool | 15s | | Browser: first catalog download before any check | 45s | | Browser: one calculator run | 5s | | Server: one deck submission check (all scopes) | 15s | | Server: the queue job around that check | 50s | A script that runs past its limit (an endless loop, say) is stopped and the check reports an error instead of a pass. Keep scripts linear in the size of the deck or card pool: a card rule runs once for every card in the catalog when the builder filters the pool. ## Safety issue codes Each rejection carries one of these codes. | Member | Value | Description | | --- | --- | --- | | `AsyncUnsupported` | `"async_unsupported"` | An `async` function or an `await` expression. | | `GeneratorUnsupported` | `"generator_unsupported"` | A generator function (`function*`) or a `yield` expression. | | `InvalidSyntax` | `"invalid_syntax"` | The source is empty or does not parse as an ES module. | | `NewExpressionUnsupported` | `"new_expression_unsupported"` | `new` on anything other than an allowed constructor (`Date`, `Map`, `RegExp`, `Set`), or on a local that shadows one. | | `PropertyAccessBlocked` | `"property_access_blocked"` | Reading or writing a blocked property name such as `constructor`, `prototype` or `__proto__`. | | `SyntaxUnsupported` | `"syntax_unsupported"` | Disallowed syntax: imports, extra exports, classes, `this`, `delete`, labels, `debugger`, getters/setters, tagged templates, `import()` / `import.meta`, `super`. | | `UnsafeAssignment` | `"unsafe_assignment"` | Assigning to a name the script did not declare (a global or an undeclared variable). | | `UnsafeGlobal` | `"unsafe_global"` | Referencing a free identifier that is not on the allowed globals list (e.g. `globalThis`, `eval`, `fetch`). | | `VariableKindUnsupported` | `"variable_kind_unsupported"` | A `var` declaration. Use `let` or `const`. | At most 12 issues are reported per script. The check stops at this many issues, so fixing them can reveal more. --- url: https://docs.turny.gg/reference/scripting/calculators description: "Reference for calculator compute scripts: arguments, every dashboard widget they can return, output limits, and the default calculators as examples." --- # Calculator script API A calculator is a small JavaScript function that turns a deck into a dashboard: a mana curve, a type breakdown, opening-hand odds. It returns **data plus a widget type, never markup**. Turny.gg draws each widget with its own trusted components, which is what makes it safe to show a calculator someone else wrote. The no-code builder produces the same kind of script, so everything here also applies to a builder calculator you open as code. For a walkthrough of building and sharing calculators, see the [calculators guide](https://docs.turny.gg/guide/calculators). ## The contract A calculator script defines one function, `compute`, and returns a dashboard: ```js export default function compute(pile, cardsById, ctx) { return { widgets: [{ kind: "stat", label: "Hello", value: "world" }], }; } ``` Turny.gg finds the function in one of three ways, in this order: 1. `export default function compute(...) { ... }` (any name, or none, works here). 2. `export default `, where the expression is a function. 3. A top-level function declared as `function compute(...) { ... }`. The script runs in the same sandbox as custom rulesets: no network, no timers, no `async`, and only a short list of built-in globals. See [Script sandbox](https://docs.turny.gg/reference/scripting/sandbox) for exactly what is allowed. A script the safety check rejects never runs. ### Arguments | # | Argument | Type | Description | | --- | --- | --- | --- | | 1 | `pile` | `Record` | The deck being viewed: card ref to number of copies. Refs are the keys of `cardsById`. | | 2 | `cardsById` | `Record` | Every card in the pile, by ref. Game-specific fields live on `card.game`; see the card data reference for your game. | | 3 | `context` | `CalculatorScriptContext \| undefined` | Optional catalog context (fields below). May be `undefined`: a script that reads it must work without it. | `CalculatorScriptContext`: | Property | Type | Description | | --- | --- | --- | | `globals` | `unknown` | The game catalog's globals document (region, keyword and set lookup tables). Its shape is per game; null when the catalog has none or it failed to load. | | `attachedPile?` | `CalculatorPile` | Cards the deck must own but never plays from it (Hearthstone's E.T.C. band and Zilliax's modules), keyed like `pile`: card ref -> quantity. Never part of `pile`, so totals, curves and draw odds stay on the played deck; a cost calculator adds what it can price. Absent when the deck has none. Their cards are in `cardsById` too. | Things to know about the arguments: - **They are read-only.** `pile`, `cardsById` and `ctx` are frozen copies. Build new arrays and objects instead of changing them. - **A card can be missing.** Guard `cardsById[ref]` before reading from it; the default calculators treat a missing card as having no fields. - **Card fields are per game.** Everything game-specific lives on `card.game`. See the card data reference for [Cyberpunk TCG](https://docs.turny.gg/reference/card-data/cyberpunk), [Flesh and Blood](https://docs.turny.gg/reference/card-data/fab), [Hearthstone](https://docs.turny.gg/reference/card-data/hs), [Legends of Runeterra](https://docs.turny.gg/reference/card-data/lor), [Magic: The Gathering](https://docs.turny.gg/reference/card-data/mtg), [Palworld TCG](https://docs.turny.gg/reference/card-data/palworld), [Pokémon TCG](https://docs.turny.gg/reference/card-data/pokemon) and [Riftbound](https://docs.turny.gg/reference/card-data/riftbound). - **`ctx` may be absent.** Any run can call `compute` without it, including the editor preview. Check it before use: ```js export default function compute(pile, cardsById, ctx) { const hasGlobals = ctx !== undefined && ctx.globals !== undefined; return { widgets: [ { kind: "stat", label: "Catalog globals", value: hasGlobals ? "Yes" : "No", }, ], }; } ``` ### Return value `compute` returns an object with a `widgets` array. Widgets are drawn in array order. Each widget is a plain object whose `kind` picks how it is drawn; the rest of its fields are the data for that kind. ## Widget examples Every widget type with a minimal working `compute`: ::: code-group ```js [stat] export default function compute(pile) { let total = 0; Object.keys(pile).forEach((ref) => { total += pile[ref]; }); return { widgets: [ { kind: "stat", label: "Deck size", value: total, unit: "cards" }, ], }; } ``` ```js [histogram] export default function compute(pile) { // Distinct cards run as 1-ofs, 2-ofs and 3+-ofs. const buckets = [0, 0, 0]; Object.keys(pile).forEach((ref) => { const copies = Math.min(Math.max(pile[ref], 1), 3); buckets[copies - 1] += 1; }); return { widgets: [ { kind: "histogram", label: "Copies per card", buckets: buckets, labels: ["1", "2", "3+"], }, ], }; } ``` ```js [donut] export default function compute(pile) { let singles = 0; let multiples = 0; Object.keys(pile).forEach((ref) => { if (pile[ref] === 1) { singles += 1; } else { multiples += 1; } }); return { widgets: [ { kind: "donut", label: "Singles vs multiples", segments: [ { key: "singles", label: "1 copy", value: singles, color: "#3a78e8" }, { key: "multiples", label: "2+ copies", value: multiples, color: "" }, ], }, ], }; } ``` ```js [gauge] export default function compute(pile) { let singles = 0; let multiples = 0; Object.keys(pile).forEach((ref) => { if (pile[ref] === 1) { singles += pile[ref]; } else { multiples += pile[ref]; } }); return { widgets: [ { kind: "gauge", label: "Copies in singles vs multiples", segments: [ { key: "singles", label: "Singles", value: singles, color: "" }, { key: "multiples", label: "Multiples", value: multiples, color: "" }, ], }, ], }; } ``` ```js [table] export default function compute(pile, cardsById) { const rows = Object.keys(pile) .sort((left, right) => pile[right] - pile[left]) .slice(0, 5) .map((ref) => { const card = cardsById[ref]; const name = card && typeof card.name === "string" ? card.name : ref; return [name, pile[ref]]; }); return { widgets: [ { kind: "table", label: "Most copies", columns: ["Card", "Copies"], rows: rows, }, ], }; } ``` ```js [hypergeometric] export default function compute(pile) { // Odds of drawing at least one copy of your most-played card in 7 cards. let deckSize = 0; let mostCopies = 0; Object.keys(pile).forEach((ref) => { deckSize += pile[ref]; mostCopies = Math.max(mostCopies, pile[ref]); }); return { widgets: [ { kind: "hypergeometric", label: "Top card in opening hand", population: deckSize, successCount: mostCopies, draws: 7, exactCounts: [1, 2], }, ], }; } ``` ```js [ratio] export default function compute(pile) { let copies = 0; Object.keys(pile).forEach((ref) => { copies += pile[ref]; }); return { widgets: [ { kind: "ratio", label: "Copies per card", numerator: copies, denominator: Object.keys(pile).length, format: "multiplier", }, ], }; } ``` ::: ## Widget reference | kind | Description | | --- | --- | | `"stat"` | A single headline value in a stat tile (e.g. "Average cost: 3.4"). | | `"histogram"` | A bar chart: one bar per bucket (e.g. a mana curve). Bars pair with `labels` by index. | | `"donut"` | A donut (pie) chart of labelled, coloured segments. | | `"gauge"` | A semicircular meter: segments fill a half-circle in proportion to their values. Same payload as `donut`, drawn as a gauge. | | `"bars"` | Horizontal bars, one per segment (e.g. regions, domains, mana sources). | | `"table"` | A table of rows under column headers. | | `"hypergeometric"` | A closed-form hypergeometric draw-odds widget: the probability of drawing successes when taking `draws` cards, without replacement, from a `population` of which `successCount` match a filter (e.g. "odds of opening at least one basic in a 7-card hand"). The renderer computes and shows P(X>=1); when `exactCounts` is given it also shows P(X=k) for each listed k in a small table. | | `"ratio"` | A derived index number: `numerator / denominator`, formatted per `format`. Renders as a stat tile. Guards against a zero denominator. | ### `kind: "stat"` A single headline value in a stat tile (e.g. "Average cost: 3.4"). | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `value` | `number \| string` | The value. A finite number is formatted in the viewer's locale (`Intl.NumberFormat`); a string is shown verbatim (e.g. `"12.5%"`). | | `unit?` | `string` | Optional suffix shown after the value (e.g. `"cards"`). | ### `kind: "histogram"` A bar chart: one bar per bucket (e.g. a mana curve). Bars pair with `labels` by index. | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `buckets` | `number[]` | Bar heights, left to right. | | `labels` | `string[]` | One axis label per bucket, same order as `buckets`. | | `bucketCardRefs?` | `string[][]` | Optional pile refs per bucket, parallel to `buckets`: the cards counted in each bar. A bar is clickable (selecting it highlights those cards on the deck page) only when its entry is a non-empty list. Capped like `DeckStatSegment.cardRefs`. | ### `kind: "donut"` A donut (pie) chart of labelled, coloured segments. | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `vocabulary?` | `string` | Optional `CalculatorVocabulary` id resolving segment labels and colors per game. | | `segments` | `DeckStatSegment[]` | Slices, drawn in order; zero-value slices are skipped. | ### `kind: "gauge"` A semicircular meter: segments fill a half-circle in proportion to their values. Same payload as `donut`, drawn as a gauge. | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `vocabulary?` | `string` | Optional `CalculatorVocabulary` id resolving segment labels and colors per game. | | `segments` | `DeckStatSegment[]` | Arcs, drawn in order; zero-value arcs are skipped. | ### `kind: "bars"` Horizontal bars, one per segment (e.g. regions, domains, mana sources). | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `vocabulary?` | `string` | Optional `CalculatorVocabulary` id resolving segment labels and colors per game. | | `segments` | `DeckStatSegment[]` | Bars, drawn in order. | ### `kind: "table"` A table of rows under column headers. | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `columns` | `string[]` | Column headers, left to right. | | `columnKeys?` | `string[]` | Optional i18n keys under `calculators.widgets.*`, parallel to `columns`. | | `columnVocabularies?` | `string[]` | Optional `CalculatorVocabulary` ids, parallel to `columns` (`""` for none). A cell in a column naming one is a vocabulary key the game resolves to its translated label, as segment keys are; an unresolved key shows as-is. | | `rows` | `(string \| number)[][]` | Rows of cells; each row pairs with `columns` by index. | ### `kind: "hypergeometric"` A closed-form hypergeometric draw-odds widget: the probability of drawing successes when taking `draws` cards, without replacement, from a `population` of which `successCount` match a filter (e.g. "odds of opening at least one basic in a 7-card hand"). The renderer computes and shows P(X>=1); when `exactCounts` is given it also shows P(X=k) for each listed k in a small table. | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `population` | `number` | Population size: the pile / deck size drawn from. | | `successCount` | `number` | Successes in the population: cards matching the filter. | | `draws` | `number` | Number of cards drawn (e.g. the opening-hand size). | | `exactCounts?` | `number[]` | Optional exact-count targets. When present, the renderer adds a P(X=k) row per listed k alongside the headline P(X>=1) figure. | ### `kind: "ratio"` A derived index number: `numerator / denominator`, formatted per `format`. Renders as a stat tile. Guards against a zero denominator. | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Title shown on the widget. | | `labelKey?` | `string` | Optional i18n key under `calculators.widgets.*`; falls back to `label`. | | `numerator` | `number` | Top of the fraction. | | `denominator` | `number` | Bottom of the fraction. A zero shows the no-data placeholder. | | `format?` | `CalculatorRatioFormat` | How to format the quotient. Defaults to `number`. | ### Segments A `donut` slice or `gauge` arc (`DeckStatSegment`): | Property | Type | Description | | --- | --- | --- | | `key` | `string` | Stable identifier for the segment (e.g. `"spells"`). | | `label` | `string` | Legend text. | | `value` | `number` | The segment's size; segments are drawn in proportion to their values. | | `color` | `string` | CSS color (e.g. `"#3a78e8"`). Empty picks a fallback palette color. | | `cardRefs?` | `string[]` | The pile refs (the keys of `compute`'s `pile`) of the cards counted in this segment. Optional: a segment is clickable (selecting it highlights those cards on the deck page) only when it carries a non-empty list. The runner keeps strings only, de-duplicated and capped (`CALCULATOR_OUTPUT_CAPS.maxCardRefsPerSegment` / `maxCardRefsPerWidget`). | ### Ratio formats | Format | Shows | | --- | --- | | `"number"` | The raw quotient to two decimals (e.g. `1.83`). | | `"percent"` | The quotient as a percentage to one decimal (e.g. `65.0%`). | | `"multiplier"` | The quotient to two decimals with a multiplier sign (e.g. `1.83×`). | | `"ratio"` | The pair reduced to lowest terms (e.g. `11:6`). | ## How bad output is handled A calculator's return value is never trusted. Before anything is drawn it passes through a checker (`normalizeCalculatorResult`) that repairs or drops whatever does not fit the shapes above. The checker never throws, so a buggy script produces a smaller dashboard, not a crash: | Your script returns | What is drawn | | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Anything other than an object with a `widgets` array | An empty dashboard | | A widget that is not an object, or has an unknown `kind` | That widget is dropped; the rest are kept | | A missing or non-text `label` | An empty label | | A number field (`value` of a segment, `buckets`, `population`, `numerator`, ...) | Converted with `Number()`; `NaN`, `Infinity` and non-numbers become `0` | | A text field set to a number or boolean | Converted to text; any other value (object, `null`) becomes empty text | | A `stat` `value` | Kept as a number if it is one (non-finite becomes `0`), otherwise text | | A `table` cell | Kept as a number if it is one, otherwise text; a row that is not an array is dropped | | A segment that is not an object | That segment is dropped | | `unit`, `exactCounts` or `format` of the wrong type (or an unknown `format`) | That optional field is left out | | Extra properties on a widget | Dropped | | More entries or longer text than the [limits](#limits) allow | Cut to the limit | An error **thrown** by your script, a syntax error, or a safety-check rejection is different: the calculator shows an error message instead of a dashboard. A widget with nothing to show draws a "No data" placeholder instead of an empty chart: a `stat` whose value is empty text, a `histogram` or `donut`/`gauge` with no positive values, a `table` with no columns or no rows, a `hypergeometric` with a `population` of `0` or less, or a `ratio` with a `denominator` of `0`. ## Limits Hard caps `normalizeCalculatorResult` applies to guest output. Guest code is untrusted: these clamp the blast radius of a hostile or buggy script on the trusted renderer. Output past a cap is truncated (extra entries dropped, strings cut), never rejected. | Cap | Limit | Applies to | | --- | --- | --- | | `maxWidgets` | 50 | Widgets kept per dashboard; later widgets are dropped. | | `maxSegments` | 100 | Segments kept per `donut`, `gauge` or `bars` widget. | | `maxHistogramBuckets` | 200 | Entries kept in a `histogram`'s `buckets` and in its `labels`. | | `maxTableRows` | 200 | Rows kept per `table`. | | `maxTableColumns` | 20 | Entries kept in a `table`'s `columns`, and cells kept per row. | | `maxLabelLength` | 200 | Characters kept in every short string: widget labels and label keys, `stat` string values and units, segment keys, labels and colors, histogram labels and table column headers and column keys. | | `maxCellLength` | 200 | Characters kept in a string `table` cell. | | `maxExactCounts` | 50 | Entries kept in a `hypergeometric` widget's `exactCounts`. | | `maxCardRefsPerSegment` | 250 | Card refs kept per segment `cardRefs` and per histogram bucket's `bucketCardRefs` entry, after dropping non-strings and duplicates. | | `maxCardRefsPerWidget` | 2000 | Card refs kept across one widget's segments or buckets; once spent, later segments/buckets keep none. Bounds the payload a hostile script can emit. | **Time limit:** a run that takes longer than **5 seconds** is stopped and the calculator shows an error instead of a dashboard. ## Builder-generated scripts A calculator made with the no-code builder is an ordinary script whose first line is a marker comment holding the builder's settings: ```text // @calculator-spec:v1 {"widgets":[...]} ``` The marker is only a comment, so it has no effect on how the script runs. The builder uses it to re-open the calculator: - **Drop to code** switches a builder calculator to the code editor. - While the code is still exactly what the builder generates from the marker (checked by rebuilding it and comparing byte for byte), you can switch back to the builder. - Once you edit the code by hand, the rebuilt code no longer matches and the calculator is **detached** from the builder: it stays a code calculator. Undoing your edits so the code matches again re-enables switching back. To make sure hand edits are never replaced by the builder's version, **delete the marker line** before saving. A script without a readable marker always opens in the code editor. ## Examples: the default calculators Every game except Teamfight Tactics ships default calculators, and they are ordinary calculator scripts. The code below is pulled from the source the site runs, so it is always current. Copy one as a starting point for your own. ::: code-group ```js [Cyberpunk TCG] const COST_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+"]; const LEGEND_TYPE = "legend"; // Colour display order (the official database's order); unknown colours are not charted. const COLOR_ORDER = ["red", "blue", "green", "yellow"]; // Main-deck card-type display order; unexpected types trail by count. const TYPE_ORDER = ["unit", "gear", "program"]; export default function compute(pile, cardsById) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; const costBuckets = Array.from({ length: 11 }, () => 0); const typeCounts = new Map(); const colorCounts = new Map(); const ramLimits = new Map(); const highestRam = new Map(); const overLimit = new Map(); // The cards behind each bar and segment, so the deck page can highlight them. const costRefs = new Map(); const typeRefs = new Map(); const colorRefs = new Map(); const mainCards = []; const mainDeck = {}; let legendCount = 0; let mainCount = 0; let sellableCount = 0; let costTotal = 0; let costCount = 0; let powerTotal = 0; let powerCount = 0; Object.keys(deck).forEach((cardId) => { if (!isRecord(catalog[cardId])) { return; } const quantity = deck[cardId]; const game = cardGame(catalog[cardId]); const type = typeof game.cardType === "string" && game.cardType.length > 0 ? game.cardType : "unknown"; const color = COLOR_ORDER.indexOf(game.color) === -1 ? null : game.color; const ram = Number.isFinite(game.ram) ? Math.max(0, Math.floor(game.ram)) : 0; // Legends sit in their own pile: they only raise their colour's RAM limit. if (type === LEGEND_TYPE) { legendCount += quantity; if (color !== null) { ramLimits.set(color, (ramLimits.get(color) ?? 0) + ram * quantity); } return; } mainCount += quantity; mainDeck[cardId] = quantity; mainCards.push({ color, ram, quantity }); if (Number.isFinite(game.cost)) { const cost = Math.max(0, Math.floor(game.cost)); const costIndex = Math.min(cost, 10); costBuckets[costIndex] += quantity; addRef(costRefs, costIndex, cardId); costTotal += cost * quantity; costCount += quantity; } if (Number.isFinite(game.power)) { powerTotal += Math.max(0, game.power) * quantity; powerCount += quantity; } if (game.sellable === true) { sellableCount += quantity; } typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity); addRef(typeRefs, type, cardId); if (color !== null) { colorCounts.set(color, (colorCounts.get(color) ?? 0) + quantity); addRef(colorRefs, color, cardId); highestRam.set(color, Math.max(highestRam.get(color) ?? 0, ram)); } }); // Over-limit copies need every Legend's RAM first, so they are counted after the pass. mainCards.forEach((card) => { if (card.color !== null && card.ram > (ramLimits.get(card.color) ?? 0)) { overLimit.set(card.color, (overLimit.get(card.color) ?? 0) + card.quantity); } }); // One row per colour the deck touches (a Legend or a main-deck card): its // main-deck cards, their highest RAM, the Legends' limit and the copies over it. const ramRows = COLOR_ORDER.filter((color) => colorCounts.has(color) || ramLimits.has(color)).map((color) => [ titleCase(color), colorCounts.get(color) ?? 0, highestRam.get(color) ?? 0, ramLimits.get(color) ?? 0, overLimit.get(color) ?? 0, ]); const widgets = [ { kind: "stat", label: "Total cards", labelKey: "totalCards", value: mainCount }, { kind: "stat", label: "Legends", labelKey: "cyberpunk.legends", value: legendCount }, { kind: "table", label: "RAM", labelKey: "cyberpunk.ram", columns: ["Color", "Cards", "Highest RAM", "RAM limit", "Over limit"], columnKeys: ["cyberpunk.ramTable.color", "cyberpunk.ramTable.cards", "cyberpunk.ramTable.highest", "cyberpunk.ramTable.limit", "cyberpunk.ramTable.overLimit"], rows: ramRows, }, { kind: "histogram", label: "Cost curve", labelKey: "cyberpunk.costCurve", buckets: costBuckets, labels: COST_CURVE_LABELS, bucketCardRefs: bucketRefList(costRefs, costBuckets.length) }, { kind: "ratio", label: "Sell tag share", labelKey: "cyberpunk.sellTagShare", numerator: sellableCount, denominator: mainCount, format: "percent" }, { kind: "donut", label: "Card types", labelKey: "cyberpunk.cardTypes", vocabulary: "cyberpunk.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) }, { kind: "donut", label: "Colors", labelKey: "cyberpunk.colors", vocabulary: "cyberpunk.color", segments: withCardRefs(orderedSegments(colorCounts, COLOR_ORDER), colorRefs) }, { kind: "stat", label: "Average cost", labelKey: "cyberpunk.averageCost", value: costCount > 0 ? roundTo(costTotal / costCount, 2) : 0 }, { kind: "stat", label: "Average power", labelKey: "cyberpunk.averagePower", value: powerCount > 0 ? roundTo(powerTotal / powerCount, 2) : 0 }, ]; { const pile = mainDeck; const chanceHand = 6; // Distinct-card table: one row per distinct card (keyed by name) in the // match set, with the configured metric columns. All combinatorics are // inline — the sandbox cannot import a helper. const containsValue = (haystack, needle) => { if (Array.isArray(haystack)) { return haystack.indexOf(needle) !== -1; } if (haystack === undefined || haystack === null) { return false; } return String(haystack).indexOf(String(needle)) !== -1; }; const lineCopies = new Map(); const linePrintings = new Map(); const lineCards = new Map(); const lineOrder = []; let deckSize = 0; let matchTotal = 0; Object.keys(pile).forEach((ref) => { const quantity = Number(pile[ref]) || 0; if (quantity <= 0) { return; } deckSize = deckSize + quantity; const card = cardsById[ref]; const row = { quantity: quantity, card: card, ref: ref }; if (!(true)) { return; } matchTotal = matchTotal + quantity; const key = String(row.card !== null && row.card !== undefined && typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref); if (!lineCopies.has(key)) { lineCopies.set(key, 0); linePrintings.set(key, 0); lineCards.set(key, row); lineOrder.push(key); } lineCopies.set(key, lineCopies.get(key) + quantity); linePrintings.set(key, linePrintings.get(key) + 1); }); // P(the opening hand contains none of a pool of `excluded` cards), drawing // `drawCount` without replacement — a running product of draw ratios so a // 60-card deck never overflows a factorial. 0 when the pool leaves too few // safe cards to fill the hand. const probNoneOf = (excluded, drawCount) => { if (deckSize - excluded < drawCount) { return 0; } let probability = 1; for (let i = 0; i < drawCount; i = i + 1) { probability = (probability * (deckSize - excluded - i)) / (deckSize - i); } return probability; }; // Clamp to [0,1] and render as a 2-decimal percentage string. const formatPercent = (value) => { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; }; const entries = lineOrder.map((key) => { const copies = lineCopies.get(key); return { key: key, copies: copies, printings: linePrintings.get(key), row: lineCards.get(key), otherMatches: matchTotal - copies, }; }); // Highest copy count first (== highest possible-starter odds for fixed // draws); ties broken by key. entries.sort((left, right) => { if (right.copies !== left.copies) { return right.copies - left.copies; } return left.key < right.key ? -1 : left.key > right.key ? 1 : 0; }); widgets.push({ kind: "table", label: "Chance to see", columns: ["Card", "Hand", "Mulligan", "+1 draw", "+3 draws"], rows: entries.map((entry) => { const row = entry.row; return [entry.key, (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand, deckSize)))), (formatPercent(1 - Math.pow(probNoneOf(entry.copies, Math.min(chanceHand, deckSize)), 2))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 1, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 3, deckSize))))]; }), }); const chanceTable = widgets[widgets.length - 1]; chanceTable.labelKey = "chanceToSee"; chanceTable.columnKeys = [ "chanceToSeeColumns.card", "chanceToSeeColumns.openingHand", "chanceToSeeColumns.mulligan", "chanceToSeeColumns.afterOneDraw", "chanceToSeeColumns.afterThreeDraws", ]; } return { widgets }; } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } ``` ```js [Flesh and Blood] const COST_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7+"]; // Pitch value -> colour-bar key (the fab.pitch vocabulary is keyed by colour). const PITCH_COLORS = { 1: "red", 2: "yellow", 3: "blue" }; const PITCH_ORDER = ["red", "yellow", "blue"]; // Types that never sit in a deck list: skipped everywhere but the total. const NON_DECK_TYPES = ["token", "demi_hero", "macro", "event"]; // A main-deck card's one display type: the first of these its types carry. An // attack action reads as "attack", any other action as "action". const TYPE_ORDER = ["attack", "action", "attack_reaction", "defense_reaction", "instant", "block", "resource", "mentor"]; const TYPE_PRIORITY = ["attack_reaction", "defense_reaction", "instant", "attack", "action", "block", "resource", "mentor"]; // English fallbacks; the fab.cardType vocabulary supplies the shown label. const TYPE_LABELS = { attack: "Attack", action: "Action", attack_reaction: "Attack reaction", defense_reaction: "Defense reaction", instant: "Instant", block: "Block", resource: "Resource", mentor: "Mentor", }; // The attack vs non-attack split's second key, beside the "attack" card type. const NON_ATTACK = "non_attack"; // Classes in canonical order; "generic" cards go in any deck and sit last. const CLASS_ORDER = ["adjudicator", "assassin", "bard", "brute", "guardian", "illusionist", "mechanologist", "merchant", "necromancer", "ninja", "pirate", "ranger", "runeblade", "shapeshifter", "thief", "warrior", "wizard", "generic"]; const GENERIC = "generic"; // A card blocks well when its defense is at least this. const BLOCKER_DEFENSE = 3; // Hand size when the list names no hero (most adult and young heroes draw 4). const DEFAULT_INTELLECT = 4; // The opening-hand table's rows: at least 1, 2 and 3 of a colour bar. const OPENING_HAND_AT_LEAST = [1, 2, 3]; export default function compute(pile, cardsById) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; const curveBuckets = Array.from({ length: COST_CURVE_LABELS.length }, () => 0); const pitchCounts = new Map(); const typeCounts = new Map(); const splitCounts = new Map(); const classCounts = new Map(); // The cards behind each bar and segment, so the deck page can highlight them. const curveRefs = new Map(); const pitchRefs = new Map(); const typeRefs = new Map(); const splitRefs = new Map(); const classRefs = new Map(); // The main deck by ref: what the chance-to-see odds draw from. const mainDeck = {}; let total = 0; let heroes = 0; let weapons = 0; let equipment = 0; let main = 0; let pitchTotal = 0; let costTotal = 0; let costed = 0; let power = 0; let defense = 0; let blockers = 0; let intellect = DEFAULT_INTELLECT; Object.keys(deck).forEach((cardId) => { const quantity = deck[cardId]; const card = catalog[cardId]; if (!isRecord(card)) { total += quantity; return; } const game = cardGame(card); const types = Array.isArray(game.types) ? game.types : []; const has = (type) => types.indexOf(type) !== -1; if (has("hero") || game.isHero === true) { heroes += quantity; if (Number.isFinite(game.intelligence) && game.intelligence > 0) { intellect = Math.floor(game.intelligence); } return; } if (has("weapon")) { weapons += quantity; total += quantity; return; } // Inventory that is not a weapon: equipment, plus Companions (typed ally // and companion) that take the off-hand slot without the Equipment type. if (has("equipment") || (game.equipmentSlot !== undefined && game.equipmentSlot !== null)) { equipment += quantity; total += quantity; return; } if (NON_DECK_TYPES.some(has)) { return; } main += quantity; total += quantity; mainDeck[cardId] = quantity; const pitchColor = Number.isFinite(game.pitch) ? PITCH_COLORS[game.pitch] : undefined; if (pitchColor !== undefined) { pitchCounts.set(pitchColor, (pitchCounts.get(pitchColor) ?? 0) + quantity); addRef(pitchRefs, pitchColor, cardId); pitchTotal += game.pitch * quantity; } if (Number.isFinite(game.cost)) { const cost = Math.max(0, Math.floor(game.cost)); const curveIndex = Math.min(cost, COST_CURVE_LABELS.length - 1); curveBuckets[curveIndex] += quantity; addRef(curveRefs, curveIndex, cardId); costTotal += cost * quantity; costed += quantity; } const type = TYPE_PRIORITY.find(has); if (type !== undefined) { typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity); addRef(typeRefs, type, cardId); } const split = has("attack") ? "attack" : NON_ATTACK; splitCounts.set(split, (splitCounts.get(split) ?? 0) + quantity); addRef(splitRefs, split, cardId); const cardClass = primaryClass(game); classCounts.set(cardClass, (classCounts.get(cardClass) ?? 0) + quantity); addRef(classRefs, cardClass, cardId); if (Number.isFinite(game.power)) { power += Math.max(0, game.power) * quantity; } if (Number.isFinite(game.defense)) { defense += Math.max(0, game.defense) * quantity; if (game.defense >= BLOCKER_DEFENSE) { blockers += quantity; } } }); // Means over the main deck, to one decimal: pitch over every main-deck card // (a card without a colour bar pitches nothing), cost over the costed ones. const averagePitch = main > 0 ? roundTo(pitchTotal / main, 1) : 0; const averageCost = costed > 0 ? roundTo(costTotal / costed, 1) : 0; // Over every main-deck card, so a pitch-only or cost-only card still counts. const resourceSurplus = main > 0 ? roundTo((pitchTotal - costTotal) / main, 2) : 0; const blockerShare = main > 0 ? formatPercentValue(blockers / main) : "0.00%"; const attackSplit = ["attack", NON_ATTACK].map((key) => ({ key, label: key === NON_ATTACK ? "Non-attack" : "Attack", value: splitCounts.get(key) ?? 0, color: "", cardRefs: splitRefs.get(key) ?? [], })); const widgets = [ { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total }, { kind: "table", label: "Deck zones", labelKey: "fab.deckZones", columns: ["Hero", "Weapons", "Equipment", "Main deck"], columnKeys: ["fab.zones.hero", "fab.zones.weapons", "fab.zones.equipment", "fab.zones.mainDeck"], rows: [[heroes, weapons, equipment, main]], }, { kind: "donut", label: "Pitch", labelKey: "fab.pitch", vocabulary: "fab.pitch", segments: withCardRefs(orderedSegments(pitchCounts, PITCH_ORDER), pitchRefs) }, { kind: "stat", label: "Average pitch", labelKey: "fab.averagePitch", value: averagePitch }, { kind: "histogram", label: "Cost curve", labelKey: "fab.costCurve", buckets: curveBuckets, labels: COST_CURVE_LABELS, bucketCardRefs: bucketRefList(curveRefs, curveBuckets.length) }, { kind: "stat", label: "Average cost", labelKey: "fab.averageCost", value: averageCost }, { kind: "donut", label: "Card types", labelKey: "fab.cardTypes", vocabulary: "fab.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER, TYPE_LABELS), typeRefs) }, { kind: "gauge", label: "Attack / non-attack", labelKey: "fab.attackSplit", vocabulary: "fab.cardType", segments: attackSplit }, { kind: "donut", label: "Classes", labelKey: "fab.classes", vocabulary: "fab.class", segments: withCardRefs(orderedSegments(classCounts, CLASS_ORDER), classRefs) }, { kind: "stat", label: "Total power", labelKey: "fab.totalPower", value: power }, { kind: "stat", label: "Total defense", labelKey: "fab.totalDefense", value: defense }, { kind: "stat", label: "Blocks for 3+", labelKey: "fab.blockers", value: blockers }, { kind: "stat", label: "Share that blocks for 3+", labelKey: "fab.blockerShare", value: blockerShare }, { kind: "stat", label: "Pitch minus cost per card", labelKey: "fab.resourceSurplus", value: resourceSurplus }, { kind: "stat", label: "Hand size (intellect)", labelKey: "fab.handSize", value: intellect }, ].concat(openingHandTable(main, pitchCounts, intellect)); { const pile = mainDeck; const chanceHand = intellect; // Distinct-card table: one row per distinct card (keyed by name) in the // match set, with the configured metric columns. All combinatorics are // inline — the sandbox cannot import a helper. const containsValue = (haystack, needle) => { if (Array.isArray(haystack)) { return haystack.indexOf(needle) !== -1; } if (haystack === undefined || haystack === null) { return false; } return String(haystack).indexOf(String(needle)) !== -1; }; const lineCopies = new Map(); const linePrintings = new Map(); const lineCards = new Map(); const lineOrder = []; let deckSize = 0; let matchTotal = 0; Object.keys(pile).forEach((ref) => { const quantity = Number(pile[ref]) || 0; if (quantity <= 0) { return; } deckSize = deckSize + quantity; const card = cardsById[ref]; const row = { quantity: quantity, card: card, ref: ref }; if (!(true)) { return; } matchTotal = matchTotal + quantity; const key = String((typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref) + (Number.isFinite(cardGame(row.card).pitch) && PITCH_COLORS[cardGame(row.card).pitch] !== undefined ? " (" + titleCase(PITCH_COLORS[cardGame(row.card).pitch]) + ")" : "")); if (!lineCopies.has(key)) { lineCopies.set(key, 0); linePrintings.set(key, 0); lineCards.set(key, row); lineOrder.push(key); } lineCopies.set(key, lineCopies.get(key) + quantity); linePrintings.set(key, linePrintings.get(key) + 1); }); // P(the opening hand contains none of a pool of `excluded` cards), drawing // `drawCount` without replacement — a running product of draw ratios so a // 60-card deck never overflows a factorial. 0 when the pool leaves too few // safe cards to fill the hand. const probNoneOf = (excluded, drawCount) => { if (deckSize - excluded < drawCount) { return 0; } let probability = 1; for (let i = 0; i < drawCount; i = i + 1) { probability = (probability * (deckSize - excluded - i)) / (deckSize - i); } return probability; }; // Clamp to [0,1] and render as a 2-decimal percentage string. const formatPercent = (value) => { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; }; const entries = lineOrder.map((key) => { const copies = lineCopies.get(key); return { key: key, copies: copies, printings: linePrintings.get(key), row: lineCards.get(key), otherMatches: matchTotal - copies, }; }); // Highest copy count first (== highest possible-starter odds for fixed // draws); ties broken by key. entries.sort((left, right) => { if (right.copies !== left.copies) { return right.copies - left.copies; } return left.key < right.key ? -1 : left.key > right.key ? 1 : 0; }); widgets.push({ kind: "table", label: "Chance to see", columns: ["Card", "Hand", "2 hands"], rows: entries.map((entry) => { const row = entry.row; return [entry.key, (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand * 2, deckSize))))]; }), }); const chanceTable = widgets[widgets.length - 1]; chanceTable.labelKey = "chanceToSee"; chanceTable.columnKeys = [ "chanceToSeeColumns.card", "chanceToSeeColumns.openingHand", "chanceToSeeColumns.twoHands", ]; } return { widgets }; } // The chance an opening hand of `handSize` cards from the main deck holds at // least N cards of each colour bar (hypergeometric), one row per N. function openingHandTable(deckSize, pitchCounts, handSize) { if (deckSize <= 0) { return []; } const dealt = Math.min(handSize, deckSize); return [ { kind: "table", label: "Opening hand odds", labelKey: "fab.openingHand", columns: ["At least", "Red", "Yellow", "Blue"], columnKeys: ["fab.openingHandAtLeast", "fab.pitchColors.red", "fab.pitchColors.yellow", "fab.pitchColors.blue"], rows: OPENING_HAND_AT_LEAST.filter((count) => count <= dealt).map((count) => [count].concat( PITCH_ORDER.map((color) => formatOdds(atLeastChance(deckSize, pitchCounts.get(color) ?? 0, dealt, count))), ), ), }, ]; } // P(at least `wanted` of `copies` among `draws` cards from `size`). function atLeastChance(size, copies, draws, wanted) { const total = choose(size, draws); if (total <= 0) { return 0; } let below = 0; for (let hits = 0; hits < wanted; hits += 1) { below += (choose(copies, hits) * choose(size - copies, draws - hits)) / total; } return Math.max(0, 1 - below); } function choose(n, k) { if (k < 0 || k > n) { return 0; } let result = 1; for (let i = 1; i <= Math.min(k, n - k); i += 1) { result = (result * (n - Math.min(k, n - k) + i)) / i; } return result; } function formatOdds(value) { return (Math.round(value * 1000) / 10).toFixed(1) + "%"; } // The class a card counts toward: its first non-generic class in canonical // order (a hybrid card reads as the earlier class), else generic. function primaryClass(game) { const classes = Array.isArray(game.classes) ? game.classes : []; const known = CLASS_ORDER.filter((value) => value !== GENERIC && classes.indexOf(value) !== -1); return known.length > 0 ? known[0] : GENERIC; } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } ``` ```js [Hearthstone] const MANA_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7+"]; // The playable classes in canonical order; "neutral" is any class's card. const CLASS_ORDER = ["deathknight", "demonhunter", "druid", "hunter", "mage", "paladin", "priest", "rogue", "shaman", "warlock", "warrior"]; const NEUTRAL = "neutral"; const CLASS_LABELS = { deathknight: "Death Knight", demonhunter: "Demon Hunter", druid: "Druid", hunter: "Hunter", mage: "Mage", paladin: "Paladin", priest: "Priest", rogue: "Rogue", shaman: "Shaman", warlock: "Warlock", warrior: "Warrior", neutral: "Neutral", }; // Deck-card types in display order; unexpected types trail by count. const TYPE_ORDER = ["minion", "spell", "weapon", "location", "hero"]; // Rarities lowest to highest; the rarity donut keeps this order. const RARITY_ORDER = ["free", "common", "rare", "epic", "legendary"]; // Arcane Dust to craft one regular (non-golden) copy, by rarity — the in-game // crafting table (https://hearthstone.wiki.gg/wiki/Crafting): Common 40, Rare // 100, Epic 400, Legendary 1600. Free cards can't be crafted (every player owns // them), so they cost nothing; an unknown rarity is treated the same. A copy of // HEARTHSTONE_DUST_BY_RARITY's craft costs (a spec keeps them in sync). const DUST_COST = { common: 40, rare: 100, epic: 400, legendary: 1600 }; // Upstream set tokens whose regular printings can't be crafted, so a printing // from one costs no dust whatever its rarity: the Core set (free to every // player; CORE_HIDDEN holds the stat-changed Core copies old deckstrings name), // Demon Hunter Initiate (free with the class) and Event (reward cards). Path // of Arthas is craftable. A copy of HEARTHSTONE_UNCRAFTABLE_SET_IDS (a spec // keeps them in sync; its doc cites the sources). const UNCRAFTABLE_SETS = ["CORE", "CORE_HIDDEN", "DEMON_HUNTER_INITIATE", "EVENT"]; // Draw odds. Going first you draw 3; on the coin you draw 4 and get The Coin, // which comes from outside the deck. Both players also draw at the start of // every turn, turn 1 included, so by your turn N you have seen 3 + N cards // going first and 4 + N on the coin. const OPENING_HAND_FIRST = 3; const OPENING_HAND_COIN = 4; const DRAW_ODDS_TURNS = [1, 2, 3, 4, 5, 6]; const DRAW_ODDS_COPIES = [1, 2]; export default function compute(pile, cardsById, ctx) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; const curveBuckets = Array.from({ length: MANA_CURVE_LABELS.length }, () => 0); const typeCounts = new Map(); const rarityCounts = new Map(); // The cards behind each bar and segment, so the deck page can highlight them. const curveRefs = new Map(); const typeRefs = new Map(); const rarityRefs = new Map(); let total = 0; let library = 0; let dust = 0; let legendaries = 0; const entries = []; Object.keys(deck).forEach((cardId) => { const quantity = deck[cardId]; total += quantity; const card = catalog[cardId]; // Only collectible cards are ever shuffled into the deck (as in the sample // hand); an unresolved card still counts, so the library never shrinks. if (!isRecord(card) || card.collectible !== false) { library += quantity; } if (!isRecord(card)) { return; } const game = cardGame(card); entries.push({ ref: cardId, quantity, classes: cardClasses(game) }); const cost = Number.isFinite(game.cost) ? Math.max(0, Math.floor(game.cost)) : 0; const curveIndex = Math.min(cost, MANA_CURVE_LABELS.length - 1); curveBuckets[curveIndex] += quantity; addRef(curveRefs, curveIndex, cardId); if (typeof game.cardType === "string" && game.cardType.length > 0) { typeCounts.set(game.cardType, (typeCounts.get(game.cardType) ?? 0) + quantity); addRef(typeRefs, game.cardType, cardId); } const rarity = typeof game.rarity === "string" ? game.rarity : ""; if (RARITY_ORDER.indexOf(rarity) !== -1) { rarityCounts.set(rarity, (rarityCounts.get(rarity) ?? 0) + quantity); addRef(rarityRefs, rarity, cardId); } dust += craftCost(card, cardId, rarity) * quantity; if (rarity === "legendary") { legendaries += quantity; } }); // The sideboards: only collectible cards are crafted (E.T.C.'s band); an // unresolved ref can't be told from a Zilliax module, so it costs nothing. const attached = normalizePile(isRecord(ctx) ? ctx.attachedPile : null); Object.keys(attached).forEach((cardId) => { const card = catalog[cardId]; if (!isRecord(card) || card.collectible === false || cardGame(card).zilliaxModule != null) { return; } const rarity = cardGame(card).rarity; dust += craftCost(card, cardId, typeof rarity === "string" ? rarity : "") * attached[cardId]; }); return { widgets: [ { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total }, { kind: "stat", label: "Dust cost", labelKey: "hearthstone.dustCost", value: dust }, { kind: "stat", label: "Legendaries", labelKey: "hearthstone.legendaries", value: legendaries }, { kind: "histogram", label: "Mana curve", labelKey: "hearthstone.manaCurve", buckets: curveBuckets, labels: MANA_CURVE_LABELS, bucketCardRefs: bucketRefList(curveRefs, curveBuckets.length) }, { kind: "donut", label: "Classes", labelKey: "hearthstone.classes", vocabulary: "hearthstone.class", segments: classSegments(entries) }, { kind: "bars", label: "Card types", labelKey: "cardTypes", vocabulary: "hearthstone.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) }, { kind: "donut", label: "Rarity", labelKey: "hearthstone.rarity", vocabulary: "hearthstone.rarity", segments: withCardRefs(orderedSegments(rarityCounts, RARITY_ORDER), rarityRefs) }, ].concat(drawOddsTables(library)), }; } // ---- Draw odds --------------------------------------------------------------- // The chance to have at least one copy of a card by your turn N, for a card the // deck runs once or twice. The mulligan is modelled as hunting for that card: // keep the opener when it holds a copy, otherwise replace every card. Like the // game (and the sample hand), the replacements are drawn first and only then do // the replaced cards shuffle back, so a replacement is never a card you just // threw away. The deck size comes from the pile, so 30- and 40-card decks work. function drawOddsTables(library) { if (library <= 0) { return []; } const table = (label, labelKey, opener) => ({ kind: "table", label, labelKey, columns: ["Turn", "1 copy", "2 copies"], columnKeys: ["hearthstone.drawOdds.turn", "hearthstone.drawOdds.oneCopy", "hearthstone.drawOdds.twoCopies"], rows: DRAW_ODDS_TURNS.map((turn) => [turn].concat(DRAW_ODDS_COPIES.map((copies) => formatOdds(drawOdds(library, copies, opener, turn)))), ), }); return [ table("Draw odds going first (mulligan for it)", "hearthstone.drawOddsGoingFirst", OPENING_HAND_FIRST), table("Draw odds on the coin (mulligan for it)", "hearthstone.drawOddsOnCoin", OPENING_HAND_COIN), ]; } // P(at least one of `copies` in a `deckSize` deck by turn `turn`), from an // `opener`-card opening hand and a mulligan that hunts for the card. It misses // only when the opener, the replacements and the turn draws all miss. function drawOdds(deckSize, copies, opener, turn) { const copiesInDeck = Math.min(copies, deckSize); const dealt = Math.min(opener, deckSize); const missOpener = missChance(deckSize, copiesInDeck, dealt); // After a full mulligan the opener's cards are back in the deck, but the // hand still holds `dealt` non-copies, so the rest draws from the others. const remaining = deckSize - dealt; const missReplacements = missChance(remaining, copiesInDeck, Math.min(dealt, remaining)); const missDraws = missChance(remaining, copiesInDeck, Math.min(turn, remaining)); return 1 - missOpener * missReplacements * missDraws; } // P(no copy among `draws` cards drawn from `size` cards holding `copies`). function missChance(size, copies, draws) { if (draws <= 0 || copies <= 0) { return 1; } const total = choose(size, draws); return total > 0 ? choose(size - copies, draws) / total : 0; } function choose(n, k) { if (k < 0 || k > n) { return 0; } let result = 1; for (let i = 1; i <= Math.min(k, n - k); i += 1) { result = (result * (n - Math.min(k, n - k) + i)) / i; } return result; } function formatOdds(value) { return (Math.round(value * 1000) / 10).toFixed(1) + "%"; } // Arcane Dust to craft one copy of the printing the pile names: its rarity's // cost, or nothing for a Free, uncraftable-set or marked-uncraftable printing. function craftCost(card, cardId, identityRarity) { const printing = cardPrinting(card, cardId); const craftRarity = printingRarity(printing, identityRarity); if ( RARITY_ORDER.indexOf(craftRarity) === -1 || UNCRAFTABLE_SETS.indexOf(printingSet(card, printing)) !== -1 || markedUncraftable(card, printing) ) { return 0; } return DUST_COST[craftRarity] ?? 0; } // The printings entry the pile names; undefined for an identity ref. function cardPrinting(card, cardId) { const printings = Array.isArray(card.printings) ? card.printings : []; return printings.find((entry) => isRecord(entry) && entry.id === cardId); } // The set of the printing the pile names: its setCode, else (an identity ref) // the default printing's game.setId. function printingSet(card, printing) { if (printing && typeof printing.setCode === "string") { return printing.setCode; } const game = cardGame(card); return typeof game.setId === "string" ? game.setId : ""; } // The catalog marked the named printing (else, for an identity ref, the // default printing) `metadata.craftable: false`: a card with a special unlock // (Prince Renathal, the Gift cards, …) that can't be crafted (#1251). A copy of // isHearthstonePrintingMarkedUncraftable. function markedUncraftable(card, printing) { const named = printing ?? cardPrinting(card, cardGame(card).defaultPrintingId); return Boolean(named) && isRecord(named.metadata) && named.metadata.craftable === false; } // The named printing's own rarity (`metadata.rarity`), else the identity's: a // Legacy Basic printing of a Core card is Free while the identity reads Common. function printingRarity(printing, identityRarity) { const metadata = printing && isRecord(printing.metadata) ? printing.metadata : {}; return typeof metadata.rarity === "string" && metadata.rarity.length > 0 ? metadata.rarity : identityRarity; } // The card's playable classes in canonical order; ["neutral"] when it names // none (or only unknown tokens). function cardClasses(game) { const classes = Array.isArray(game.classes) ? game.classes : []; const known = CLASS_ORDER.filter((value) => classes.indexOf(value) !== -1); return known.length > 0 ? known : [NEUTRAL]; } // Class vs Neutral: the deck's class is the one most single-class cards share; // a multi-class card counts toward it when it carries it, else toward its first // class. Classes by copies (highest first), Neutral last. function classSegments(entries) { const singleClassCounts = new Map(); entries.forEach((entry) => { if (entry.classes.length === 1 && entry.classes[0] !== NEUTRAL) { singleClassCounts.set(entry.classes[0], (singleClassCounts.get(entry.classes[0]) ?? 0) + entry.quantity); } }); const deckClasses = CLASS_ORDER.filter((value) => singleClassCounts.has(value)).sort( (left, right) => singleClassCounts.get(right) - singleClassCounts.get(left), ); const counts = new Map(); const refs = new Map(); entries.forEach((entry) => { const key = deckClasses.find((value) => entry.classes.indexOf(value) !== -1) ?? entry.classes[0]; counts.set(key, (counts.get(key) ?? 0) + entry.quantity); addRef(refs, key, entry.ref); }); const rank = (key) => (key === NEUTRAL ? CLASS_ORDER.length : 0); const segments = []; counts.forEach((value, key) => { segments.push({ key, label: CLASS_LABELS[key] ?? key, value, color: "", cardRefs: refs.get(key) ?? [] }); }); return segments.sort( (left, right) => rank(left.key) - rank(right.key) || right.value - left.value || CLASS_ORDER.indexOf(left.key) - CLASS_ORDER.indexOf(right.key), ); } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } ``` ```js [Legends of Runeterra] const MANA_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+"]; // Card-type keys in display order, with English fallback labels. const TYPE_LABELS = { champions: "Champion", followers: "Follower", spells: "Spell", landmarks: "Landmark", equipment: "Equipment", }; export default function compute(pile, cardsById) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; // Cards missing from the catalog can't be classified, so they count nowhere. const entries = Object.keys(deck) .filter((cardId) => isRecord(catalog[cardId])) .map((cardId) => { const card = catalog[cardId]; const game = cardGame(card); return { ref: cardId, card, game, quantity: deck[cardId], cost: cardCost(game), regionRefs: cardRegionRefs(game) }; }) .sort(compareDeckCards); const deckRegions = detectDeckRegions(entries); const manaBuckets = Array.from({ length: 11 }, () => 0); const typeCounts = { champions: 0, followers: 0, spells: 0, landmarks: 0, equipment: 0 }; const rarityCounts = new Map(); const regionCounts = new Map(); // The cards behind each bar and segment, so the deck page can highlight them. const manaRefs = new Map(); const typeRefs = new Map(); const rarityRefs = new Map(); const regionCardRefs = new Map(); let costTotal = 0; let cardTotal = 0; entries.forEach((entry) => { const game = entry.game; const quantity = entry.quantity; const manaIndex = Math.min(entry.cost, 10); manaBuckets[manaIndex] += quantity; addRef(manaRefs, manaIndex, entry.ref); costTotal += entry.cost * quantity; cardTotal += quantity; // Categorize by the canonical (English) type ref, falling back to the // localized value for catalogs published before the refs existed. const type = game.typeRef ?? game.type; const supertype = game.supertypeRef ?? game.supertype; let typeKey = null; if (type === "Unit") { typeKey = supertype === "Champion" ? "champions" : "followers"; } else if (type === "Spell") { typeKey = "spells"; } else if (type === "Landmark") { typeKey = "landmarks"; } else if (type === "Equipment") { typeKey = "equipment"; } if (typeKey !== null) { typeCounts[typeKey] += quantity; addRef(typeRefs, typeKey, entry.ref); } const rarityRef = typeof game.rarityRef === "string" ? game.rarityRef : "Unknown"; rarityCounts.set(rarityRef, (rarityCounts.get(rarityRef) ?? 0) + quantity); addRef(rarityRefs, rarityRef, entry.ref); // A card counts toward the first deck region it carries, so counts sum to // the deck size even for multi-region cards; one fitting none is skipped. const region = deckRegions.find((candidate) => entry.regionRefs.indexOf(candidate) !== -1); if (region !== undefined) { regionCounts.set(region, (regionCounts.get(region) ?? 0) + quantity); addRef(regionCardRefs, region, entry.ref); } }); // Regions keep deck-region order; empty ones drop out. const regionSegments = deckRegions .filter((region) => (regionCounts.get(region) ?? 0) > 0) .map((region) => ({ key: region, label: region, value: regionCounts.get(region), color: "", cardRefs: regionCardRefs.get(region) ?? [] })); const typeSegments = Object.keys(TYPE_LABELS) .filter((key) => typeCounts[key] > 0) .map((key) => ({ key, label: TYPE_LABELS[key], value: typeCounts[key], color: "", cardRefs: typeRefs.get(key) ?? [] })); // Most copies first; ties keep card order. const raritySegments = []; rarityCounts.forEach((value, key) => { if (value > 0) { raritySegments.push({ key, label: key, value, color: "", cardRefs: rarityRefs.get(key) ?? [] }); } }); raritySegments.sort((left, right) => right.value - left.value); // Mean mana cost across the deck, weighted by copies, to one decimal. const averageCost = cardTotal > 0 ? Math.round((costTotal / cardTotal) * 10) / 10 : 0; // Units (champions + followers) against spells, as a reduced pair. const unitCount = typeCounts.champions + typeCounts.followers; const spellCount = typeCounts.spells; // Like the deck page, a breakdown with nothing to show is left out. const widgets = []; if (regionSegments.length > 0) { widgets.push({ kind: "bars", label: "Regions", labelKey: "lor.regions", vocabulary: "lor.region", segments: regionSegments }); } widgets.push({ kind: "histogram", label: "Mana Curve", labelKey: "lor.manaCurve", buckets: manaBuckets, labels: MANA_CURVE_LABELS, bucketCardRefs: bucketRefList(manaRefs, manaBuckets.length) }); if (typeSegments.length > 0) { widgets.push({ kind: "donut", label: "Card Types", labelKey: "lor.cardTypes", vocabulary: "lor.cardType", segments: typeSegments }); } if (raritySegments.length > 0) { widgets.push({ kind: "donut", label: "Rarity", labelKey: "lor.rarity", vocabulary: "lor.rarity", segments: raritySegments }); } widgets.push({ kind: "stat", label: "Average Cost", labelKey: "lor.averageCost", value: averageCost }); widgets.push({ kind: "ratio", label: "Units : Spells", labelKey: "lor.unitsToSpells", numerator: unitCount, denominator: spellCount, format: "ratio" }); return { widgets }; } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } function cardName(card) { return isRecord(card) && typeof card.name === "string" ? card.name : ""; } function cardCost(game) { return Number.isFinite(game.cost) ? Math.max(0, Math.floor(game.cost)) : 0; } function cardRegionRefs(game) { return Array.isArray(game.regionRefs) ? game.regionRefs.filter((ref) => typeof ref === "string" && ref.length > 0) : []; } // The deck page's card order: by cost, then by name. function compareDeckCards(left, right) { return left.cost - right.cost || cardName(left.card).localeCompare(cardName(right.card)); } // The deck's regions, as the deck page derives them: every single-region // card's region in card order, then (only if some card still fits none) the // other regions of those unaccounted cards, never a Runeterra champion's // card-code ref. function detectDeckRegions(entries) { const regions = []; entries.forEach((entry) => { if (entry.regionRefs.length === 1 && regions.indexOf(entry.regionRefs[0]) === -1) { regions.push(entry.regionRefs[0]); } }); entries .filter((entry) => !entry.regionRefs.some((ref) => regions.indexOf(ref) !== -1)) .forEach((entry) => { entry.regionRefs.forEach((ref) => { if (!/^\d/.test(ref) && regions.indexOf(ref) === -1) { regions.push(ref); } }); }); return regions; } ``` ```js [Magic: The Gathering] const MANA_VALUE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7+"]; // WUBRG, the order pips and sources are charted in; "C" is colorless mana. const COLORS = ["W", "U", "B", "R", "G"]; const MANA_ORDER = ["W", "U", "B", "R", "G", "C"]; // Each card counts once, toward the first of these on its type line, so the // donut sums to the deck (an Artifact Creature is a creature, a creature-land a // creature). Keys are the lowercase type names. const TYPE_PRIORITY = ["Creature", "Planeswalker", "Battle", "Instant", "Sorcery", "Artifact", "Enchantment", "Land"]; const TYPE_LABELS = { creature: "Creatures", planeswalker: "Planeswalkers", battle: "Battles", instant: "Instants", sorcery: "Sorceries", artifact: "Artifacts", enchantment: "Enchantments", land: "Lands", }; const COLOR_LABELS = { W: "White", U: "Blue", B: "Black", R: "Red", G: "Green", C: "Colorless" }; // The opening hand the land stats draw: 7 cards, split by exact land count. const OPENING_HAND_SIZE = 7; const OPENING_HAND_LAND_COUNTS = [0, 1, 2, 3, 4, 5]; // Karsten's target: castable on curve at least 90% of the time. const MANA_CHECK_TARGET = 0.9; // Basic land subtype -> the color a land carrying it taps for. const LAND_SUBTYPE_COLORS = [ [/\bPlains\b/, "W"], [/\bIsland\b/, "U"], [/\bSwamp\b/, "B"], [/\bMountain\b/, "R"], [/\bForest\b/, "G"], ]; const ANY_COLOR_PATTERN = /any (one )?colors?|any combination of colors|mana of any (one )?colors?/i; const ADD_CLAUSE_PATTERN = /\badds?\b/i; export default function compute(pile, cardsById) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; const manaValueBuckets = Array.from({ length: MANA_VALUE_LABELS.length }, () => 0); const pipCounts = new Map(); const sourceCounts = new Map(); const typeCounts = new Map(); // The cards behind each bar and segment, so the deck page can highlight them. const manaValueRefs = new Map(); const pipRefs = new Map(); const sourceRefs = new Map(); const typeRefs = new Map(); let total = 0; let lands = 0; let nonlands = 0; let nonlandManaValue = 0; // Mana-check inputs: each land's producible colors (fetches resolved after // the pass, once the deck's basics are known) and each colored spell. const landEntries = []; const spellEntries = new Map(); Object.keys(deck).forEach((cardId) => { const quantity = deck[cardId]; total += quantity; const card = catalog[cardId]; if (!isRecord(card)) { return; } const types = cardTypes(card); if (types.indexOf("Land") === -1) { const value = Math.max(0, manaValue(card)); const bucket = Math.min(Math.floor(value), MANA_VALUE_LABELS.length - 1); manaValueBuckets[bucket] += quantity; addRef(manaValueRefs, bucket, cardId); nonlands += quantity; nonlandManaValue += value * quantity; const pips = strictColorPips(manaCost(card)); const name = textOf(card.name); if (Object.keys(pips).length > 0 && name && !spellEntries.has(name)) { spellEntries.set(name, { name, cost: manaCost(card), turn: Math.max(1, Math.round(value)), pips }); } } else { lands += quantity; landEntries.push({ quantity, card, produced: producedMana(card) }); } // Hybrid / Phyrexian pips ("G/W", "B/P") count toward each color they name. manaSymbols(manaCost(card)).forEach((symbol) => { symbol.split("/").forEach((part) => { const token = part.trim().toUpperCase(); if (COLORS.indexOf(token) !== -1) { pipCounts.set(token, (pipCounts.get(token) ?? 0) + quantity); addRef(pipRefs, token, cardId); } }); }); producedMana(card).forEach((mana) => { sourceCounts.set(mana, (sourceCounts.get(mana) ?? 0) + quantity); addRef(sourceRefs, mana, cardId); }); const primary = TYPE_PRIORITY.find((type) => types.indexOf(type) !== -1); if (primary) { const key = primary.toLowerCase(); typeCounts.set(key, (typeCounts.get(key) ?? 0) + quantity); addRef(typeRefs, key, cardId); } }); const typeOrder = TYPE_PRIORITY.map((type) => type.toLowerCase()); // Mean mana value of the nonland cards (lands would drag it toward 0), and // the expected lands in the opening hand, each to two decimals. const averageManaValue = nonlands > 0 ? roundTo(nonlandManaValue / nonlands, 2) : 0; const openingHandLands = total > 0 ? roundTo((OPENING_HAND_SIZE * lands) / total, 2) : 0; const manaCheck = computeManaCheck(total, lands, landEntries, Array.from(spellEntries.values())); return { widgets: [ { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total }, { kind: "stat", label: "Lands", labelKey: "mtg.lands", value: lands }, { kind: "stat", label: "Average mana value", labelKey: "mtg.averageManaValue", value: averageManaValue }, { kind: "histogram", label: "Mana value", labelKey: "mtg.manaValue", buckets: manaValueBuckets, labels: MANA_VALUE_LABELS, bucketCardRefs: bucketRefList(manaValueRefs, manaValueBuckets.length) }, { kind: "donut", label: "Color pips", labelKey: "mtg.colorPips", vocabulary: "mtg.color", segments: withCardRefs(orderedSegments(pipCounts, COLORS, COLOR_LABELS), pipRefs) }, { kind: "bars", label: "Mana sources", labelKey: "mtg.manaSources", vocabulary: "mtg.color", segments: withCardRefs(orderedSegments(sourceCounts, MANA_ORDER, COLOR_LABELS), sourceRefs) }, { kind: "donut", label: "Card types", labelKey: "cardTypes", vocabulary: "mtg.cardType", segments: withCardRefs(orderedSegments(typeCounts, typeOrder, TYPE_LABELS), typeRefs) }, { kind: "stat", label: "Lands in opening hand", labelKey: "mtg.openingHandLands", value: openingHandLands }, // P(at least one land in 7), plus the exact 0–5 land split. { kind: "hypergeometric", label: "Opening hand land odds", labelKey: "mtg.openingHandLandOdds", population: total, successCount: lands, draws: Math.min(OPENING_HAND_SIZE, total), exactCounts: OPENING_HAND_LAND_COUNTS }, ].concat(manaCheck), }; } // ---- Mana check (Frank Karsten's method) ------------------------------------ // A spell is "castable on curve" when, by the turn equal to its mana value, you // hold enough sources of each color it needs. Like Karsten, the odds are // conditioned on hitting your land drops (at least that many lands drawn), on // the play: 7 cards plus one draw per turn after the first. Sources are lands // only (the colors they tap for, plus the basic types a fetchland can find); // the odds are exact multivariate hypergeometric, so any deck size works. // Hybrid, Phyrexian and twobrid pips are left out (they have other payments). function computeManaCheck(total, lands, landEntries, spells) { if (total === 0 || lands === 0 || spells.length === 0) { return []; } const basicColors = new Set(); landEntries.forEach((entry) => { if (/\bBasic\b/.test(typeLineOf(entry.card))) { entry.produced.forEach((color) => basicColors.add(color)); } }); const sources = new Map(); landEntries.forEach((entry) => { const colors = new Set(entry.produced); fetchedColors(entry.card, basicColors).forEach((color) => colors.add(color)); colors.forEach((color) => { sources.set(color, (sources.get(color) ?? 0) + entry.quantity); }); }); const oddsFor = (spell, color, sourceCount) => castOdds(total, lands, sourceCount, spell.pips[color], spell.turn); const cardRows = spells.map((spell) => { let odds = 1; Object.keys(spell.pips).forEach((color) => { odds = Math.min(odds, oddsFor(spell, color, sources.get(color) ?? 0)); }); return { spell, odds }; }); cardRows.sort((left, right) => left.odds - right.odds || (left.spell.name < right.spell.name ? -1 : 1)); // Per color, the most demanding card: the one needing the most sources // (unreachable counts as most), ties broken by the lower on-curve odds. const colorRows = []; COLORS.forEach((color) => { let hardest = null; spells.forEach((spell) => { if (!spell.pips[color]) { return; } const needed = sourcesNeeded(total, lands, spell.pips[color], spell.turn); const demand = needed === null ? Infinity : needed; const odds = oddsFor(spell, color, sources.get(color) ?? 0); if (hardest === null || demand > hardest.demand || (demand === hardest.demand && odds < hardest.odds)) { hardest = { spell, needed, demand, odds }; } }); if (hardest === null) { return; } colorRows.push([ COLOR_LABELS[color], hardest.spell.name + " " + hardest.spell.cost, sources.get(color) ?? 0, hardest.needed === null ? "> " + lands : hardest.needed, formatOdds(hardest.odds), ]); }); return [ { kind: "table", label: "Colored sources", labelKey: "mtg.coloredSources", columns: ["Color", "Hardest card", "Sources", "Needed (90%)", "On curve"], columnKeys: ["mtg.manaCheck.color", "mtg.manaCheck.hardestCard", "mtg.manaCheck.sources", "mtg.manaCheck.needed", "mtg.manaCheck.onCurve"], rows: colorRows, }, { kind: "table", label: "Castable on curve", labelKey: "mtg.castableOnCurve", columns: ["Card", "Cost", "Turn", "Odds"], columnKeys: ["mtg.manaCheck.card", "mtg.manaCheck.cost", "mtg.manaCheck.turn", "mtg.manaCheck.odds"], rows: cardRows.map((row) => [row.spell.name, row.spell.cost, row.spell.turn, formatOdds(row.odds)]), }, ]; } // The single-color pips a cost demands: "{1}{R}{R}" -> { R: 2 }. function strictColorPips(cost) { const pips = {}; manaSymbols(cost).forEach((symbol) => { const token = symbol.trim().toUpperCase(); if (COLORS.indexOf(token) !== -1) { pips[token] = (pips[token] ?? 0) + 1; } }); return pips; } // P(at least `needed` of `sources` colored lands among the cards seen by // `turn`, given at least `turn` lands among them), on the play. Colored // sources are a subset of the lands. function castOdds(total, lands, sources, needed, turn) { const draws = Math.min(total, OPENING_HAND_SIZE + turn - 1); const colored = Math.min(sources, lands); const otherLands = lands - colored; const spells = total - lands; let enoughLands = 0; let castable = 0; for (let s = 0; s <= Math.min(colored, draws); s += 1) { for (let o = 0; o <= Math.min(otherLands, draws - s); o += 1) { const rest = draws - s - o; if (rest > spells || s + o < Math.min(turn, lands)) { continue; } const weight = choose(colored, s) * choose(otherLands, o) * choose(spells, rest); enoughLands += weight; if (s >= needed) { castable += weight; } } } return enoughLands > 0 ? castable / enoughLands : 0; } // The fewest colored sources (holding the land count fixed) that reach the // target, or null when even an all-color land base falls short. function sourcesNeeded(total, lands, needed, turn) { for (let count = needed; count <= lands; count += 1) { if (castOdds(total, lands, count, needed, turn) >= MANA_CHECK_TARGET) { return count; } } return null; } function choose(n, k) { if (k < 0 || k > n) { return 0; } let result = 1; for (let i = 1; i <= Math.min(k, n - k); i += 1) { result = (result * (n - Math.min(k, n - k) + i)) / i; } return result; } function formatOdds(value) { return (Math.round(value * 1000) / 10).toFixed(1) + "%"; } function typeLineOf(card) { const game = cardGame(card); return [textOf(game.typeLine)].concat(cardFaces(game).map((face) => textOf(face.typeLine))).join(" // "); } // Colors a fetchland can find: the basic land types its search names ("a // Plains or Island card"), or every basic color in the deck for a "basic land // card" search (Fabled Passage, Evolving Wilds). function fetchedColors(card, basicColors) { const colors = new Set(); trimmedTexts(cardGame(card), "oracleText").forEach((text) => { const match = /search your library for (an? |up to \w+ )?([^.]*?)cards?\b/i.exec(text); if (!match) { return; } const target = match[2]; let named = false; LAND_SUBTYPE_COLORS.forEach(([pattern, color]) => { if (pattern.test(target)) { colors.add(color); named = true; } }); if (!named && /\bbasic land\b/i.test(target)) { basicColors.forEach((color) => colors.add(color)); } }); return Array.from(colors); } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } function cardFaces(game) { return Array.isArray(game.faces) ? game.faces.filter(isRecord) : []; } function textOf(value) { return typeof value === "string" ? value : ""; } // The mana-symbol tokens in a cost string: "{2}{W/U}" -> ["2", "W/U"]. function manaSymbols(text) { return (textOf(text).match(/\{[^}]+\}/g) || []).map((token) => token.slice(1, -1)); } function faceManaCost(game) { const face = cardFaces(game).find((entry) => textOf(entry.manaCost).length > 0); return face ? face.manaCost : ""; } // The top-level cost, else the first face that carries one (transform/MDFC). function manaCost(card) { const game = cardGame(card); return game.manaCost !== undefined && game.manaCost !== null ? textOf(game.manaCost) : faceManaCost(game); } // Mana value: the card's cmc, else computed from the top-level or front-face // cost (generic pips add their number, X/Y/Z count 0, twobrid {2/W} counts 2). function manaValue(card) { const game = cardGame(card); if (typeof game.cmc === "number" && Number.isFinite(game.cmc)) { return game.cmc; } const cost = textOf(game.manaCost) || faceManaCost(game); let total = 0; manaSymbols(cost).forEach((symbol) => { const head = symbol.split("/")[0] ?? ""; const generic = Number(head); if (Number.isFinite(generic)) { total += generic; } else if (!/^[XYZ]$/i.test(head)) { total += 1; } }); return total; } // The major card types on the type line (before each face's "—" subtypes). function cardTypes(card) { const game = cardGame(card); const typeLine = game.typeLine !== undefined && game.typeLine !== null ? textOf(game.typeLine) : cardFaces(game).map((face) => textOf(face.typeLine)).join(" // "); if (!typeLine) { return []; } const words = new Set( typeLine .split("//") .map((facePart) => facePart.split("—")[0] ?? "") .join(" ") .split(/\s+/) .filter(Boolean), ); return TYPE_PRIORITY.filter((type) => words.has(type)); } function trimmedTexts(game, field) { return [textOf(game[field])] .concat(cardFaces(game).map((face) => textOf(face[field]))) .map((text) => text.trim()) .filter(Boolean); } // The mana a card can produce: basic land subtypes, unioned with explicit // "Add …" clauses in its rules text (reminder text included). function producedMana(card) { const game = cardGame(card); const produced = new Set(); trimmedTexts(game, "typeLine").forEach((typeLine) => { const dashIndex = typeLine.indexOf("—"); if (dashIndex === -1) { return; } const subtypes = typeLine.slice(dashIndex + 1); LAND_SUBTYPE_COLORS.forEach(([pattern, color]) => { if (pattern.test(subtypes)) { produced.add(color); } }); }); trimmedTexts(game, "oracleText").forEach((text) => { text.split(/[.\n]/).forEach((clause) => { if (!ADD_CLAUSE_PATTERN.test(clause)) { return; } if (ANY_COLOR_PATTERN.test(clause)) { COLORS.forEach((color) => produced.add(color)); return; } manaSymbols(clause).forEach((symbol) => { symbol.split("/").forEach((part) => { const token = part.trim().toUpperCase(); if (MANA_ORDER.indexOf(token) !== -1) { produced.add(token); } }); }); }); }); return MANA_ORDER.filter((mana) => produced.has(mana)); } ``` ```js [Palworld TCG] const COST_CURVE_LABELS = ["1", "2", "3", "4", "5", "6", "7", "8+"]; // The deck rule's cap on cards with the lucky icon (rules 6.1.1). const LUCKY_LIMIT = 8; // Display orders; unexpected keys trail by count. const TYPE_ORDER = ["pal", "structure", "gear", "event"]; const COLOR_ORDER = ["red", "blue", "green", "purple", "colorless"]; const ELEMENT_ORDER = ["neutral", "fire", "water", "grass", "electric", "ground", "ice", "dark", "dragon"]; // The catalog's work kinds (PalworldWorkSuitability), in its order. const WORK_ORDER = ["harvesting", "crafting", "collecting", "transporting", "kindling", "cooling", "farming", "electricity"]; const WORK_LABELS = { harvesting: "Harvesting", crafting: "Crafting", collecting: "Collecting", transporting: "Transporting", kindling: "Kindling", cooling: "Cooling", farming: "Farming", electricity: "Electricity", }; // Marks a work kind a Structure in the deck needs (`kindling:needed`). const NEEDED_SUFFIX = ":needed"; // Matches the catalog ladder (globals.rarities order). const RARITY_ORDER = ["c", "u", "r", "rr", "td", "tdr", "sr", "tsr", "osr", "sp", "tsp", "ssp", "sss", "pr"]; // English fallbacks for the printed rarity codes (the web domain localizes). const RARITY_LABELS = { c: "C", u: "U", r: "R", rr: "RR", sr: "SR", osr: "OSR", sp: "SP", ssp: "SSP", sss: "SSS", td: "TD", tdr: "TDR", tsr: "TSR", tsp: "TSP", pr: "PR", }; export default function compute(pile, cardsById) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; const costBuckets = Array.from({ length: COST_CURVE_LABELS.length }, () => 0); const typeCounts = new Map(); const colorCounts = new Map(); const elementCounts = new Map(); const rarityCounts = new Map(); const strikeRows = new Map(); const costRefs = new Map(); const typeRefs = new Map(); const colorRefs = new Map(); const elementRefs = new Map(); const rarityRefs = new Map(); const luckyRefs = new Map(); const workPals = new Map(); const workRefs = new Map(); const workStructures = new Map(); const mainDeck = {}; let total = 0; let luckyCount = 0; let palCount = 0; let powerTotal = 0; let powerCount = 0; let strikeTotal = 0; let strikeCount = 0; Object.keys(deck).forEach((cardId) => { const card = catalog[cardId]; if (!isRecord(card)) { return; } const quantity = deck[cardId]; const game = cardGame(card); const type = typeof game.cardType === "string" && game.cardType.length > 0 ? game.cardType : "unknown"; // Souls are the resource deck, never part of the main deck. if (type === "soul") { return; } mainDeck[cardId] = quantity; total += quantity; typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity); addRef(typeRefs, type, cardId); // No card prints a cost below 1 today; one that did would fold into the // "1" bucket rather than drop off the curve. if (Number.isFinite(game.cost)) { const costIndex = Math.min(Math.max(Math.floor(game.cost), 1), COST_CURVE_LABELS.length) - 1; costBuckets[costIndex] += quantity; addRef(costRefs, costIndex, cardId); } if (typeof game.color === "string" && game.color.length > 0) { colorCounts.set(game.color, (colorCounts.get(game.color) ?? 0) + quantity); addRef(colorRefs, game.color, cardId); } if (game.isLucky === true) { luckyCount += quantity; addRef(luckyRefs, "lucky", cardId); } const rarity = printingRarity(card, cardId); if (rarity !== null) { rarityCounts.set(rarity, (rarityCounts.get(rarity) ?? 0) + quantity); addRef(rarityRefs, rarity, cardId); } const works = (Array.isArray(game.workSuitability) ? game.workSuitability : []).filter( (work, index, list) => WORK_ORDER.indexOf(work) !== -1 && list.indexOf(work) === index, ); if (type === "structure") { works.forEach((work) => { workStructures.set(work, (workStructures.get(work) ?? 0) + quantity); }); } if (type !== "pal") { return; } works.forEach((work) => { workPals.set(work, (workPals.get(work) ?? 0) + quantity); addRef(workRefs, work, cardId); }); palCount += quantity; (Array.isArray(game.elements) ? game.elements : []).forEach((element) => { if (ELEMENT_ORDER.indexOf(element) !== -1) { elementCounts.set(element, (elementCounts.get(element) ?? 0) + quantity); addRef(elementRefs, element, cardId); } }); const hasPower = Number.isFinite(game.power); if (hasPower) { powerTotal += game.power * quantity; powerCount += quantity; } if (Number.isFinite(game.strike)) { const strike = Math.max(0, Math.floor(game.strike)); strikeTotal += strike * quantity; strikeCount += quantity; const row = strikeRows.get(strike) ?? { pals: 0, powerTotal: 0, powerCount: 0 }; row.pals += quantity; if (hasPower) { row.powerTotal += game.power * quantity; row.powerCount += quantity; } strikeRows.set(strike, row); } }); // One row per printed strike value, lowest first: [strike, Pals, average power]. const strikeTableRows = Array.from(strikeRows.keys()) .sort((left, right) => left - right) .map((strike) => { const row = strikeRows.get(strike); return [strike, row.pals, row.powerCount > 0 ? roundTo(row.powerTotal / row.powerCount, 1) : "-"]; }); const luckySegments = [ { key: "lucky", label: "Lucky", value: luckyCount, color: "", cardRefs: luckyRefs.get("lucky") ?? [] }, { key: "open", label: "Open", value: Math.max(0, LUCKY_LIMIT - luckyCount), color: "" }, ]; // Pals per work kind, in the catalog's order; a kind a Structure needs is // keyed `:needed` so the web vocabulary marks it. const workSegments = WORK_ORDER.filter((work) => (workPals.get(work) ?? 0) > 0).map((work) => { const needed = workStructures.has(work); return { key: needed ? work + NEEDED_SUFFIX : work, label: needed ? WORK_LABELS[work] + " ★" : WORK_LABELS[work], value: workPals.get(work), color: "", cardRefs: workRefs.get(work) ?? [], }; }); // One row per work kind the deck's Structures need: [work, Structures, Pals]. // The work cell is the raw kind, which the column's vocabulary translates. const structureWorkRows = WORK_ORDER.filter((work) => workStructures.has(work)).map((work) => [ work, workStructures.get(work), workPals.get(work) ?? 0, ]); const rarities = withCardRefs(orderedSegments(rarityCounts, RARITY_ORDER, RARITY_LABELS), rarityRefs); const widgets = [ { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total }, { kind: "histogram", label: "Cost curve", labelKey: "palworld.costCurve", buckets: costBuckets, labels: COST_CURVE_LABELS, bucketCardRefs: bucketRefList(costRefs, costBuckets.length) }, { kind: "donut", label: "Card types", labelKey: "palworld.cardTypes", vocabulary: "palworld.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) }, { kind: "donut", label: "Colors", labelKey: "palworld.colors", vocabulary: "palworld.color", segments: withCardRefs(orderedSegments(colorCounts, COLOR_ORDER), colorRefs) }, { kind: "gauge", label: "Lucky cards (max 8)", labelKey: "palworld.luckyCards", segments: luckySegments }, { kind: "bars", label: "Pal elements", labelKey: "palworld.elements", vocabulary: "palworld.element", segments: withCardRefs(orderedSegments(elementCounts, ELEMENT_ORDER), elementRefs) }, { kind: "stat", label: "Average Pal power", labelKey: "palworld.averagePower", value: powerCount > 0 ? roundTo(powerTotal / powerCount, 1) : 0 }, { kind: "stat", label: "Average Pal strike", labelKey: "palworld.averageStrike", value: strikeCount > 0 ? roundTo(strikeTotal / strikeCount, 1) : 0 }, { kind: "table", label: "Pals by strike", labelKey: "palworld.strikeTable", columns: ["Strike", "Pals", "Average power"], columnKeys: ["palworld.strikeColumns.strike", "palworld.strikeColumns.pals", "palworld.strikeColumns.averagePower"], rows: strikeTableRows, }, ...(workSegments.length > 0 ? [{ kind: "bars", label: "Work suitability (★ needed by a Structure)", labelKey: "palworld.workSuitability", vocabulary: "palworld.workSuitability", segments: workSegments }] : []), ...(structureWorkRows.length > 0 ? [{ kind: "table", label: "Structure work", labelKey: "palworld.structureWork", columns: ["Work", "Structures", "Pals"], columnKeys: ["palworld.structureWorkColumns.work", "palworld.structureWorkColumns.structures", "palworld.structureWorkColumns.pals"], columnVocabularies: ["palworld.workSuitability", "", ""], rows: structureWorkRows, }] : []), ...(rarities.length > 0 ? [{ kind: "donut", label: "Rarity", labelKey: "palworld.rarity", vocabulary: "palworld.rarity", segments: rarities }] : []), ]; { const pile = mainDeck; const chanceHand = 5; // Distinct-card table: one row per distinct card (keyed by name) in the // match set, with the configured metric columns. All combinatorics are // inline — the sandbox cannot import a helper. const containsValue = (haystack, needle) => { if (Array.isArray(haystack)) { return haystack.indexOf(needle) !== -1; } if (haystack === undefined || haystack === null) { return false; } return String(haystack).indexOf(String(needle)) !== -1; }; const lineCopies = new Map(); const linePrintings = new Map(); const lineCards = new Map(); const lineOrder = []; let deckSize = 0; let matchTotal = 0; Object.keys(pile).forEach((ref) => { const quantity = Number(pile[ref]) || 0; if (quantity <= 0) { return; } deckSize = deckSize + quantity; const card = cardsById[ref]; const row = { quantity: quantity, card: card, ref: ref }; if (!(true)) { return; } matchTotal = matchTotal + quantity; const key = String(row.card !== null && row.card !== undefined && typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref); if (!lineCopies.has(key)) { lineCopies.set(key, 0); linePrintings.set(key, 0); lineCards.set(key, row); lineOrder.push(key); } lineCopies.set(key, lineCopies.get(key) + quantity); linePrintings.set(key, linePrintings.get(key) + 1); }); // P(the opening hand contains none of a pool of `excluded` cards), drawing // `drawCount` without replacement — a running product of draw ratios so a // 60-card deck never overflows a factorial. 0 when the pool leaves too few // safe cards to fill the hand. const probNoneOf = (excluded, drawCount) => { if (deckSize - excluded < drawCount) { return 0; } let probability = 1; for (let i = 0; i < drawCount; i = i + 1) { probability = (probability * (deckSize - excluded - i)) / (deckSize - i); } return probability; }; // Clamp to [0,1] and render as a 2-decimal percentage string. const formatPercent = (value) => { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; }; const entries = lineOrder.map((key) => { const copies = lineCopies.get(key); return { key: key, copies: copies, printings: linePrintings.get(key), row: lineCards.get(key), otherMatches: matchTotal - copies, }; }); // Highest copy count first (== highest possible-starter odds for fixed // draws); ties broken by key. entries.sort((left, right) => { if (right.copies !== left.copies) { return right.copies - left.copies; } return left.key < right.key ? -1 : left.key > right.key ? 1 : 0; }); widgets.push({ kind: "table", label: "Chance to see", columns: ["Card", "Hand", "+1 draw", "+3 draws"], rows: entries.map((entry) => { const row = entry.row; return [entry.key, (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 1, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 3, deckSize))))]; }), }); const chanceTable = widgets[widgets.length - 1]; chanceTable.labelKey = "chanceToSee"; chanceTable.columnKeys = [ "chanceToSeeColumns.card", "chanceToSeeColumns.openingHand", "chanceToSeeColumns.afterOneDraw", "chanceToSeeColumns.afterThreeDraws", ]; } return { widgets }; } // The rarity of the printing the pile names (its `metadata.rarity`), else the // default printing's `game.rarity` (an identity ref, or a printing without // one); lower-cased to the catalog's rarity ids. Null when neither is known. function printingRarity(card, ref) { const printings = Array.isArray(card.printings) ? card.printings : []; const printing = printings.find((entry) => isRecord(entry) && entry.id === ref); const metadata = printing && isRecord(printing.metadata) ? printing.metadata : {}; const game = cardGame(card); const rarity = typeof metadata.rarity === "string" && metadata.rarity.length > 0 ? metadata.rarity : game.rarity; return typeof rarity === "string" && rarity.length > 0 ? rarity.toLowerCase() : null; } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } ``` ```js [Pokémon TCG] // Canonical Pokémon energy types, matched against spelled-out energy names. const POKEMON_ENERGY_TYPES = ["Grass", "Fire", "Water", "Lightning", "Psychic", "Fighting", "Darkness", "Metal", "Fairy", "Dragon", "Colorless"]; // PTCGO/Live single-letter energy glyph codes -> canonical type. Basic and typed // Special Energy print a {X} token ("Basic {L} Energy") rather than the spelled // type, so the element is read off the glyph: {R} is Fire, {N} is Dragon. const POKEMON_ENERGY_GLYPH_TYPES = { G: "Grass", R: "Fire", W: "Water", L: "Lightning", P: "Psychic", F: "Fighting", D: "Darkness", M: "Metal", Y: "Fairy", N: "Dragon", C: "Colorless" }; const RETREAT_LABELS = ["0", "1", "2", "3", "4+"]; export default function compute(pile, cardsById) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; let pokemon = 0; let trainer = 0; let energy = 0; let total = 0; let basicPokemon = 0; const energyTypeCounts = new Map(); const retreatBuckets = Array.from({ length: 5 }, () => 0); const regulationCounts = new Map(); // The cards behind each bar and segment, so the deck page can highlight them. const supertypeRefs = new Map(); const energyTypeRefs = new Map(); const retreatRefs = new Map(); const regulationRefs = new Map(); Object.keys(deck).forEach((cardId) => { const quantity = deck[cardId]; const card = catalog[cardId]; const game = cardGame(card); const supertype = typeof game.supertype === "string" ? game.supertype : ""; const subtypes = Array.isArray(game.subtypes) ? game.subtypes : []; total += quantity; // The catalog ships the accented "Pokémon" token; tolerate the ASCII form. if (supertype === "Pokémon" || supertype === "Pokemon") { pokemon += quantity; addRef(supertypeRefs, "pokemon", cardId); if (subtypes.indexOf("Basic") !== -1) { basicPokemon += quantity; } const retreat = Number.isFinite(game.convertedRetreatCost) ? Math.max(0, Math.floor(game.convertedRetreatCost)) : 0; const retreatIndex = Math.min(retreat, 4); retreatBuckets[retreatIndex] += quantity; addRef(retreatRefs, retreatIndex, cardId); } else if (supertype === "Trainer") { trainer += quantity; addRef(supertypeRefs, "trainer", cardId); } else if (supertype === "Energy") { energy += quantity; addRef(supertypeRefs, "energy", cardId); // Energy-type donut counts ONLY Energy-supertype cards, so Pokémon (which // carry their own game.types) never leak into the energy breakdown. A basic // Energy derives its element from its identity id (or name); a special // Energy that declares an element uses it, and one with no element falls // into a "Special" bucket so the donut still sums to the deck's energy count. const energyTypes = pokemonCardEnergyTypes(card); const elements = Array.isArray(energyTypes) ? energyTypes.filter((type) => typeof type === "string" && type.length > 0) : []; if (elements.length > 0) { elements.forEach((type) => { energyTypeCounts.set(type, (energyTypeCounts.get(type) ?? 0) + quantity); addRef(energyTypeRefs, type, cardId); }); } else { energyTypeCounts.set("Special", (energyTypeCounts.get("Special") ?? 0) + quantity); addRef(energyTypeRefs, "Special", cardId); } } // Regulation mark (A–J), when the card carries one. Basic energy is // format-evergreen (not rotation-relevant), so exclude it from the gauge; // Pokémon, Trainers, and special (non-basic) energy still count. const isBasicEnergy = supertype === "Energy" && subtypes.indexOf("Basic") !== -1; const mark = typeof game.regulationMark === "string" ? game.regulationMark : ""; if (mark.length > 0 && !isBasicEnergy) { regulationCounts.set(mark, (regulationCounts.get(mark) ?? 0) + quantity); addRef(regulationRefs, mark, cardId); } }); const breakdown = [ { key: "pokemon", label: "Pokémon", value: pokemon, color: "" }, { key: "trainer", label: "Trainer", value: trainer, color: "" }, { key: "energy", label: "Energy", value: energy, color: "" }, ] .filter((segment) => segment.value > 0) .map((segment) => ({ ...segment, cardRefs: supertypeRefs.get(segment.key) ?? [] })); // Mulligan: P(no Basic Pokémon in the opening 7). Running product of draw // ratios (no factorial). 0 when a basic can't be avoided (too few non-basics). const handSize = 7; const drawCount = Math.min(handSize, total); let mulligan = 0; if (total > 0 && total - basicPokemon >= drawCount) { let probability = 1; for (let i = 0; i < drawCount; i = i + 1) { probability = (probability * (total - basicPokemon - i)) / (total - i); } mulligan = probability; } const widgets = []; widgets.push({ kind: "donut", label: "Deck breakdown", labelKey: "pokemon.deckBreakdown", vocabulary: "pokemon.supertype", segments: breakdown }); widgets.push({ kind: "stat", label: "Total cards", labelKey: "pokemon.totalCards", value: total }); widgets.push({ kind: "donut", label: "Energy types", labelKey: "pokemon.energyTypes", vocabulary: "pokemon.energyType", segments: withCardRefs(energyTypeSegments(energyTypeCounts), energyTypeRefs) }); widgets.push({ kind: "stat", label: "Mulligan chance", labelKey: "pokemon.mulliganChance", value: formatPercentValue(mulligan) }); { // Distinct-card table: one row per distinct card (keyed by name) in the // match set, with the configured metric columns. All combinatorics are // inline — the sandbox cannot import a helper. const containsValue = (haystack, needle) => { if (Array.isArray(haystack)) { return haystack.indexOf(needle) !== -1; } if (haystack === undefined || haystack === null) { return false; } return String(haystack).indexOf(String(needle)) !== -1; }; const lineCopies = new Map(); const linePrintings = new Map(); const lineCards = new Map(); const lineOrder = []; let deckSize = 0; let matchTotal = 0; Object.keys(pile).forEach((ref) => { const quantity = Number(pile[ref]) || 0; if (quantity <= 0) { return; } deckSize = deckSize + quantity; const card = cardsById[ref]; const row = { quantity: quantity, card: card, ref: ref }; if (!(["Pokémon", "Pokemon"].indexOf(row.card?.game?.supertype) !== -1 && containsValue(row.card?.game?.subtypes, "Basic"))) { return; } matchTotal = matchTotal + quantity; const key = String(row.card !== null && row.card !== undefined && typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref); if (!lineCopies.has(key)) { lineCopies.set(key, 0); linePrintings.set(key, 0); lineCards.set(key, row); lineOrder.push(key); } lineCopies.set(key, lineCopies.get(key) + quantity); linePrintings.set(key, linePrintings.get(key) + 1); }); // P(the opening hand contains none of a pool of `excluded` cards), drawing // `drawCount` without replacement — a running product of draw ratios so a // 60-card deck never overflows a factorial. 0 when the pool leaves too few // safe cards to fill the hand. const probNoneOf = (excluded, drawCount) => { if (deckSize - excluded < drawCount) { return 0; } let probability = 1; for (let i = 0; i < drawCount; i = i + 1) { probability = (probability * (deckSize - excluded - i)) / (deckSize - i); } return probability; }; // Clamp to [0,1] and render as a 2-decimal percentage string. const formatPercent = (value) => { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; }; const entries = lineOrder.map((key) => { const copies = lineCopies.get(key); return { key: key, copies: copies, printings: linePrintings.get(key), row: lineCards.get(key), otherMatches: matchTotal - copies, }; }); // Highest copy count first (== highest possible-starter odds for fixed // draws); ties broken by key. entries.sort((left, right) => { if (right.copies !== left.copies) { return right.copies - left.copies; } return left.key < right.key ? -1 : left.key > right.key ? 1 : 0; }); widgets.push({ kind: "table", label: "Opening Hand Starters", columns: ["Pokémon", "Possible Starter", "Forced Starter"], rows: entries.map((entry) => { const row = entry.row; return [entry.key, formatPercent(1 - probNoneOf(entry.copies, Math.min(7, deckSize))), formatPercent(probNoneOf(entry.otherMatches, Math.min(7, deckSize)) - probNoneOf(entry.otherMatches + entry.copies, Math.min(7, deckSize)))]; }), }); const starterTable = widgets[widgets.length - 1]; starterTable.labelKey = "pokemon.openingHandStarters"; starterTable.columnKeys = [ "pokemon.starterTable.pokemon", "pokemon.starterTable.possibleStarter", "pokemon.starterTable.forcedStarter", ]; } widgets.push({ kind: "histogram", label: "Retreat cost", labelKey: "pokemon.retreatCost", buckets: retreatBuckets, labels: RETREAT_LABELS, bucketCardRefs: bucketRefList(retreatRefs, retreatBuckets.length) }); widgets.push({ kind: "gauge", label: "Regulation marks", labelKey: "pokemon.regulationMarks", segments: withCardRefs(regulationSegments(regulationCounts), regulationRefs) }); return { widgets: widgets }; } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } // Energy-type donut segments (canonical English type keys, or "Special"), // highest count first. function energyTypeSegments(counts) { const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key: key, value: value }); } }); return entries .sort((left, right) => right.value - left.value) .map((entry) => ({ key: entry.key, label: entry.key, value: entry.value, color: "" })); } // Regulation-mark gauge segments, in alphabetical (A–J) mark order. Colors are // left empty; the renderer fills them from its fallback palette. function regulationSegments(counts) { const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key: key, value: value }); } }); return entries .sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0)) .map((entry) => ({ key: entry.key, label: entry.key, value: entry.value, color: "" })); } // The energy element an Energy card provides, read from its identity id. The // catalog slugs every identity from its canonical English name in every locale // ("basic-d-energy--935d278dfee1", "bubbly-w-energy--6fce5d2069c1"), while // card.name is localized ("基本悪エネルギー" under /ja/), so the id is the // locale-independent source. function pokemonEnergyTypesFromId(id) { const slug = String(id === undefined || id === null ? "" : id).split("--")[0].toLowerCase(); const glyph = slug.match(/(?:^|-)([a-z])-energy$/); if (glyph) { const type = POKEMON_ENERGY_GLYPH_TYPES[glyph[1].toUpperCase()]; return type ? [type] : []; } const base = slug.replace(/^basic-/, "").replace(/-energy$/, ""); return POKEMON_ENERGY_TYPES.filter((type) => type.toLowerCase() === base); } // The energy element(s) an Energy card provides, read from its NAME ("Fire // Energy" -> Fire; "Basic {L} Energy" -> Lightning) — the fallback for ids that // carry no element (printing-keyed or JP-only identities, multi-glyph names). // {X} glyph tokens win; failing that, a spelled-out Basic Energy name is // matched against the canonical types. function pokemonEnergyTypesFromName(name) { const text = String(name === undefined || name === null ? "" : name); const glyphTypes = []; const glyphTokens = text.match(/\{[A-Za-z]\}/g) || []; glyphTokens.forEach((token) => { const type = POKEMON_ENERGY_GLYPH_TYPES[token.slice(1, 2).toUpperCase()]; if (type && glyphTypes.indexOf(type) === -1) { glyphTypes.push(type); } }); if (glyphTypes.length > 0) { return glyphTypes; } const base = text.replace(/^basic\s+/i, "").replace(/\s+energy$/i, "").trim().toLowerCase(); return POKEMON_ENERGY_TYPES.filter((type) => type.toLowerCase() === base); } // The energy type(s) to group a card by. A Pokémon carries a declared game.types // array, used as-is. An Energy card carries none, so its element is derived from // its identity id, then its name. Any other card keeps its raw game.types // (undefined for Trainers). function pokemonCardEnergyTypes(card) { const game = cardGame(card); const declared = game.types; if (Array.isArray(declared) && declared.length > 0) { return declared; } if (game.supertype === "Energy") { const fromId = pokemonEnergyTypesFromId(isRecord(card) ? card.id : ""); return fromId.length > 0 ? fromId : pokemonEnergyTypesFromName(isRecord(card) ? card.name : ""); } return declared; } ``` ```js [Riftbound] const ENERGY_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+"]; // Might shares the 0–9 + overflow bucket shape of the energy curve. const MIGHT_LABELS = ENERGY_CURVE_LABELS; // Card types that sit in a separate zone, not the main deck; excluded from the // energy curve, domain pips, and card-type breakdown. Runes are handled first // (their own domain split) before this main-deck exclusion. const EXCLUDED_ZONE_TYPES = ["legend", "rune", "battlefield"]; // Main-deck card types that are Units (Champions are Units) — the population of // the Might distribution. const UNIT_TYPES = ["unit", "champion"]; // Known domains in display order; unknown domain refs are not charted. const DOMAIN_ORDER = ["body", "calm", "chaos", "fury", "mind", "order", "colorless", "neutral"]; // Card-type display order; unexpected types trail by count. const TYPE_ORDER = ["champion", "unit", "spell", "gear"]; export default function compute(pile, cardsById) { const deck = normalizePile(pile); const catalog = isRecord(cardsById) ? cardsById : {}; const energyBuckets = Array.from({ length: 11 }, () => 0); const mightBuckets = Array.from({ length: 11 }, () => 0); const domainCounts = new Map(); const runeDomainCounts = new Map(); const typeCounts = new Map(); // The cards behind each bar and segment, so the deck page can highlight them. const energyRefs = new Map(); const mightRefs = new Map(); const domainRefs = new Map(); const runeDomainRefs = new Map(); const typeRefs = new Map(); let energyTotal = 0; let mainCount = 0; Object.keys(deck).forEach((cardId) => { if (!isRecord(catalog[cardId])) { return; } const quantity = deck[cardId]; const game = cardGame(catalog[cardId]); const type = typeof game.type === "string" && game.type.length > 0 ? game.type : "unknown"; // The Rune deck has its own domain split (the mana base — 6/6 vs 8/4), read // off the rune zone alone and kept out of the main-deck counts. if (type === "rune") { addDomains(runeDomainCounts, runeDomainRefs, game.domains, quantity, cardId); return; } // Legend / battlefield cards are separate zones, not the main deck. if (EXCLUDED_ZONE_TYPES.indexOf(type) !== -1) { return; } // Riftbound uses energy as its cost. const energy = Number.isFinite(game.energy) ? Math.max(0, Math.floor(game.energy)) : 0; const energyIndex = Math.min(energy, 10); energyBuckets[energyIndex] += quantity; addRef(energyRefs, energyIndex, cardId); energyTotal += energy * quantity; mainCount += quantity; typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity); addRef(typeRefs, type, cardId); // Might distribution over Units (Champions are Units). Units with no numeric // might are skipped so missing data never piles into the 0 bucket. if (UNIT_TYPES.indexOf(type) !== -1 && Number.isFinite(game.might)) { const might = Math.max(0, Math.floor(game.might)); const mightIndex = Math.min(might, 10); mightBuckets[mightIndex] += quantity; addRef(mightRefs, mightIndex, cardId); } addDomains(domainCounts, domainRefs, game.domains, quantity, cardId); }); // Mean energy over the main deck (zone-excluded), to one decimal. const averageEnergy = mainCount > 0 ? Math.round((energyTotal / mainCount) * 10) / 10 : 0; // The balance of the three main card types. A ratio widget holds only two // values, so the three-way split renders as a small donut. const typeBalance = ["unit", "spell", "gear"].map((key) => ({ key, label: titleCase(key), value: typeCounts.get(key) ?? 0, color: "", cardRefs: typeRefs.get(key) ?? [], })); const runeDomains = withCardRefs(orderedSegments(runeDomainCounts, DOMAIN_ORDER), runeDomainRefs); const hasMight = mightBuckets.some((count) => count > 0); // Like the panel, the rune split and Might chart only appear when they have data. return { widgets: [ { kind: "bars", label: "Domains", labelKey: "riftbound.domains", vocabulary: "riftbound.domain", segments: withCardRefs(orderedSegments(domainCounts, DOMAIN_ORDER), domainRefs) }, ...(runeDomains.length > 0 ? [{ kind: "bars", label: "Rune domains", labelKey: "riftbound.runeDomains", vocabulary: "riftbound.domain", segments: runeDomains }] : []), { kind: "histogram", label: "Energy curve", labelKey: "riftbound.energyCurve", buckets: energyBuckets, labels: ENERGY_CURVE_LABELS, bucketCardRefs: bucketRefList(energyRefs, energyBuckets.length) }, ...(hasMight ? [{ kind: "histogram", label: "Might", labelKey: "riftbound.might", buckets: mightBuckets, labels: MIGHT_LABELS, bucketCardRefs: bucketRefList(mightRefs, mightBuckets.length) }] : []), { kind: "donut", label: "Card types", labelKey: "riftbound.cardTypes", vocabulary: "riftbound.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) }, { kind: "stat", label: "Average energy", labelKey: "riftbound.averageEnergy", value: averageEnergy }, { kind: "donut", label: "Unit / Spell / Gear", labelKey: "riftbound.typeBalance", vocabulary: "riftbound.cardType", segments: typeBalance }, ], }; } function normalizePile(pile) { if (!isRecord(pile)) { return {}; } return Object.entries(pile).reduce((result, [cardId, quantity]) => { const normalizedQuantity = normalizeQuantity(quantity); if (normalizedQuantity > 0) { result[cardId] = normalizedQuantity; } return result; }, {}); } function normalizeQuantity(value) { return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0; } function cardGame(card) { return isRecord(card) && isRecord(card.game) ? card.game : {}; } function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function roundTo(value, digits) { const factor = Math.pow(10, digits); return Math.round(value * factor) / factor; } function titleCase(value) { return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value; } // Clamp to [0,1] and render as a 2-decimal percentage string. function formatPercentValue(value) { const clamped = value < 0 ? 0 : value > 1 ? 1 : value; return (Math.round(clamped * 10000) / 100).toFixed(2) + "%"; } // Segments in a fixed display order, then any unlisted key by count (highest // first). Labels are English fallbacks (labels[key] when a labels map is // given, else the title-cased key): the widget's vocabulary lets the web // domain supply the localized label and the palette color. function orderedSegments(counts, order, labels) { const rank = (key) => { const index = order.indexOf(key); return index === -1 ? order.length : index; }; const entries = []; counts.forEach((value, key) => { if (value > 0) { entries.push({ key, value }); } }); return entries .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value) .map((entry) => ({ key: entry.key, label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key), value: entry.value, color: "", })); } // Remember a card's pile ref under a segment key or a bar index (each card // once), so the deck page can highlight the cards a chart segment counts. function addRef(refsByKey, key, ref) { const refs = refsByKey.get(key); if (refs === undefined) { refsByKey.set(key, [ref]); } else if (refs.indexOf(ref) === -1) { refs.push(ref); } } // Each segment with its card refs (collected with addRef by segment key). function withCardRefs(segments, refsByKey) { return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] })); } // A histogram's card refs per bar (collected with addRef by bar index), // parallel to its buckets. function bucketRefList(refsByIndex, length) { return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []); } function addDomains(counts, refsByDomain, domains, quantity, ref) { (Array.isArray(domains) ? domains : []).forEach((domain) => { if (DOMAIN_ORDER.indexOf(domain) !== -1) { counts.set(domain, (counts.get(domain) ?? 0) + quantity); addRef(refsByDomain, domain, ref); } }); } ``` ::: --- url: https://docs.turny.gg/reference/scripting/playtest description: "Reference for playtest rules scripts: the arguments, the table definition they return, every step, predicate and enum, the shortcut grammar, limits and validation issue codes." --- # 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](https://docs.turny.gg/guide/playtest). ## The contract {#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 `, 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](https://docs.turny.gg/reference/scripting/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 {#arguments} | # | Argument | Type | Description | | --- | --- | --- | --- | | 1 | `deck` | `PlaytestScriptDeck` | The player's deck: card code to number of copies, per deck zone (fields below). | | 2 | `cardsById` | `Record` | 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. | | 3 | `ctx` | `PlaytestScriptContext \| undefined` | Optional 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. | Property | Type | Description | | --- | --- | --- | | `main` | `Record` | | | `sideboard` | `Record` | | | `command` | `Record` | | `PlaytestScriptContext`: | Property | Type | Description | | --- | --- | --- | | `globals` | `unknown` | The 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](https://docs.turny.gg/reference/card-data/cyberpunk), [Flesh and Blood](https://docs.turny.gg/reference/card-data/fab), [Hearthstone](https://docs.turny.gg/reference/card-data/hs), [Legends of Runeterra](https://docs.turny.gg/reference/card-data/lor), [Palworld TCG](https://docs.turny.gg/reference/card-data/palworld), [Pokémon TCG](https://docs.turny.gg/reference/card-data/pokemon) and [Riftbound](https://docs.turny.gg/reference/card-data/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 {#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](#enums). Anything else, a missing field, or a reference to something the definition does not declare is rejected with an [issue code](#issue-codes), and the table is not built. ## The table definition {#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. | Property | Type | Description | | --- | --- | --- | | `version` | `1` | Manifest format version. | | `table` | `PlaytestTableDefinition` | Table grid size. | | `zones` | `PlaytestZoneDefinition[]` | Every zone on the table. | | `trackers` | `PlaytestTrackerDefinition[]` | Numeric counters on sides or the table. | | `markers` | `PlaytestMarkerDefinition[]` | Counters and badges placed on cards. | | `flags?` | `PlaytestFlagDefinition[]` | On/off card flags that `flag` steps set. Omitted declares none. | | `actions` | `PlaytestActionDefinition[]` | Everything the player can do. | | `roundActionId?` | `string` | The 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. | | `setup` | `PlaytestStep[]` | Steps run for each side on New game, after `initialZones` is placed. | | `initialZones` | `Record` | Where the deck's cards start: zone id → card codes, repeated once per copy. Applied per side from that side's deck. | | `cardTags?` | `Record` | Tags per card code, computed by the script from `cardsById`; `tag` predicates read them. | | `associatedCards?` | `Record` | 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. | Property | Type | Description | | --- | --- | --- | | `columns` | `number` | Grid columns per side; the shared strip uses the same columns. | | `rows` | `number` | Grid rows per side. | | `sharedRows?` | `number` | Rows of the shared strip between the two halves. Defaults to 1 when any zone is shared. | ### zones (`PlaytestZoneDefinition`) One zone (pile) on the table. | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Unique id within the definition, referenced by steps and predicates. | | `label` | `string` | Display name. | | `labelKey?` | `string` | Optional i18n key under `playtest.labels.*`; falls back to `label`. | | `owner` | `PlaytestZoneOwner` | Once per side, or once for the table. | | `visibility` | `PlaytestZoneVisibility` | Who sees card faces. | | `layout` | `PlaytestZoneLayout` | How cards are arranged. | | `area` | `PlaytestZoneArea` | Grid 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?` | `PlaytestSharedPlacement` | `Shared` zones only: where the zone renders. Defaults to `Strip`. | | `removesCreated?` | `boolean` | When true, created cards (`created: true`) that enter this zone leave the game instead, e.g. MTG tokens going to the graveyard. | | `capacity?` | `number` | Max cards (or card stacks for `Slots`). Omitted is unlimited. A `capacity` step can change it per zone instance during a game. | | `ordered` | `boolean` | Whether card order matters (a deck, a discard pile). | | `defaultFaceDown` | `boolean` | Face state a card takes on entry when the moving step does not set one. | | `enterState?` | `PlaytestZoneEnterState` | State forced on every entering card. | | `showCount?` | `boolean` | Shows a card-count badge. Defaults to true for `Pile` layouts. | | `primaryActionId?` | `string` | Action run by clicking the zone itself (e.g. the deck draws). `Alt`-click runs it on the opponent's zone. | | `accepts?` | `PlaytestPredicate` | Cards must match this to be dropped or moved in; others are refused. | | `dropActionId?` | `string` | Action 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. | Property | Type | Description | | --- | --- | --- | | `row` | `number` | 0-based row. | | `col` | `number` | 0-based column. | | `rowSpan?` | `number` | Rows spanned. Defaults to 1. | | `colSpan?` | `number` | Columns spanned. Defaults to 1. | ### Zone enter state (`PlaytestZoneEnterState`) State forced on every card that enters a zone, over the moving step's values. | Property | Type | Description | | --- | --- | --- | | `rotation?` | `PlaytestRotation` | Rotation to set, e.g. `0` so a discarded card is ready. | | `faceDown?` | `boolean` | Face state to set, e.g. `false` so a hand never holds face-down cards. | | `resetCounters?` | `boolean` | When true, clears every marker count on entry. | | `resetFlags?` | `boolean` | When true, clears every flag on entry. | ### trackers (`PlaytestTrackerDefinition`) A numeric counter on a side or on the table (life, prizes, points, mana). | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Unique id within the definition. | | `label` | `string` | Display name. | | `labelKey?` | `string` | Optional i18n key under `playtest.labels.*`; falls back to `label`. | | `initial` | `number` | Value on New game. | | `min?` | `number` | Lowest allowed value. | | `max?` | `number` | Highest allowed value. | | `owner` | `PlaytestZoneOwner` | One per side, or one shared. | ### markers (`PlaytestMarkerDefinition`) A counter or badge placed on cards (damage, +1/+1, buffs). | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Unique id within the definition. | | `label` | `string` | Display name. | | `labelKey?` | `string` | Optional i18n key under `playtest.labels.*`; falls back to `label`. | | `step` | `number` | Amount one +/- click changes it by, e.g. `10` for Pokémon damage. | | `min?` | `number` | Lowest allowed count. Defaults to 0. | | `color?` | `string` | CSS 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. | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Unique id within the definition, referenced by steps and predicates. | | `label` | `string` | Display name. | | `labelKey?` | `string` | Optional i18n key under `playtest.labels.*`; falls back to `label`. | ### actions (`PlaytestActionDefinition`) Something the player can do: a named, triggerable list of steps. | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Unique id within the definition; the history references it. | | `label` | `string` | Menu and shortcut-sheet text. | | `labelKey?` | `string` | Optional i18n key under `playtest.labels.*`; falls back to `label`. | | `description?` | `string` | Optional 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. | | `target` | `PlaytestActionTarget` | What 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?` | `PlaytestPredicate` | For `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?` | `boolean` | Lists the action in the target's right-click menu. Defaults to true. | | `group?` | `string` | Menu section heading; actions sharing a group are listed together. | | `shortcut?` | `string` | Keyboard 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: "" }`. | | `steps` | `PlaytestStep[]` | Steps run in order, as one undo unit. | ### Action params (`PlaytestActionParam`) A value the user supplies when running an action (draw N, which zone). | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Id steps reference with `{ param: "" }`. | | `label` | `string` | Prompt text. | | `labelKey?` | `string` | Optional i18n key under `playtest.labels.*`; falls back to `label`. | | `kind` | `PlaytestActionParamKind` | Number or choice. | | `default?` | `number \| string` | Pre-filled value; required for the action to run without a prompt. | | `min?` | `number` | Lowest allowed `Number` value. | | `max?` | `number` | Highest allowed `Number` value. | | `options?` | `PlaytestActionParamOption[]` | The options of a `Choice` param. | | `cardSource?` | `PlaytestCardSource` | Where a `Card` param's candidates come from. | ### Param options (`PlaytestActionParamOption`) One selectable option of a `Choice` param. | Property | Type | Description | | --- | --- | --- | | `value` | `number \| string` | The value passed to steps. | | `label` | `string` | Display name. | | `labelKey?` | `string` | Optional 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`). | Property | Type | Description | | --- | --- | --- | | `kind` | `PlaytestCardSourceKind` | Which cards are offered. | | `where?` | `PlaytestPredicate` | Keep only candidates whose tags satisfy this predicate. | ## Enums {#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. | Member | Value | Description | | --- | --- | --- | | `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). | Member | Value | Description | | --- | --- | --- | | `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. | Member | Value | Description | | --- | --- | --- | | `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. | Member | Value | Description | | --- | --- | --- | | `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. | Member | Value | Description | | --- | --- | --- | | `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). | Member | Value | Description | | --- | --- | --- | | `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`. | Member | Value | Description | | --- | --- | --- | | `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. | Member | Value | Description | | --- | --- | --- | | `Associated` | `"associated"` | The target card's associated cards. | ### `PlaytestZonePosition` Where a card goes in, or is taken from, an ordered zone. | Member | Value | Description | | --- | --- | --- | | `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. | Member | Value | Description | | --- | --- | --- | | `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. | Member | Value | Description | | --- | --- | --- | | `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. | Member | Value | Description | | --- | --- | --- | | `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 {#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`): | Property | Type | Description | | --- | --- | --- | | `param` | `string` | Id 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`. `{ 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. | Property | Type | Description | | --- | --- | --- | | `tracker` | `string` | Id of a tracker in the definition's `trackers`. | | `side?` | `PlaytestTrackerRefSide` | Which 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". | Property | Type | Description | | --- | --- | --- | | `zone` | `PlaytestValue` | Zone to take cards from. | | `count?` | `PlaytestValue` | How many cards to take. Omitted takes every matching card. | | `pick?` | `PlaytestZonePosition` | Which end to take from (`Index` is not allowed here). Defaults to `Top`. | | `where?` | `PlaytestPredicate` | Only 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. | kind | Description | | --- | --- | | `"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). | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to move. Omitted moves the action's targets. | | `to` | `PlaytestValue` | Destination zone id. | | `position?` | `PlaytestZonePosition` | Where the cards go in the destination. Defaults to `Top`. | | `index?` | `PlaytestValue` | 0-based index from the top; required when `position` is `Index`. | | `faceDown?` | `boolean` | Face 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). | Property | Type | Description | | --- | --- | --- | | `from` | `PlaytestValue` | Zone drawn from (usually the deck). | | `to` | `PlaytestValue` | Zone drawn into (usually the hand). | | `count?` | `PlaytestValue` | Cards to draw. Defaults to 1; stops early when `from` runs out. | | `faceDown?` | `boolean` | Face state in `to`. Omitted uses the destination's `defaultFaceDown`. | #### `kind: "shuffle"` Shuffle a zone with the seeded game RNG (redo reproduces the same order). | Property | Type | Description | | --- | --- | --- | | `zone` | `PlaytestValue` | Zone to shuffle. | #### `kind: "flip"` Turn cards face-up or face-down. | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to flip. Omitted flips the action's targets. | | `faceDown?` | `boolean` | The face state to set. Omitted toggles each card. | #### `kind: "rotate"` Rotate cards (tap / exhaust). | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to rotate. Omitted rotates the action's targets. | | `to?` | `PlaytestRotation` | The 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`. | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to change. Omitted changes the action's targets. | | `marker` | `string` | Id of a marker in the definition's `markers`. | | `delta?` | `PlaytestValue` | Amount to add (negative removes). | | `set?` | `PlaytestValue` | 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. | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to attach. Omitted attaches the action's targets. | | `mode` | `PlaytestAttachMode` | Whether 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. | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to detach. Omitted detaches the action's targets. | | `to?` | `PlaytestValue` | Optional zone to move the detached cards to. | | `position?` | `PlaytestZonePosition` | Where 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. | Property | Type | Description | | --- | --- | --- | | `tracker` | `string` | Id of a tracker in the definition's `trackers`. | | `delta?` | `PlaytestValue` | Amount to add (negative subtracts). | | `set?` | `PlaytestValue` | Absolute value to set. | | `toggle?` | `true` | Flips 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"). | Property | Type | Description | | --- | --- | --- | | `zones` | `string[]` | Zone ids to ready. | | `skipFlag?` | `string` | Id 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). | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to reveal. Omitted reveals the action's targets. | | `revealed?` | `boolean` | Whether 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. | Property | Type | Description | | --- | --- | --- | | `die` | `PlaytestValue` | Number of sides; `2` is a coin flip. | | `count?` | `PlaytestValue` | Number of dice to roll. Defaults to 1. | #### `kind: "log"` Append a line of text to the game log. | Property | Type | Description | | --- | --- | --- | | `message` | `string` | The text, shown verbatim. | #### `kind: "turn"` Change the game turn counter (`PlaytestGameState.turn`). Set exactly one of `delta` and `set`; both omitted adds 1. | Property | Type | Description | | --- | --- | --- | | `delta?` | `PlaytestValue` | Amount to add. | | `set?` | `PlaytestValue` | 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`. | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to change. Omitted changes the action's targets. | | `flag` | `string` | Id of a flag in the definition's `flags`. | | `mode` | `PlaytestFlagMode` | What 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`. | Property | Type | Description | | --- | --- | --- | | `flag` | `string` | Id of a flag in the definition's `flags`. | | `zones` | `string[]` | 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. | Property | Type | Description | | --- | --- | --- | | `zone` | `PlaytestValue` | Zone id. | | `delta?` | `PlaytestValue` | Amount to add to the current capacity. | | `set?` | `PlaytestValue` | 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`. | Property | Type | Description | | --- | --- | --- | | `steps` | `PlaytestStep[]` | 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. | Property | Type | Description | | --- | --- | --- | | `until` | `PlaytestPredicate` | Stops the loop once true; resolved against the acting side. | | `steps` | `PlaytestStep[]` | Primitive steps run on each pass. | | `maxIterations` | `number` | Upper 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`. | Property | Type | Description | | --- | --- | --- | | `card` | `"target" \| PlaytestValue` | The card to create: `"target"` copies each target's card code; otherwise a literal card code or `{ param }` (usually a `Card` param). | | `to?` | `PlaytestValue` | Destination zone id. Omitted: each target's own zone (required with no card target). | | `position?` | `PlaytestZonePosition` | Where the cards go in the destination. Defaults to `Top`; `Index` is not allowed. | | `count?` | `PlaytestValue` | 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?` | `boolean` | Face 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. | Property | Type | Description | | --- | --- | --- | | `card` | `PlaytestValue` | 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. | Property | Type | Description | | --- | --- | --- | | `cards?` | `PlaytestCardSelector` | Cards to remove. Omitted removes the action's targets. | ## Predicates {#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`. | kind | Description | | --- | --- | | `"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`. | Property | Type | Description | | --- | --- | --- | | `tag` | `string` | Tag name. | #### `kind: "zone"` True when the card is currently in this zone. | Property | Type | Description | | --- | --- | --- | | `zone` | `string` | Zone id. | #### `kind: "faceDown"` True when the card's face state equals `faceDown`. | Property | Type | Description | | --- | --- | --- | | `faceDown` | `boolean` | The face state to match. | #### `kind: "rotated"` True when the card's rotated state (any rotation but `0`) equals `rotated`. | Property | Type | Description | | --- | --- | --- | | `rotated` | `boolean` | The rotated state to match. | #### `kind: "counterAtLeast"` True when the card holds at least `n` of a marker. | Property | Type | Description | | --- | --- | --- | | `marker` | `string` | Marker id. | | `n` | `number` | Minimum count. | #### `kind: "flag"` True when the card carries this flag. | Property | Type | Description | | --- | --- | --- | | `flag` | `string` | Id 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. | Property | Type | Description | | --- | --- | --- | #### `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. | Property | Type | Description | | --- | --- | --- | | `zone` | `string` | Zone id. | | `where?` | `PlaytestPredicate` | Only cards matching this count. Omitted counts every card. | | `atLeast?` | `number` | Minimum matching cards. Defaults to 1. | #### `kind: "all"` True when every child is true (an empty list is true). | Property | Type | Description | | --- | --- | --- | | `all` | `PlaytestPredicate[]` | Child predicates. | #### `kind: "any"` True when at least one child is true (an empty list is false). | Property | Type | Description | | --- | --- | --- | | `any` | `PlaytestPredicate[]` | Child predicates. | #### `kind: "not"` True when the child is false. | Property | Type | Description | | --- | --- | --- | | `not` | `PlaytestPredicate` | The negated predicate. | ## Shortcuts {#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+]`. `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. | Keys | Tokens | | --- | --- | | Letters | `a` to `z` | | Digits | `0` to `9` | | Digit range | `1-9` | | Named keys | `space`, `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`): | Key | Used for | | --- | --- | | `mod+z` | Undo | | `mod+shift+z` | Redo | | `mod+y` | Redo | | `?` | Open the shortcut sheet | | `escape` | Clear the selection | ### Examples | Shortcut | Result | Notes | | --- | --- | --- | | `"d"` | Binds `d` | The D key. | | `"shift+d"` | Binds `shift+d` | Shift and D. | | `"mod+d"` | Binds `mod+d` | Cmd+D on macOS, Ctrl+D elsewhere. | | `"Shift+Mod+D"` | Binds `mod+shift+d` | Same as `mod+shift+d`: case and modifier order don't matter. | | `"1-9"` | Binds `1-9` | Every digit key; the pressed digit fills the action's first `number` param. | | `"alt+d"` | Rejected: `shortcut_uses_alt` | Alt is reserved for the opponent side. | | `"option+d"` | Rejected: `shortcut_uses_alt` | Option is Alt on macOS. | | `"ctrl+d"` | Rejected: `invalid_shortcut` | Write `mod`, never `ctrl` or `cmd`. | | `"mod+z"` | Rejected: `shortcut_reserved` | Undo belongs to the table. | | `"shift+/"` | Rejected: `shortcut_reserved` | The same physical keys as `?`. | ## How actions run {#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 {#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. | Cap | Limit | Applies to | | --- | --- | --- | | `maxZones` | 40 | Zones in `zones`. | | `maxActions` | 150 | Actions in `actions`. | | `maxStepsPerAction` | 32 | Steps in one action's `steps`, counting the steps inside block steps. | | `maxSetupSteps` | 64 | Steps in `setup`, counting the steps inside block steps. | | `maxRepeatIterations` | 20 | A `repeatUntil` step's `maxIterations`. | | `maxMarkers` | 24 | Markers in `markers`. | | `maxTrackers` | 24 | Trackers in `trackers`. | | `maxFlags` | 24 | Flags in `flags`. | | `maxParamsPerAction` | 8 | Params in one action's `params`. | | `maxParamOptions` | 32 | Options in one `choice` param. | | `maxCardInstances` | 500 | Card instances across every `initialZones` list (one side's deck). | | `maxTaggedCards` | 2000 | Card codes in `cardTags`. | | `maxTagsPerCard` | 24 | Tags on one card code. | | `maxAssociatedCards` | 2000 | Card codes in `associatedCards`. | | `maxAssociatedPerCard` | 48 | Associated card codes listed for one card code. | | `maxCreateCount` | 20 | A `create` step's literal `count` (the engine also clamps to it). | | `maxPredicateDepth` | 8 | Nesting depth of one predicate tree. | | `maxPredicateNodes` | 64 | Nodes in one predicate tree. | | `maxTableColumns` | 24 | `table.columns`. | | `maxTableRows` | 12 | `table.rows`. | | `maxSharedRows` | 6 | `table.sharedRows`. | | `maxIdLength` | 64 | Characters in an id or reference (zone, action, tracker, marker, param, tag). | | `maxCardCodeLength` | 128 | Characters in a card code. | | `maxLabelLength` | 200 | Characters in a label, label key, group or color. | | `maxLogMessageLength` | 500 | Characters in a `log` step's message. | | `maxDescriptionLength` | 500 | Characters 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 {#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](https://docs.turny.gg/guide/playtest#troubleshooting) explains how to fix each one. | Code | Shown in the app | Meaning | | --- | --- | --- | | `script_unsafe` | The rules script uses code that isn't allowed. | The static safety gate rejected the source (`metadata.safetyCode`). | | `script_error` | The rules script failed to run. | The script threw, or did not default-export a function. | | `invalid_shape` | The 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_version` | The rules script returned an unsupported version ({version}). | `version` is not `1`. | | `over_cap` | The rules script returned more than the allowed {limit}. | A list, record, string or number is over its `PLAYTEST_DEFINITION_CAPS` entry. | | `invalid_id` | The rules script used an invalid id. | An id or record key is empty, malformed or an `Object.prototype` name. | | `duplicate_zone_id` | Zone "{id}" is declared more than once. | Two zones share an id. | | `duplicate_action_id` | Action "{id}" is declared more than once. | Two actions share an id. | | `duplicate_tracker_id` | Tracker "{id}" is declared more than once. | Two trackers share an id. | | `duplicate_marker_id` | Marker "{id}" is declared more than once. | Two markers share an id. | | `duplicate_param_id` | Option "{id}" is declared more than once. | Two params share an id. | | `duplicate_flag_id` | Flag "{id}" is declared more than once. | Two flags share an id. | | `unknown_zone` | The rules script refers to an unknown zone, "{zone}". | A step, predicate, action, param option or `initialZones` key names an undeclared zone. | | `unknown_action` | The rules script refers to an unknown action, "{action}". | `primaryActionId` / `dropActionId` / `roundActionId` names an undeclared action. | | `invalid_round_action` | The 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_tracker` | The rules script refers to an unknown tracker, "{tracker}". | A `tracker` step or a `{ tracker }` value names an undeclared tracker. | | `unknown_flag` | The rules script refers to an unknown flag, "{flag}". | A `flag` / `clearFlag` step, `readyAll.skipFlag` or `flag` predicate names an undeclared flag. | | `invalid_tracker_ref` | Tracker "{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_toggle` | Tracker "{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_step` | A "{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_setup` | Setup already runs once for each side, so it can't use forEachSide. | `setup` uses `forEachSide`; setup already runs once per side. | | `condition_needs_zone_has` | A repeatUntil condition can only check zones with zoneHas, not "{kind}". | A `repeatUntil` condition tests a card; it may only combine `zoneHas` leaves. | | `unknown_marker` | The rules script refers to an unknown marker, "{marker}". | A `counter` step or `counterAtLeast` predicate names an undeclared marker. | | `unknown_param` | The rules script refers to an unknown option, "{param}". | A `{ param }` reference names a param the action does not declare (setup has none). | | `param_kind_mismatch` | Option "{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_table` | Zone "{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_overlap` | Zones "{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_shortcut` | The rules script has an invalid keyboard shortcut. | A shortcut does not follow the grammar (`[mod+][shift+]`). | | `shortcut_uses_alt` | Shortcut "{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_reserved` | Shortcut "{shortcut}" is reserved by the playtest table. | A shortcut shadows an engine key (`PLAYTEST_RESERVED_SHORTCUTS`). | | `shortcut_conflict` | Shortcut "{shortcut}" is bound to more than one action. | Two actions in the same target scope share a shortcut. | | `card_param_needs_source` | Card 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_tag` | A 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_target` | A 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_timeout` | The 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_failed` | The 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 {#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. | Game | Rules | Source | | --- | --- | --- | | Cyberpunk TCG | Standard | [Read the script](https://cyberpunk.turny.gg/playtest-rules/019a6a4c-7c50-7a01-9c2e-4f1d8b3e7c50) | | Flesh and Blood | Standard | [Read the script](https://fab.turny.gg/playtest-rules/01926f3a-2067-7000-8000-000000000001) | | Hearthstone | Standard | [Read the script](https://hs.turny.gg/playtest-rules/01926f3a-1118-7000-8000-000000000001) | | Legends of Runeterra | Standard | [Read the script](https://lor.turny.gg/playtest-rules/01926f3a-1019-7000-8000-000000000001) | | Magic: The Gathering | Standard | [Read the script](https://mtg.turny.gg/playtest-rules/019a2b40-1022-7a01-8c3e-5d2f7b9e1022) | | Magic: The Gathering | Commander | [Read the script](https://mtg.turny.gg/playtest-rules/019a2b40-1022-7a02-8c3e-5d2f7b9e1022) | | Palworld TCG | Standard game | [Read the script](https://palworld.turny.gg/playtest-rules/01926f3a-9a1d-7000-8000-000000000001) | | Pokémon TCG | Standard | [Read the script](https://pokemon.turny.gg/playtest-rules/019a1f6e-5c3d-7a41-9b2e-6f0d4c8a1020) | | Riftbound | Standard | [Read the script](https://riftbound.turny.gg/playtest-rules/01926f3a-1021-7000-8000-000000000001) | --- url: https://docs.turny.gg/reference/card-data/cyberpunk description: "Every field a script can read on a Cyberpunk TCG card and in its game globals." --- # Cyberpunk TCG card data Ruleset and calculator scripts get Cyberpunk TCG cards as plain objects straight from the card catalog. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs A Cyberpunk TCG card in the catalog is a **card identity**: one playable card with all of its printings (Nova Rare and Iconic alternates, starter deck and promo reprints) listed under `printings`. Two kinds of id matter: - The **identity id**, `card.id`: `cp-` plus a hash, like `cp-01f71059135ee373ac32`. - A **printing id**: the short set code and the collector number, like `wnc-071`. An alternate art has its own number in the same set (`wnc-150`). Each printing's rarity and artist are in `printing.metadata` (`{ "rarity": "iconic_legend", "artist": "Pandart Studio" }`). Decks store **printing ids**. `cardsById` is keyed by the deck's refs, and each one points to its **identity**, so two printings of the same card in one deck resolve to the same object: - Count copies of "the same card" by `card.id`, not by ref. - To read the printing a ref points to, find it in the list: `card.printings.find((p) => p.id === ref)`. - `ctx.globals.aliases[ref]` gives the identity id for any printing id, when globals are available. A card rule gets the identity card itself, so `card.id` is always the identity id. The `game` fields describe the card's **default printing** (`game.defaultPrintingId`): the Retail base set printing when there is one. That matters for per-printing fields such as `rarity`, `setCode` and `artist`; `printingRarities` lists the rarity of every printing. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to Cyberpunk TCG lives on `card.game`. Classification values (`cardType`, `color`, `rarity`) are lower-case tokens you can compare directly; look them up in the globals for display names. Legends print no Eddie cost and Programs print no Power, so `cost` and `power` can be `null`. | Property | Type | Description | | --- | --- | --- | | `cardType` | `CyberpunkCardType` | Card type: `"legend"`, `"unit"`, `"gear"` or `"program"`. | | `color` | `CyberpunkColor` | The card's single colour, which is also its RAM colour (CR §3.20.1.2). | | `rarity` | `CyberpunkRarity` | Rarity of the default printing (`"rare"`, `"nova_rare"`, …). | | `printingRarities?` | `CyberpunkRarity[]` | Every printing's rarity, distinct, in enum order: the chase treatments (Nova Rare, Iconic) usually print as alternates, so featured-card scoring reads this rather than `rarity`. Non-render (image ingest ignores it). | | `subtitle` | `string \| null` | Printed subtitle (`"Streetkid"` on `"V: Streetkid"`), or `null`. Name plus subtitle identifies a card for copy limits (CR §7.3.3); Legend uniqueness reads the name alone (CR §7.3.1). | | `tags` | `string[]` | Classifications (tags) printed on the card, at least one (`["Merc"]`, `["Arasaka", "Cyberware"]`). | | `keywords` | `string[]` | Keyword markers found in the rules text as `{Marker}` tokens, lower-kebab (`{Go Solo}` becomes `"go-solo"`): `play`, `attack`, `call`, `defeated`, `spend`, `blocker`, `quick`, `go-solo`, `adrenaline`. | | `cost` | `number \| null` | Eddie cost; `null` for the Legends printed without one (rendered `–`). | | `power` | `number \| null` | Power; `null` when the card prints none (Programs). | | `ram` | `number` | RAM value (0..6) in the card's `color` (CR §3.20). A Legend's RAM raises the deck's RAM limit in its colour; every other card must fit within that limit. | | `sellable` | `boolean` | True when the card carries the sell tag (can be sold for 1 Eddie). | | `legalities` | `CyberpunkCardLegalities` | Legality per format (`{ standard: "legal" }`, `"banned"`, or `"not_legal"`). A missing format counts as legal. | | `isProvisional?` | `boolean` | True while every printing of the card is in a set whose curated release date is still in the future (as of catalog generation): such a card is `not_legal` in Standard. Absent once any printing has released, or when the set carries no release date. Same meaning as Pokémon's and Riftbound's `isProvisional`. Viewer-independent (ADL §42). | | `defaultPrintingId` | `string` | Id of the default printing (`"wnc-005a"`, `-`): the Retail base-set printing when there is one, else the earliest printing in curated set order. Deck refs default to it. | | `setCode` | `string` | Short set code of the default printing (`"wnc"`). | | `collectorNumber` | `string` | Collector number of the default printing, lower-case (`"005a"`). | | `artist?` | `string` | Artist of the default printing. | | `text?` | `string` | Rules text in the catalog locale. Keyword markers stay `{Marker}` tokens (`{Blocker}`) and `€$` stands for Eddies. Absent when the card prints none. | ## Globals (`ctx.globals`) The catalog's globals are lookup tables for the values on a card (`color: "green"` resolves through `ctx.globals.colors.green`), the keyword glossary and the printing alias map. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them and fall back to the raw value. ::: | Property | Type | Description | | --- | --- | --- | | `colors` | `Record` | Colours by `game.color` value (`"red"`). | | `types` | `Record` | Card types by `game.cardType` value (`"unit"`). | | `rarities` | `Record` | Rarities by `game.rarity` value (`"nova_rare"`). | | `tags` | `Record` | Classifications by tag, as printed (`"Arasaka"`). | | `sets` | `Record` | Sets by short set code (`"wnc"`). | | `formats` | `Record` | Formats by `game.legalities` key (`"standard"`). | | `keywords?` | `Record` | Keyword glossary by `game.keywords` id (`"go-solo"`). | | `aliases` | `Record` | Printing or variant id → identity id; identity ids map to themselves. | ### Lookup entries Every table except `keywords` and `aliases` maps a key to an entry with these fields: | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Display name (`"Red"`, `"Nova Rare"`). | | `order` | `number` | Sort position in filters and lists, lowest first. | | `metadataRef` | `{ key: string; }` | Anchor an operator override is matched on (`"cyberpunk.globals.colors.red"`). | ### Set entries Entries of `sets` add: | Property | Type | Description | | --- | --- | --- | | `sourceSetCode` | `string` | The upstream's set code (`"welcometonightcityretail"`). | | `releaseDate?` | `string` | Curated release date (`YYYY-MM-DD`); absent when the set has none. | ### Keyword entries Each entry of `keywords`: | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Display name (`"Go Solo"`). | | `description` | `string` | Reminder text: what the keyword does. | | `kind` | `"trigger" \| "effect"` | `"trigger"` for a when-this-happens marker (`play`, `attack`), `"effect"` for a static ability (`blocker`, `go-solo`). | | `order` | `number` | Sort position in the glossary, lowest first. | | `metadataRef` | `{ key: string; }` | Operator-override anchor: a published `card_globals_overrides` row (`namespace: "keywords"`, `key: `) patches this entry (#2087). | ## Example card Goro Takemura, Vengeful Bodyguard, trimmed to two printings with one image each: ```json { "id": "cp-01f71059135ee373ac32", "slug": "goro-takemura-vengeful-bodyguard", "name": "Goro Takemura: Vengeful Bodyguard", "setCode": "wnc", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/cyberpunk/assets/cp-01f71059135ee373ac32-card-cea4dbcf6f6f90aed7cf9bb361e01af8be9f28f122fa2362cce48e5d1484e296.webp" } ], "printings": [ { "id": "wnc-071", "setCode": "wnc", "number": "071", "releaseDate": "2026-11-06", "variants": [ { "id": "wnc-071:normal", "kind": "normal" } ], "metadata": { "rarity": "rare", "artist": "Daniel Valaisis" } }, { "id": "wnc-150", "setCode": "wnc", "number": "150", "releaseDate": "2026-11-06", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/cyberpunk/assets/wnc-150-card-cf0a3113ac21b526b5cde56be16b00656616341bdaa4988d5842e215ebf36a0a.webp" } ], "variants": [ { "id": "wnc-150:iconic", "kind": "iconic" } ], "metadata": { "rarity": "iconic_legend", "artist": "Pandart Studio" } } ], "hasImage": true, "game": { "cardType": "legend", "color": "green", "rarity": "rare", "printingRarities": ["rare", "nova_rare", "iconic_legend"], "subtitle": "Vengeful Bodyguard", "tags": ["Arasaka", "Corpo"], "keywords": ["spend", "blocker", "quick"], "cost": null, "power": null, "ram": 2, "sellable": true, "legalities": { "standard": "legal" }, "defaultPrintingId": "wnc-071", "setCode": "wnc", "collectorNumber": "071", "artist": "Daniel Valaisis", "text": "{Quick} 1 €$, {Spend} Give a friendly Unit with cost 4 or less {Blocker} this turn. If you control a value-pair of Gigs, also give it +1 power this turn.\nWhen a friendly Unit uses {Blocker}, you may discard 1. If you do, draw 1." } } ``` ## Common recipes ::: code-group ```js [Eddie curve] // Calculator: main-deck copies at each Eddie cost, 6+ grouped. export default function compute(pile, cardsById) { const buckets = [0, 0, 0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; if (typeof game.cost !== "number") { return; // Legends print no Eddie cost. } buckets[Math.min(game.cost, 6)] += pile[ref]; }); return { widgets: [ { kind: "histogram", label: "Eddie curve", buckets: buckets, labels: ["0", "1", "2", "3", "4", "5", "6+"], }, ], }; } ``` ```js [Count by colour] // Calculator: copies per colour. export default function compute(pile, cardsById) { const counts = {}; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const color = game.color || "other"; counts[color] = (counts[color] || 0) + pile[ref]; }); return { widgets: [ { kind: "donut", label: "Colours", segments: Object.keys(counts).map((color) => ({ label: color, value: counts[color], })), }, ], }; } ``` ```js [Standard legal] // Card rule: not banned in Standard. A card with no entry counts as legal. export default function validateCard(card) { const legalities = (card.game && card.game.legalities) || {}; if (legalities.standard !== "banned") { return true; } return { valid: false, issues: [{ message: card.name + " is banned in Standard." }], }; } ``` ```js [Colour with globals] // Card rule: green cards only. Uses the colour's display name when globals exist. export default function validateCard(card, ctx) { const game = card.game || {}; if (game.color === "green") { return true; } const globals = ctx && ctx.globals; const green = globals && globals.colors && globals.colors.green ? globals.colors.green.label : "green"; return { valid: false, issues: [{ message: card.name + " is not a " + green + " card." }], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/fab description: "Every field a script can read on a Flesh and Blood card and in its game globals." --- # Flesh and Blood card data Ruleset and calculator scripts get Flesh and Blood cards as plain objects straight from the card catalog. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs A Flesh and Blood card in the catalog is a **card identity**: one card name at one pitch, with every printing of it listed under `printings`. The red, yellow and blue versions of a card are three identities, so `Command and Conquer` in red is its own card. Three kinds of id matter: - The **identity id**, `card.id`: `fab-` plus a hash, like `fab-d2dbc5d0a6028396c6ed`. - A **printing id**: one set and collector number in lowercase, like `arc159`. - A **variant id**: one edition and foiling of a printing, like `arc159:f-r` (first edition, rainbow foil). A variant's `metadata` carries its edition, foiling, rarity and TCGplayer product id. A double-faced card is one identity keyed on its front face; the back face is on `game.backFace` and is never a deck card on its own. `cardsById` is keyed by the deck's refs, and each one points to its **identity**: - Count copies of "the same card" by `card.id`, not by ref. - To read the printing a ref points to, find it in the list: `card.printings.find((p) => p.id === ref)`. - `ctx.globals.printings[ref]` gives the identity id for a printing id, when globals are available. A card rule gets the identity card itself, so `card.id` is always the identity id. The `game` fields describe the identity. `rarity` is the rarity of its **default printing** (`game.defaultPrintingId`, the latest released standard-foil printing), and each printing's `metadata` has its own rarity and artists. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to Flesh and Blood lives on `card.game`. Types, classes and talents are lower-case tokens with spaces and hyphens turned into `_` (`defense_reaction`, `demi_hero`); look them up in the globals for display names. A stat the card doesn't have is `null`, and a printed `X` or `*` is `null` too, with the raw value in `variableStats`. | Property | Type | Description | | --- | --- | --- | | `pitch` | `FabPitch \| null` | Pitch value; `null` for cards without a colour bar. Part of the identity. | | `color` | `FabPitchColor \| null` | The printed colour bar as the source spells it, `null` when there is none. Almost always `FAB_PITCH_COLOR_BY_PITCH` of `pitch`, but not always: Goldfin Harpoon is printed yellow with no pitch value, so a text decklist line `Goldfin Harpoon (Yellow)` must match on colour, not pitch. | | `cost` | `number \| null` | Resource cost. | | `power` | `number \| null` | Attack power. | | `defense` | `number \| null` | Defense value. | | `health` | `number \| null` | Hero (and demi-hero / ally) life total. | | `intelligence` | `number \| null` | Hero hand size. | | `arcane` | `number \| null` | Arcane damage the card deals. | | `variableStats?` | `FabVariableStats` | Non-numeric printed stats (`{ cost: "X" }`); absent when every stat is numeric. | | `types` | `FabCardType[]` | Structural types, sorted (`["action", "attack"]`). | | `classes` | `FabClass[]` | Classes; `["generic"]` for class-less cards, two for hybrid cards. | | `talents` | `FabTalent[]` | Talents; empty for untalented cards. | | `subtypes` | `string[]` | The rest of the type line as source tokens (`["Sword"]`, `["Young"]`, `["Evo", "Base"]`); open-ended, never compared as an enum. | | `equipmentSlot` | `FabEquipmentSlot \| null` | Slot an equipment takes; `null` for anything else. | | `weaponHands` | `FabWeaponHands \| null` | Hands a weapon takes; `null` for anything else. | | `keywords` | `string[]` | The card's own keywords as source tokens (`["Go again", "Dominate"]`). | | `isHero` | `boolean` | True for heroes (adult and young). | | `isYoungHero` | `boolean` | True for young heroes (Blitz / Silver Age); adult heroes play CC and LL. | | `playedHorizontally` | `boolean` | Printed landscape (Landmarks, some macros); gets its own art window. | | `legalities` | `FabCardLegalities` | Legality per format (see Legalities below). | | `extraLegalities?` | `{ upf: CardLegalityStatus; } & JsonObject` | Formats carried as source legality data only, no Turny rule or preset (Ultimate Pit Fight). | | `defaultPrintingId?` | `string` | The representative printing (latest released standard-foil, no art variation); the deck-legal ref the builder pool exposes. | | `isProvisional?` | `boolean` | True while no printing of the card has released yet; absent once released. | | `rarity` | `FabRarity \| null` | Rarity of the representative (default) printing's base variant. | | `backFace?` | `FabCardBackFace` | The back face of a double-faced card (see the module header); absent on single-faced cards. Back faces have no legality or pitch of their own. | | `text?` | `string` | Rules text with the source's markdown-ish markup. | | `textPlain?` | `string` | Rules text as plain text. | | `typeText?` | `string` | The printed type line (`"Guardian Action - Attack"`). | ### Legalities The `legalities` object, one entry per format: | Property | Type | Description | | --- | --- | --- | | `cc` | `CardLegalityStatus` | Classic Constructed. | | `blitz` | `CardLegalityStatus` | Blitz. | | `ll` | `CardLegalityStatus` | Living Legend. | | `commoner` | `CardLegalityStatus` | Commoner. | | `silver_age` | `CardLegalityStatus` | Silver Age. | ### Variable stats The `variableStats` object: | Property | Type | Description | | --- | --- | --- | | `cost?` | `string` | Printed cost (`"X"`). | | `power?` | `string` | Printed attack power (`"*"`). | | `defense?` | `string` | Printed defense. | | `health?` | `string` | Printed life. | | `intelligence?` | `string` | Printed intellect. | | `arcane?` | `string` | Printed arcane damage. | ### Back face The `backFace` object of a double-faced card: | Property | Type | Description | | --- | --- | --- | | `name` | `string` | The back face's printed name. | | `types` | `FabCardType[]` | Structural types, as on the front face. | | `classes` | `FabClass[]` | Classes, as on the front face. | | `talents` | `FabTalent[]` | Talents, as on the front face. | | `subtypes` | `string[]` | The rest of the type line as source tokens. | | `cost` | `number \| null` | Resource cost. | | `power` | `number \| null` | Attack power. | | `defense` | `number \| null` | Defense value. | | `health` | `number \| null` | Life total. | | `intelligence` | `number \| null` | Hand size. | | `arcane` | `number \| null` | Arcane damage. | | `variableStats?` | `FabVariableStats` | Non-numeric printed stats; absent when every stat is numeric. | | `keywords` | `string[]` | The back face's keywords as source tokens. | | `text?` | `string` | Rules text with the source's markdown-ish markup. | | `textPlain?` | `string` | Rules text as plain text. | | `typeText?` | `string` | The printed type line. | ### Printing metadata Each printing's `metadata`: | Property | Type | Description | | --- | --- | --- | | `rarity` | `FabRarity` | Rarity of the printing's BASE variant (standard foiling, no art variation). Rarity varies across a printing's variants (a cold-foil full-art variant of a Common is Marvel), so per-variant rarity lives on `FabVariantMetadata.rarity`. | | `artists?` | `string[]` | Artists credited on the printing. | | `flavorText?` | `string` | Printed flavour text, when any. | ### Variant metadata Each printing variant's `metadata`: | Property | Type | Description | | --- | --- | --- | | `edition` | `FabEdition` | Print run (`"first"`, `"unlimited"`, `"none"`, …). | | `foiling` | `FabFoiling` | Foil treatment (`"standard"`, `"rainbow_foil"`, `"cold_foil"`, …). | | `rarity` | `FabRarity` | This variant's own rarity (the source gives one per edition x foiling x art). | | `artVariations?` | `string[]` | Source art-variation codes (`["AA"]` for alternate art, `["EA"]` extended art). | | `tcgplayerProductId?` | `string` | TCGplayer product id, when the variant is listed there. | | `imageUrl?` | `string` | The source render for this variant (the LSS image host, or a fallback host). | | `backImageUrl?` | `string` | A same-card `_BACK` render (double-sided Marvel heroes); not a second face. | ## Globals (`ctx.globals`) The catalog's globals are lookup tables for the values on a card (`classes: ["guardian"]` resolves through `ctx.globals.classes.guardian`), the keyword glossary, the rules-text symbols and the printing map. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them and fall back to the raw value. ::: | Property | Type | Description | | --- | --- | --- | | `classes?` | `Record` | By `FabClass` value. | | `talents?` | `Record` | By `FabTalent` value. | | `types?` | `Record` | By `FabCardType` value. | | `rarities?` | `Record` | By `FabRarity` value. | | `formats?` | `Record` | By `FabFormat` value (the `legalities` keys). | | `sets?` | `Record` | By source set id. | | `keywords?` | `Record` | By source keyword name. | | `symbols?` | `Record` | Card-text symbol inventory keyed by symbol key (`p`, `r`, `d`, `h`, `i`, `t`, `c`, `u`, `x`). | | `printings?` | `Record` | Printing id → owning card identity id (`"mst131"` → `"fab-…"`), covering every emitted printing. A double-faced card's shared printing id maps to the front face's identity. Identity ids are never self-mapped. Same name and meaning as the other games' `globals.printings`. | ### Lookup entries Every table except `symbols` and `printings` maps a key to an entry with these fields: | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Display name in the catalog locale (`"Attack Reaction"`). | | `color?` | `string` | Display color set by an operator override; usually absent. | | `icon?` | `string \| null` | Icon image URL set by an operator override; usually absent. | | `order?` | `number` | Sort position in filters and lists, lowest first. | | `showInFilter?` | `boolean` | Whether the entry is offered as a filter option; absent means shown. | | `metadataRef?` | `FabCatalogMetadataReference` | Anchor an operator override is matched on. | ### Set entries Entries of `sets` add: | Property | Type | Description | | --- | --- | --- | | `releaseDate?` | `string \| null` | Release date (`YYYY-MM-DD`) of the set's earliest edition, when known. | ### Keyword entries Entries of `keywords` add: | Property | Type | Description | | --- | --- | --- | | `description?` | `string` | Reminder text: what the keyword does. | ### Symbol entries Each entry of `symbols`: | Property | Type | Description | | --- | --- | --- | | `token` | `string` | The inline token as it appears in rules text (`"{p}"`). | ## Example card Command and Conquer (red), trimmed to two printings with one image each: ```json { "id": "fab-d2dbc5d0a6028396c6ed", "slug": "command-and-conquer-red", "name": "Command and Conquer", "setCode": "1HP", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/fab/assets/fab-d2dbc5d0a6028396c6ed-card-6265564160020d520a166028818ab80890d155e11b5011dec5acf49eee39f16b.webp" } ], "printings": [ { "id": "1hp360", "setCode": "1HP", "number": "360", "releaseDate": "2022-05-06", "variants": [ { "id": "1hp360:n-s", "kind": "standard", "metadata": { "edition": "none", "foiling": "standard", "rarity": "majestic", "tcgplayerProductId": "270947", "imageUrl": "https://legendstory-production-s3-public.s3.amazonaws.com/media/cards/large/1HP360.webp" } } ], "metadata": { "rarity": "majestic", "artists": ["Fajareka Setiawan"] } }, { "id": "arc159", "setCode": "ARC", "number": "159", "releaseDate": "2020-03-27", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/fab/assets/arc159-card-942a45de4e645df90c415a928ec2007b8af8c13483aae1f4e02013da317861ea.webp" } ], "variants": [ { "id": "arc159:f-r", "kind": "rainbow_foil", "metadata": { "edition": "first", "foiling": "rainbow_foil", "rarity": "majestic", "tcgplayerProductId": "225899", "imageUrl": "https://legendstory-production-s3-public.s3.amazonaws.com/media/cards/large/ARC159-RF.webp" } }, { "id": "arc159:f-s", "kind": "standard", "metadata": { "edition": "first", "foiling": "standard", "rarity": "majestic", "tcgplayerProductId": "225899", "imageUrl": "https://legendstory-production-s3-public.s3.amazonaws.com/media/cards/large/ARC159.webp" } }, { "id": "arc159:u-r", "kind": "rainbow_foil", "metadata": { "edition": "unlimited", "foiling": "rainbow_foil", "rarity": "majestic", "tcgplayerProductId": "225899", "imageUrl": "https://legendstory-production-s3-public.s3.amazonaws.com/media/cards/large/U-ARC159-RF.webp" } }, { "id": "arc159:u-s", "kind": "standard", "metadata": { "edition": "unlimited", "foiling": "standard", "rarity": "majestic", "tcgplayerProductId": "225899", "imageUrl": "https://legendstory-production-s3-public.s3.amazonaws.com/media/cards/large/U-ARC159.webp" } } ], "metadata": { "rarity": "majestic", "artists": ["Fajareka Setiawan"] } } ], "hasImage": true, "game": { "pitch": 1, "color": "red", "cost": 2, "power": 6, "defense": 3, "health": null, "intelligence": null, "arcane": null, "types": ["action", "attack"], "classes": ["generic"], "talents": [], "subtypes": [], "equipmentSlot": null, "weaponHands": null, "keywords": [], "isHero": false, "isYoungHero": false, "playedHorizontally": false, "legalities": { "cc": "legal", "blitz": "legal", "ll": "legal", "commoner": "not_legal", "silver_age": "not_legal" }, "extraLegalities": { "upf": "unknown" }, "rarity": "majestic", "text": "Defense reaction cards can't be played this chain link. When this hits a hero, destroy all cards in their arsenal.", "textPlain": "Defense reaction cards can't be played this chain link. When this hits a hero, destroy all cards in their arsenal.", "typeText": "Generic Action - Attack", "defaultPrintingId": "1hp360" } } ``` ## Common recipes ::: code-group ```js [Pitch split] // Calculator: copies per pitch value. Cards without a colour bar are left out. export default function compute(pile, cardsById) { const counts = { red: 0, yellow: 0, blue: 0 }; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; if (game.color in counts) { counts[game.color] += pile[ref]; } }); return { widgets: [ { kind: "donut", label: "Pitch", segments: Object.keys(counts).map((color) => ({ label: color, value: counts[color], })), }, ], }; } ``` ```js [Cost curve] // Calculator: copies at each resource cost, 4+ grouped. export default function compute(pile, cardsById) { const buckets = [0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; if (typeof game.cost !== "number") { return; // Heroes, equipment and X costs have no number. } buckets[Math.min(game.cost, 4)] += pile[ref]; }); return { widgets: [ { kind: "histogram", label: "Cost curve", buckets: buckets, labels: ["0", "1", "2", "3", "4+"], }, ], }; } ``` ```js [Classic Constructed legal] // Card rule: legal in Classic Constructed. export default function validateCard(card) { const legalities = (card.game && card.game.legalities) || {}; if (legalities.cc === "legal" || legalities.cc === "restricted") { return true; } return { valid: false, issues: [{ message: card.name + " is not legal in Classic Constructed." }], }; } ``` ```js [Class with globals] // Card rule: Guardian or generic cards only. Uses the class's display name when globals exist. export default function validateCard(card, ctx) { const classes = (card.game && card.game.classes) || []; if (classes.indexOf("guardian") !== -1 || classes.indexOf("generic") !== -1) { return true; } const globals = ctx && ctx.globals; const guardian = globals && globals.classes && globals.classes.guardian ? globals.classes.guardian.label : "guardian"; return { valid: false, issues: [{ message: card.name + " is not a " + guardian + " card." }], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/hs description: "Every field a script can read on a Hearthstone card and in its game globals." --- # Hearthstone card data Ruleset and calculator scripts get Hearthstone cards as plain objects straight from the card catalog. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs A Hearthstone card in the catalog is a **card identity**: one card with every printing of it listed under `printings`. Fireball in the Core set and the original Legacy Fireball are two printings of one identity. Two kinds of id matter: - The **identity id**, `card.id`: `hs-` plus a hash, like `hs-64efa621e6de7e750001`. - A **printing id**: Blizzard's card id, like `CORE_CS2_029`. Each printing's `metadata` carries its `dbfId` (the number a deck code stores) and its rarity. `cardsById` is keyed by the deck's refs, and each one points to its **identity**, so two printings of the same card in one deck resolve to the same object: - Count copies of "the same card" by `card.id`, not by ref. - To read the printing a ref points to, find it in the list: `card.printings.find((p) => p.id === ref)`. - `ctx.globals.printings[ref]` gives the identity id for a printing id, and `ctx.globals.dbfIdToPrintingId` maps a deck code's dbfId to its printing, when globals are available. A card rule gets the identity card itself, so `card.id` is always the identity id. The `game` fields describe the card's **default printing** (`game.defaultPrintingId`, the Standard-listed one first). That matters for per-printing fields such as `dbfId`, `cardId`, `setId` and `rarity`. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to Hearthstone lives on `card.game`. Classes, card types, rarities and formats are lower-case tokens (`deathknight`, `minion`); minion types and spell schools keep Blizzard's upper-case tokens (`DRAGON`, `FIRE`). Look any of them up in the globals for display names. A stat the card doesn't have (a spell's `attack`) is left out. | Property | Type | Description | | --- | --- | --- | | `dbfId` | `number` | Blizzard's numeric card id; what deckstrings encode (`1004`). | | `cardId` | `string` | HearthstoneJSON / client card id of the default printing (`"CORE_CS2_029"`). | | `classes` | `HearthstoneClass[]` | Classes that can play the card; single-class cards carry one (`["mage"]`), neutrals `["neutral"]`, dual-class cards two. | | `cardType` | `HearthstoneCardType` | Card type: `"minion"`, `"spell"`, `"weapon"`, `"hero"` or `"location"`. | | `cost?` | `number` | Mana cost. | | `attack?` | `number` | Attack; minions, weapons and some heroes. | | `health?` | `number` | Health; minions and locations (location "durability" is reported as health upstream). | | `durability?` | `number` | Weapon durability. | | `armor?` | `number` | Armor a hero card grants. | | `rarity?` | `HearthstoneRarity` | Rarity; absent on cards the source gives none (some non-collectible cards). | | `races?` | `string[]` | Minion types, upper-case upstream tokens (`["DRAGON"]`, `["BEAST", "MURLOC"]`). | | `spellSchool?` | `string` | Spell school, upper-case upstream token (`"FIRE"`). | | `runeCost?` | `HearthstoneRuneCost` | Death Knight rune cost; absent on cards that need no runes. | | `mechanics?` | `string[]` | Upstream mechanic tokens (`["BATTLECRY", "TAUNT"]`). | | `referencedTags?` | `string[]` | Upstream tokens the card's text references without having them (`["TAUNT"]` on "Give a minion Taunt"). With `mechanics`, the card's official keyword set — what the keyword filter matches. | | `setId` | `string` | Upstream set token of the default printing (`"CORE"`, `"TITANS"`); a `globals.sets` key. | | `legalities` | `HearthstoneCardLegalities` | Legality per format (see Legalities below). | | `isProvisional?` | `boolean` | True while the card is announced but not yet released (present upstream but in neither official Standard nor Wild list). Same name and meaning as Pokémon's / Riftbound's, so the Standard (Future) rule reads every game the same way. Absent once released. | | `copyFamilyRootDbfId` | `number` | dbfId of the root of the card's `copyOfCardId` family (a reprint / Core copy points at its original). The identity's continuity anchor; equals `dbfId` when the card is its own root. | | `defaultPrintingId?` | `string` | Id of the default printing; always the first entry of the card's `printings`. | | `text?` | `string` | Rules text with the client's inline markup (`Battlecry:`, `$3`). | | `textPlain?` | `string` | Rules text as plain text, markup removed. | | `flavorText?` | `string` | Flavor text. | | `artistName?` | `string` | Artist of the default printing. | | `deckSize?` | `number` | The deck size the card sets while it is in the deck (official `deckSizeMod`: Prince Renathal 40, Azalina Soulsever 20, Whizbang 1). Absent on cards that keep the standard 30. | | `sideboard?` | `HearthstoneSideboardRules` | The sideboard the card builds; absent on cards without one. | | `bannedFromSideboard?` | `boolean` | True when the card may not be put in another card's sideboard; absent otherwise. | | `touristClass?` | `HearthstoneClass` | The class a Tourist lets into the deck (official `touristClassId`): a Tourist of the hero's class opens its named class. Absent on non-Tourists. | | `zilliaxModule?` | `HearthstoneZilliaxModuleKind` | Set on Zilliax Deluxe 3000's sideboard-only modules; absent otherwise. | | `bundledBy?` | `string[]` | Catalog identity ids of the cards that bundle this one (the official `bundledCardIds` reversed: a Fabled card's companions point back at the Fabled card), sorted. A bundled card is never added on its own — it rides in the deck with its bundling card, one copy per copy of it. Absent on cards nothing bundles. | | `associatedCardRefs?` | `string[]` | Printing ids (HS card ids) of the cards this one is shown with: the official `childIds` (tokens it creates, the Zilliax modules, a Fabled card's bundled cards) plus HearthstoneJSON's quest-reward / entourage links, in that order. Only cards the catalog carries; absent when none. | ### Legalities The `legalities` object: | Property | Type | Description | | --- | --- | --- | | `standard` | `CardLegalityStatus` | Standard. | | `wild` | `CardLegalityStatus` | Wild. | ### Rune cost The `runeCost` object of a Death Knight card: | Property | Type | Description | | --- | --- | --- | | `blood` | `number` | Blood runes. | | `frost` | `number` | Frost runes. | | `unholy` | `number` | Unholy runes. | ### Sideboard rules The `sideboard` object of a card that builds a sideboard: | Property | Type | Description | | --- | --- | --- | | `maxCards` | `number` | Most cards the sideboard holds (official `maxSideboardCards`). | | `subset?` | `string` | Upstream token for which cards the sideboard takes (official `sideboardSubset`: `"zilliax-modules"`, `"2-cost-minions"`, `"non-hunter-beast"`); absent when any card the deck could run fits (E.T.C.'s band). | | `ignoresClass` | `boolean` | Sideboard cards may be of any class (official `sideboardIgnoresClass`). | | `countsTowardCopyLimit` | `boolean` | Sideboard cards count toward the deck's copy limits (official `sideboardCardsCountAsMax`; Commander Beatrix's pick). | ## Globals (`ctx.globals`) The catalog's globals are lookup tables for the values on a card (`classes: ["mage"]` resolves through `ctx.globals.classes.mage`), the keyword glossary and the deck code maps. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them and fall back to the raw value. ::: | Property | Type | Description | | --- | --- | --- | | `classes?` | `Record` | Classes by `HearthstoneClass` value. | | `rarities?` | `Record` | Rarities by `HearthstoneRarity` value. | | `types?` | `Record` | Card types by `HearthstoneCardType` value. | | `races?` | `Record` | Minion types by upstream token (a `HearthstoneCardGameData.races` entry: `"MECHANICAL"` → Mech): every token a catalog card carries. | | `spellSchools?` | `Record` | Spell schools by upstream token (a `HearthstoneCardGameData.spellSchool`: `"FIRE"` → Fire): every token a catalog card carries. | | `formats?` | `Record` | Formats by `HearthstoneFormat` value (the `legalities` keys). | | `sets?` | `Record` | Sets by upstream set token (`"CORE"` → Core). | | `keywords?` | `Record` | Keyword glossary by upstream tag (a `mechanics` / `referencedTags` token): only the tags that are official keywords on pool cards, labelled and described from Blizzard's keyword metadata in the catalog locale. | | `printings?` | `Record` | Printing id → owning card identity id (`"CORE_CS2_029"` → `"hs-…"`), covering every emitted printing. Only printing ids are keys: identity ids are never self-mapped (a self-map would make the catalog seed create a phantom printing per identity). Same name and meaning as MTG's / Pokémon's `globals.printings`. | | `dbfIdToPrintingId?` | `Record` | dbfId (as a string key) → printing id, covering every printing a deckstring can reference (`"1004"` → `"CORE_CS2_029"`). | | `defaultPrintingIdByIdentity?` | `Record` | Card identity id → its default printing id (Standard-listed first, then Wild-listed). A Standard deckstring writes this printing's dbfId, because the client judges Standard per dbfId and reads a Legacy copy as Wild (#2630). Optional: catalogs exported before it encode every printing as held. | | `heroDbfIdToClass?` | `Record` | Hero card dbfId (base heroes and every skin) → its class, so a deckstring's hero resolves to a class whichever skin it names. | ### Lookup entries Every table up to `keywords` maps a key to an entry with these fields: | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Display name in the catalog locale (`"Death Knight"`). | | `color?` | `string` | Display color set by an operator override; usually absent. | | `icon?` | `string \| null` | Icon image URL set by an operator override; usually absent. | | `order?` | `number` | Sort position in filters and lists, lowest first. | | `showInFilter?` | `boolean` | Whether the entry is offered as a filter option; absent means shown. | | `metadataRef?` | `HearthstoneCatalogMetadataReference` | Anchor an operator override is matched on. | ### Set entries Entries of `sets` add: | Property | Type | Description | | --- | --- | --- | | `releaseDate?` | `string \| null` | Release date (`YYYY-MM-DD`) when known. | | `setGroup?` | `string \| null` | Set group the set belongs to (a rotation year / expansion block), when known. | ### Keyword entries Entries of `keywords` add: | Property | Type | Description | | --- | --- | --- | | `description?` | `string` | Reminder text: what the keyword does. | ## Example card Fireball, with its Core and Legacy printings: ```json { "id": "hs-64efa621e6de7e750001", "slug": "fireball", "name": "Fireball", "setCode": "CORE", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/hearthstone/assets/hs-64efa621e6de7e750001-card-f1acaa1cd4ffbc04a3058d048a247be1c807374474716f0e6298102ed3319399.webp" } ], "printings": [ { "id": "CORE_CS2_029", "setCode": "CORE", "metadata": { "dbfId": 69501, "rarity": "common", "craftable": false } }, { "id": "CS2_029", "setCode": "LEGACY", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/hearthstone/assets/CS2_029-card-deb20c7165af34e45b116c65a24752984ea07e974f1c0ff39db104829c5a9c07.webp" } ], "metadata": { "dbfId": 315, "rarity": "free" } } ], "hasImage": true, "game": { "dbfId": 69501, "cardId": "CORE_CS2_029", "classes": ["mage"], "cardType": "spell", "cost": 4, "rarity": "common", "spellSchool": "FIRE", "setId": "CORE", "legalities": { "standard": "legal", "wild": "legal" }, "copyFamilyRootDbfId": 315, "defaultPrintingId": "CORE_CS2_029", "text": "Deal $6 damage.", "textPlain": "Deal 6 damage.", "flavorText": "This spell is useful for burning things. If you're looking for spells that toast things, or just warm them a little, you're in the wrong place.", "artistName": "Ralph Horsley" } } ``` ## Common recipes ::: code-group ```js [Mana curve] // Calculator: copies at each mana cost, 7+ grouped. export default function compute(pile, cardsById) { const buckets = [0, 0, 0, 0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; if (typeof game.cost !== "number") { return; } buckets[Math.min(game.cost, 7)] += pile[ref]; }); return { widgets: [ { kind: "histogram", label: "Mana curve", buckets: buckets, labels: ["0", "1", "2", "3", "4", "5", "6", "7+"], }, ], }; } ``` ```js [Count by type] // Calculator: copies per card type. export default function compute(pile, cardsById) { const counts = {}; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const type = game.cardType || "other"; counts[type] = (counts[type] || 0) + pile[ref]; }); return { widgets: [ { kind: "donut", label: "Card types", segments: Object.keys(counts).map((type) => ({ label: type, value: counts[type], })), }, ], }; } ``` ```js [Standard legal] // Card rule: legal in Standard. export default function validateCard(card) { const legalities = (card.game && card.game.legalities) || {}; if (legalities.standard === "legal") { return true; } return { valid: false, issues: [{ message: card.name + " is not legal in Standard." }], }; } ``` ```js [Class with globals] // Card rule: Mage or neutral cards only. Uses the class's display name when globals exist. export default function validateCard(card, ctx) { const classes = (card.game && card.game.classes) || []; if (classes.indexOf("mage") !== -1 || classes.indexOf("neutral") !== -1) { return true; } const globals = ctx && ctx.globals; const mage = globals && globals.classes && globals.classes.mage ? globals.classes.mage.label : "mage"; return { valid: false, issues: [{ message: card.name + " is not a " + mage + " card." }], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/lor description: "Every field a script can read on a Legends of Runeterra card and in its game globals." --- # Legends of Runeterra card data Ruleset and calculator scripts get Legends of Runeterra cards as plain objects straight from the card catalog. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs Every Legends of Runeterra card is keyed by its **card code**, the same code the game client and deck codes use: - `01DE012` is set `01`, region `DE` (Demacia), card `012`. - Tokens and level-ups add a suffix: `01DE012T1` is Garen's level-up. A deck is a map of card code to copies (`{ "01DE012": 3 }`), and `cardsById` uses the same card codes as keys, so `cardsById[ref]` is always the card for a deck entry. Legends of Runeterra has no reprints, so cards have no `printings` list. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ## Game fields (`card.game`) Everything specific to Legends of Runeterra lives on `card.game`. Text fields and `type` / `supertype` are in the viewer's language, so compare the `*Ref` fields in logic: `typeRef` is `"Unit"` in every language, while `type` is `"Einheit"` in German. | Property | Type | Description | | --- | --- | --- | | `associatedCardRefs?` | `string[]` | Card codes of related cards: level-ups, spawned tokens, spells a champion creates (`["01DE012T1"]`). | | `formatRefs?` | `string[]` | Formats the card is legal in, as `globals.formats` keys (`"client_Formats_Standard_name"`). | | `keywordRefs?` | `string[]` | Keywords on the card, as `globals.keywords` keys (`"QuickStrike"`, `"Regeneration"`). | | `rarityRef?` | `string` | Rarity key into `globals.rarities`: `"Common"`, `"Rare"`, `"Epic"`, `"Champion"` or `"None"` (tokens, spells a card creates). | | `regionRefs?` | `string[]` | Regions, as `globals.regions` keys (`"Demacia"`, `"PiltoverZaun"`). A Runeterra champion's own cards also carry its card code (`"06RU001"`), matching a `globals.runeterraChampions` key. | | `spellSpeedRef?` | `string` | Spell speed key into `globals.spellSpeeds` (`"Burst"`, `"Fast"`, `"Slow"`); spells only. | | `vocabTerms?` | `string[]` | Glossary terms linked from the card text, as `globals.vocabTerms` keys (`"Strike"`, `"Allegiance"`). | | `supertype?` | `string` | Localized supertype; `"Champion"` on champions, absent otherwise. Use `supertypeRef` in logic. | | `type?` | `string` | Localized card type (`"Unit"`, `"Einheit"` in German). Use `typeRef` in logic. | | `typeRef?` | `string` | English card type in every locale: `"Unit"`, `"Spell"`, `"Landmark"`, `"Equipment"`, `"Ability"` or `"Trap"`. | | `supertypeRef?` | `string` | English supertype in every locale: `"Champion"` on champions, absent otherwise. | | `cost?` | `number` | Mana cost. | | `attack?` | `number` | Power (attack); usually `0` on non-units. | | `health?` | `number` | Health; usually `0` on non-units. | | `description?` | `string` | Rules text with the game client's inline markup (``, `` tags). | | `descriptionRaw?` | `string` | Rules text as plain text, markup removed. | | `levelupDescription?` | `string` | Champion level-up condition, with inline markup. | | `levelupDescriptionRaw?` | `string` | Champion level-up condition as plain text. | | `flavorText?` | `string` | Flavor text. | | `subtypes?` | `string[]` | Unit subtypes in upper case (`["ELITE"]`, `["YETI"]`). | | `artistName?` | `string` | Card artist's name. | ## Globals (`ctx.globals`) The catalog's globals are lookup tables that turn the refs on a card into display names, icons and descriptions: `regionRefs: ["Demacia"]` resolves through `ctx.globals.regions.Demacia`. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them and fall back to the raw ref. ::: | Property | Type | Description | | --- | --- | --- | | `formats?` | `Record` | Formats by `formatRefs` key (`"client_Formats_Standard_name"` → Standard). | | `keywords?` | `Record` | Keywords by `keywordRefs` key (`"QuickStrike"` → Quick Attack), with reminder text. | | `rarities?` | `Record` | Rarities by `rarityRef` key (`"Common"`, `"Rare"`, `"Epic"`, `"Champion"`, `"None"`). | | `regions?` | `Record` | Regions by `regionRefs` key (`"Demacia"`, `"PiltoverZaun"`, `"Runeterra"`). | | `runeterraChampions?` | `Record` | Runeterra champions by card code (`"06RU001"`): the champion refs that can appear in `regionRefs`. | | `sets?` | `Record` | Sets by the card's `setCode` (`"set1"`, `"set7b"`, `"setevent"`). | | `spellSpeeds?` | `Record` | Spell speeds by `spellSpeedRef` key (`"Burst"`, `"Fast"`, `"Slow"`). | | `types?` | `Record` | Card types by English type (`"Unit"`, `"Spell"`, `"Champion"`, `"Follower"`, …). | | `vocabTerms?` | `Record` | Glossary terms by `vocabTerms` key (`"Allegiance"`), with descriptions. | ### Lookup entries Every globals table maps a key to an entry with these fields: | Property | Type | Description | | --- | --- | --- | | `color?` | `string` | Display color: a hex value (`"#10C26E"`) or a CSS variable name (`"--color-Demacia"`). | | `icon?` | `string \| null` | Icon image URL carried by the source data (Riot format and set art); empty or `null` when there is none. The curated keyword, region, rarity and champion glyphs are bundled by the web app and resolved from `metadataRef.key`, not from this field. | | `label` | `string` | Display name in the catalog locale (`"Piltover & Zaun"`). | | `metadataRef?` | `LorCatalogMetadataReference` | Anchor an operator override is matched on. | | `order?` | `number` | Sort position in filters and lists, lowest first. | | `showInFilter?` | `boolean` | Whether the entry is offered as a filter option in the card browser. | ### Keyword and vocab term entries `keywords` and `vocabTerms` entries also have: | Property | Type | Description | | --- | --- | --- | | `description?` | `string` | Reminder text for the keyword, in the catalog locale. | ### Runeterra champion entries `runeterraChampions` entries also have: | Property | Type | Description | | --- | --- | --- | | `cardCode` | `string` | The champion's card code (`"06RU001"` for Bard), also its key in `runeterraChampions`. | ## Example card Garen (`01DE012`), trimmed to one image: ```json { "id": "01DE012", "name": "Garen", "setCode": "set1", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/lor/assets/01DE012-card-8a863d8a21d1029ab31bd8454e9456e89c2de96072d27705e2f11883752034f5.webp" } ], "game": { "associatedCardRefs": ["01DE012T1", "01DE012T2"], "formatRefs": [ "client_Formats_Eternal_name", "client_Formats_Standard_name" ], "keywordRefs": ["Regeneration"], "rarityRef": "Champion", "regionRefs": ["Demacia"], "vocabTerms": ["Strike"], "supertype": "Champion", "supertypeRef": "Champion", "type": "Unit", "typeRef": "Unit", "cost": 5, "attack": 5, "health": 5, "description": "When I'm summoned, give other allies +1|+1 this round.", "descriptionRaw": "When I'm summoned, give other allies +1|+1 this round.", "levelupDescription": "I've struck twice.", "levelupDescriptionRaw": "I've struck twice.", "flavorText": "Training and resilience are the way of a soldier. Even in the face of great peril, we will not falter.", "subtypes": ["ELITE"], "artistName": "SIXMOREVODKA" } } ``` ## Common recipes ::: code-group ```js [Count by type] // Calculator: cards per type, with champions split out. export default function compute(pile, cardsById) { const counts = {}; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const type = game.supertypeRef === "Champion" ? "Champion" : game.typeRef || "Other"; counts[type] = (counts[type] || 0) + pile[ref]; }); return { widgets: [ { kind: "donut", label: "Card types", segments: Object.keys(counts).map((type) => ({ label: type, value: counts[type], })), }, ], }; } ``` ```js [Check a rarity] // Card rule: commons only, plus champions. export default function validateCard(card) { const rarity = card.game && card.game.rarityRef; if (rarity === "Common" || rarity === "Champion") { return true; } return { valid: false, issues: [{ message: card.name + " is not a common." }], }; } ``` ```js [Region with globals] // Card rule: Demacia only. Uses the region's display name when globals exist. export default function validateCard(card, ctx) { const regions = (card.game && card.game.regionRefs) || []; if (regions.indexOf("Demacia") !== -1) { return true; } const globals = ctx && ctx.globals; const region = globals && globals.regions && globals.regions.Demacia ? globals.regions.Demacia.label : "Demacia"; return { valid: false, issues: [{ message: card.name + " is not from " + region + "." }], }; } ``` ```js [Mana curve] // Calculator: copies at each mana cost, 7+ grouped. export default function compute(pile, cardsById) { const buckets = [0, 0, 0, 0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const cost = Math.min(Math.max(game.cost || 0, 0), 7); buckets[cost] += pile[ref]; }); return { widgets: [ { kind: "histogram", label: "Mana curve", buckets: buckets, labels: ["0", "1", "2", "3", "4", "5", "6", "7+"], }, ], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/mtg description: "Every field a script can read on a Magic: The Gathering card and in its game globals." --- # Magic: The Gathering card data Ruleset and calculator scripts get Magic: The Gathering cards as plain objects straight from the card catalog. The data comes from Scryfall and covers paper Magic. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs A Magic card in the catalog is a **card identity**: one playable card with all of its printings (reprints, promos, Secret Lair and The List versions) listed under `printings`. Two ids matter: - The **identity id**, `card.id`: `mtg-` plus a hash, like `mtg-7cc37a2f416de612a410`. - A **printing id**: `-`, like `eld-115` or `clb-781`. A few printings with unusual collector numbers get a longer id, such as `plst-ELD11524d6`. Decks store **printing ids**, so a deck is a map like `{ "eld-115": 2, "clb-781": 2 }`. `cardsById` is keyed by those same printing ids, and each one points to its **identity**. In that example both refs are Bonecrusher Giant, so `cardsById["eld-115"]` and `cardsById["clb-781"]` are the same card and share one `card.id`: - Count copies of "the same card" by `card.id` (or `card.name`), not by ref. The deck above runs 4 Bonecrusher Giant. - To read the printing a ref points to, find it in the list: `card.printings.find((p) => p.id === ref)`. - `ctx.globals.printings[ref]` gives the identity id for any printing id, when globals are available. A card rule gets the identity card itself, so `card.id` is always the identity id, never a printing id. The `game` fields describe the card's **default printing**, the first entry of `printings` (`game.defaultPrintingId`). That matters for the per-printing fields `rarity`, `collectorNumber` and `releasedAt`, and for `card.setCode`. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to Magic lives on `card.game`. Values follow Scryfall: colors are the letters `W` `U` `B` `R` `G`, costs use brace notation (`{2}{W}{W}`), and rarity and legality are lower-case tokens you can compare directly. Watch for three things: - **Colorless means missing.** A colorless card has no `colors` (and a colorless identity has no `colorIdentity`); there is no `C` color. Read them as `game.colors || []`. - **`power`, `toughness`, `loyalty` and `defense` are strings**, as printed (`"4"`, `"*"`, `"1+*"`). Convert with `Number()` and check for `NaN` before doing math. - **Cards with more than one face** (double-faced, split, adventure and flip cards) keep their rules text on `faces`, not on `oracleText`. Double-faced cards also keep their mana cost and colors only on `faces`. Read both when you need a card's text or cost. | Property | Type | Description | | --- | --- | --- | | `manaCost?` | `string` | Mana cost in Scryfall's brace notation (`"{2}{W}{W}"`). Split, adventure and flip cards join their halves' costs with `" // "`; double-faced cards have it only on `faces`. Absent on lands. | | `cmc?` | `number` | Mana value (converted mana cost), such as `4`. `0` for lands. | | `colors?` | `MtgColor[]` | Colors as WUBRG letters (`["W", "U"]`). Absent on colorless cards, and on double-faced cards, whose colors are on `faces`. | | `colorIdentity?` | `MtgColor[]` | Color identity as WUBRG letters: the colors in the cost and rules text, as Commander uses them. Absent when colorless. | | `typeLine?` | `string` | Type line (`"Legendary Creature — Elf Druid"`). A multi-face card joins its faces' lines with `" // "`. | | `oracleText?` | `string` | Rules (Oracle) text. On a multi-face card it is on `faces` instead. | | `englishName?` | `string` | The card's English name, on a card whose `name` is translated (`"Lightning Bolt"` in a catalog that names it `"稲妻"`). Deck lists, imports and English search use it. Absent in English and on untranslated cards. | | `printedTypeLine?` | `string` | Type line as printed in the catalog's language (`"Éphémère"`). Display only: rules, filters and deck checks read the English `typeLine`. Absent in English and on untranslated cards. | | `printedText?` | `string` | Rules text as printed in the catalog's language. Display only: rules read the English `oracleText`. Absent in English and on untranslated cards. | | `flavorText?` | `string` | Flavor text. | | `keywords?` | `string[]` | Keyword abilities and actions, as Scryfall names them (`["Flying", "First strike"]`). | | `rarity?` | `MtgRarity` | Rarity of the default printing: `"common"`, `"uncommon"`, `"rare"`, `"mythic"`, `"special"` or `"bonus"`. | | `power?` | `string` | Power, as printed (`"4"`, `"*"`, `"1+*"`). Convert with `Number()` before doing math. | | `toughness?` | `string` | Toughness, as printed. | | `loyalty?` | `string` | Planeswalker starting loyalty, as printed (`"4"`, `"X"`). | | `defense?` | `string` | Battle starting defense, as printed (`"5"`). | | `legalities?` | `MtgCardLegalities` | Legality per format, keyed by Scryfall format id (`{ modern: "legal", standard: "not_legal" }`), plus Turny's `standard_future` key. Values are `"legal"`, `"not_legal"`, `"restricted"` or `"banned"`. | | `isProvisional?` | `boolean` | True while the card is announced but not yet released: none of its printings has a `released_at` on or before the catalog's generation time. Scryfall marks such a card `not_legal` in every format until release day; `legalities.standard_future` is `legal` meanwhile when it is bound for a Standard set. Absent once any printing has released. | | `faces?` | `MtgCardFaceContract[]` | One entry per face of a double-faced, split, adventure or flip card. Absent on single-faced cards. | | `layout?` | `string` | Scryfall's layout: `"normal"`, `"transform"`, `"modal_dfc"`, `"split"`, `"adventure"`, `"flip"`, `"saga"`, … | | `associatedCardRefs?` | `string[]` | Printing ids of related cards, such as the tokens it makes or its meld partner. | | `collectorNumber?` | `string` | Collector number of the default printing within its set (`"115"`). | | `releasedAt?` | `string` | Release date of the default printing (`"2019-10-04"`). | | `defaultPrintingId?` | `string` | Id of the default printing (`"eld-115"`): the newest regular booster printing, at its lowest rarity. Always the first entry of `printings`; deck rows and card art default to it. | | `oracleId?` | `string` | Scryfall's stable oracle identity id, shared by every printing. | ### Faces Each entry of `faces`: | Property | Type | Description | | --- | --- | --- | | `name` | `string` | This face's name (`"Stomp"`). | | `manaCost?` | `string` | This face's mana cost (`"{1}{R}"`). Absent on a back face that is never cast. | | `typeLine?` | `string` | This face's type line (`"Instant — Adventure"`). | | `oracleText?` | `string` | This face's rules text. | | `printedTypeLine?` | `string` | This face's type line as printed in the catalog's language (`"Créature — humain et chevalier"`). Display only: rules and filters read the English `typeLine`. Absent in English and on untranslated cards. | | `printedText?` | `string` | This face's rules text as printed in the catalog's language. Display only: rules read the English `oracleText`. Absent in English and on untranslated cards. | | `flavorText?` | `string` | This face's flavor text. | | `colors?` | `MtgColor[]` | This face's colors as WUBRG letters, on double-faced cards (Scryfall lists other cards' colors once, at the top). | | `power?` | `string` | This face's power, as printed (`"4"`, `"*"`). | | `toughness?` | `string` | This face's toughness, as printed. | | `loyalty?` | `string` | This face's starting loyalty, as printed. | | `defense?` | `string` | This face's starting defense (a battle face), as printed. | ## Globals (`ctx.globals`) The catalog's globals hold set names and the printing index that maps every printing id to its identity. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them. ::: | Property | Type | Description | | --- | --- | --- | | `printings?` | `Record` | Printing id → owning card identity id, for every printing (`"eld-115"` → `"mtg-7cc37a2f416de612a410"`). Deck refs are printing ids, so this is how a ref finds its card. | | `sets?` | `Record` | Sets by the card's `setCode` (`"eld"` → Throne of Eldraine). | ### Set entries Each entry of `sets`: | Property | Type | Description | | --- | --- | --- | | `label` | `string` | The set's name (`"Throne of Eldraine"`). | | `type?` | `string` | Scryfall's set type: `"core"`, `"expansion"`, `"masters"`, `"commander"`, … | | `releasedAt?` | `string` | The set's release date (`"2019-10-04"`): the earliest `released_at` of its printings. Ranks sets for the daily card puzzle's set column (#1370). | ## Example card Bonecrusher Giant, an adventure card, trimmed to two printings with images and most format legalities left out: ```json { "id": "mtg-7cc37a2f416de612a410", "name": "Bonecrusher Giant // Stomp", "setCode": "eld", "collectible": true, "printings": [ { "id": "eld-115", "setCode": "eld", "number": "115", "releaseDate": "2019-10-04", "metadata": { "scryfallId": "09fd2d9c-1793-4beb-a3fb-7a869f660cd4", "rarity": "rare" } }, { "id": "clb-781", "setCode": "clb", "number": "781", "releaseDate": "2022-06-10", "metadata": { "scryfallId": "b5b71cd2-de35-451f-b16e-2e3936169407", "rarity": "rare" } } ], "hasImage": true, "game": { "manaCost": "{2}{R} // {1}{R}", "cmc": 3, "colors": ["R"], "colorIdentity": ["R"], "typeLine": "Creature — Giant // Instant — Adventure", "flavorText": "Not every tale ends in glory.", "rarity": "rare", "power": "4", "toughness": "3", "legalities": { "standard": "not_legal", "standard_future": "not_legal", "pioneer": "legal", "modern": "legal", "legacy": "legal", "vintage": "legal", "pauper": "not_legal", "commander": "legal" }, "faces": [ { "name": "Bonecrusher Giant", "manaCost": "{2}{R}", "typeLine": "Creature — Giant", "oracleText": "Whenever this creature becomes the target of a spell, this creature deals 2 damage to that spell's controller.", "flavorText": "Not every tale ends in glory.", "power": "4", "toughness": "3" }, { "name": "Stomp", "manaCost": "{1}{R}", "typeLine": "Instant — Adventure", "oracleText": "Damage can't be prevented this turn. Stomp deals 2 damage to any target." } ], "layout": "adventure", "associatedCardRefs": ["teld-20", "eld-291"], "collectorNumber": "115", "releasedAt": "2019-10-04", "oracleId": "d6d72f5f-8f5d-4180-b514-f22ff5482902", "defaultPrintingId": "eld-115" } } ``` ## Common recipes ::: code-group ```js [Count by type] // Calculator: cards per type. Each card counts once, toward the first type // on its type line from this list, so artifact creatures count as creatures. export default function compute(pile, cardsById) { const order = [ "Creature", "Planeswalker", "Battle", "Instant", "Sorcery", "Artifact", "Enchantment", "Land", ]; const counts = {}; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const typeLine = game.typeLine || ""; const type = order.find((name) => typeLine.indexOf(name) !== -1) || "Other"; counts[type] = (counts[type] || 0) + pile[ref]; }); return { widgets: [ { kind: "donut", label: "Card types", segments: Object.keys(counts).map((type) => ({ label: type, value: counts[type], })), }, ], }; } ``` ```js [Mana curve] // Calculator: nonland copies at each mana value, 7+ grouped. export default function compute(pile, cardsById) { const buckets = [0, 0, 0, 0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; if ((game.typeLine || "").indexOf("Land") !== -1) { return; // Lands sit at 0 and would swamp the curve. } const cmc = typeof game.cmc === "number" ? game.cmc : 0; buckets[Math.min(Math.floor(cmc), 7)] += pile[ref]; }); return { widgets: [ { kind: "histogram", label: "Mana curve", buckets: buckets, labels: ["0", "1", "2", "3", "4", "5", "6", "7+"], }, ], }; } ``` ```js [Modern legal] // Card rule: legal in Modern. Restricted, banned and not_legal all fail. export default function validateCard(card) { const legalities = (card.game && card.game.legalities) || {}; if (legalities.modern === "legal") { return true; } return { valid: false, issues: [{ message: card.name + " is not legal in Modern." }], }; } ``` ```js [Color identity] // Card rule: fits a white-blue Commander deck. Colorless cards always fit. export default function validateCard(card) { const identity = (card.game && card.game.colorIdentity) || []; const allowed = ["W", "U"]; const outside = identity.filter((color) => allowed.indexOf(color) === -1); if (outside.length === 0) { return true; } return { valid: false, issues: [ { message: card.name + " has " + outside.join("") + " in its identity." }, ], }; } ``` ```js [Set with globals] // Card rule: only cards whose default printing is from Throne of Eldraine. // Uses the set's name from the globals when they exist. export default function validateCard(card, ctx) { if (card.setCode === "eld") { return true; } const globals = ctx && ctx.globals; const set = globals && globals.sets && globals.sets.eld ? globals.sets.eld.label : "eld"; return { valid: false, issues: [{ message: card.name + " is not from " + set + "." }], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/palworld description: "Every field a script can read on a Palworld TCG card and in its game globals." --- # Palworld TCG card data Ruleset and calculator scripts get Palworld TCG cards as plain objects straight from the card catalog. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs A Palworld TCG card in the catalog is a **card identity**: one playable card with all of its printings (parallel rarities, trial deck and promo reprints) listed under `printings`. Two kinds of id matter: - The **identity id**, `card.id`: `pw-` plus a hash, like `pw-2b062b5618e4f713d60f`. - A **printing id**: the product code and collector number in lowercase, like `ebp01-006`. A parallel adds its rarity: `ebp01-006sr` is the SR parallel. Each printing's printed card number and rarity are in `printing.metadata` (`{ "cardNumber": "EBP01-006", "rarity": "u" }`). Decks store **printing ids**. `cardsById` is keyed by the deck's refs, and each one points to its **identity**, so two printings of the same card in one deck resolve to the same object: - Count copies of "the same card" by `card.id`, not by ref. - To read the printing a ref points to, find it in the list: `card.printings.find((p) => p.id === ref)`. - `ctx.globals.aliases[ref]` gives the identity id for any printing id, when globals are available. A card rule gets the identity card itself, so `card.id` is always the identity id. The `game` fields describe the card's **default printing** (`game.defaultPrintingId`). That matters for per-printing fields such as `rarity`, `setId` and `collectorNumber`; `printingRarities` lists the rarity of every printing. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to Palworld TCG lives on `card.game`. Classification values (`cardType`, `color`, `elements`, `rarity`) are lower-case tokens you can compare directly; look them up in the globals for display names. Souls print no cost or colour, so `cost` and `color` can be `null`. | Property | Type | Description | | --- | --- | --- | | `color` | `PalworldColor \| null` | Cost-background colour; `null` on Souls. | | `cardType` | `PalworldCardType` | Card kind: `"pal"`, `"structure"`, `"gear"`, `"event"` or `"soul"`. | | `subtype` | `PalworldPalSubtype \| null` | Pal subtype (`"normal"` / `"lucky"`); `null` on every non-Pal. | | `isLucky` | `boolean` | True when the card carries the lucky icon. The deck rule's "at most 8 lucky cards" reads this flag rather than the subtype, so a future Gear or Event with the icon can count once the source exposes it. Today the official card list has no separate icon field, so ingest derives the flag from the Lucky Pal subtype. | | `deckCopyLimit` | `number \| PalworldDeckCopyLimit \| null` | The copy limit this card's own text sets for its name, replacing the default `PALWORLD_DEFAULT_DECK_COPY_LIMIT`: a number ("up to 8 cards with the same card name as this card", Swee – Hibernating Together), `PalworldDeckCopyLimit.Unlimited` ("any number of cards", Beegarde), or `null` when the text sets none. Parsed from the rules text at ingest. | | `cost` | `number \| null` | Printed cost (`◇N`); `null` on Souls. | | `power` | `number \| null` | Power for a Pal; durability for a Structure (printed in the same field). `null` on Gear, Events and Souls. | | `strike` | `number \| null` | Strike (source `attack`); Pals only, `null` otherwise. | | `elements` | `PalworldElement[]` | Pal elements (`["dragon", "electric"]`); `[]` on non-Pals. | | `workSuitability` | `PalworldWorkSuitability[]` | Work suitability (`["electricity", "crafting"]`): what a Pal has, or what a Structure needs; `[]` on other cards. | | `traits` | `string[]` | Trait tags the source mixes into the aptitude field (`["Legendary"]`, `["Marcus"]`); `[]` when none. | | `keywords` | `string[]` | Keywords the rules text uses, as `globals.keywords` keys (`["quick", "brave"]`); numeric variants (`[Brave 2]`) collapse to their base id. | | `orientation` | `PalworldCardOrientation` | `"landscape"` for Structures, `"portrait"` otherwise. | | `setId` | `string` | Product code of the default printing's set, with the English `E` prefix (`"EBP02"`); a `globals.sets` key. | | `collectorNumber` | `string` | Collector number within the set, without the set prefix or parallel suffix (`"001"`). | | `variantSuffix` | `string \| null` | Parallel suffix of the default printing (`"OSR"`, `"SSP"`, promo `"S"`); `null` on a base printing. | | `rarity` | `PalworldRarity` | Rarity of the default printing. | | `printingRarities?` | `PalworldRarity[]` | Every printing's rarity, distinct, in ladder order: parallels and promos (OSR, SSP, `S`) sit on non-default printings, and lean list cards carry no `printings`, so the rarity filter and `rarity:` search read this (#2640). Non-render (image ingest ignores it). | | `isProvisional` | `boolean` | True while the card is announced but not yet released: every printing's set has a release date in the future (as of catalog generation). A set with no release date (promos, `PR2026`) counts as RELEASED, so a promo-only card is never provisional (add-game SKILL.md §2 "Unreleased cards": a missing date counts as released). Viewer-independent (ADL §42), so it rides the public card JSON. | | `legalities` | `PalworldCardLegalities` | Legality per card rule id; see `PalworldCardLegalities`. | | `defaultPrintingId` | `string` | Id of the default printing (lower-cased `card_number`, `"ebp01-001"`): the suffix-free printing of the earliest set. Always the first entry of the card's `printings`. | | `text?` | `string` | Rules text with `[Keyword]` markers and `:palworld_:` symbol tokens (`:palworld_act:`, `:palworld_cost_2:`). | | `textPlain?` | `string` | Rules text without markup; `[Keyword]` markers stay and `:palworld_…:` tokens become `{…}`. | | `englishName?` | `string` | The English card name (`"Orserk – Thunderclap Roar"`), the interchange name deck lists carry so a list copied in one locale reads in another. Present on every card of a translated catalog (`ja`), where `name` is localized or falls back to English; absent in the English catalog, where `name` is the English name. | ## Globals (`ctx.globals`) The catalog's globals are lookup tables for the values on a card (`elements: ["fire"]` resolves through `ctx.globals.elements.fire`), the keyword glossary, the rules-text symbols and the printing alias map. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them and fall back to the raw value. ::: | Property | Type | Description | | --- | --- | --- | | `colors?` | `Record` | Colours by `PalworldColor` value. | | `types?` | `Record` | Card kinds by `PalworldCardType` value. | | `elements?` | `Record` | Elements by `PalworldElement` value. | | `workSuitability?` | `Record` | Work suitability by `PalworldWorkSuitability` value. | | `rarities?` | `Record` | Rarities by `PalworldRarity` value. | | `sets?` | `Record` | Products by code (`"EBP02"` → Legends Awaken). | | `formats?` | `Record` | Formats by `PalworldTournamentFormatId` value. | | `keywords?` | `Record` | Keyword glossary by normalized keyword id; only keywords pool cards use. | | `symbols?` | `Record` | Inline symbol-token lexicon (`:palworld_…:`), keyed by token key. | | `aliases?` | `Record` | Printing id → owning card identity id (`"ebp02-001osr"` → `"pw-…"`); identity ids map to themselves. Deck refs may be either. Same name and meaning as Riftbound's `globals.aliases`. | ### Lookup entries Every table except `symbols` and `aliases` maps a key to an entry with these fields: | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Display name (`"Red"`, `"Dawn of Palpagos"`). | | `color?` | `string` | Display color set by an operator override; usually absent. | | `icon?` | `string \| null` | Icon image URL set by an operator override; usually absent. | | `order?` | `number` | Sort position in filters and lists, lowest first. | | `showInFilter?` | `boolean` | Whether the entry is offered as a filter option; absent means shown. | | `metadataRef?` | `PalworldCatalogMetadataReference` | Anchor an operator override is matched on. | ### Set entries Entries of `sets` add: | Property | Type | Description | | --- | --- | --- | | `releaseDate` | `string \| null` | Release date (`YYYY-MM-DD`); `null` when the source gives none (promos). A null date means RELEASED for legality and provisional status, never "unreleased". | | `productType` | `PalworldProductType` | Product kind from the products endpoint. | ### Keyword entries Entries of `keywords` add: | Property | Type | Description | | --- | --- | --- | | `description?` | `string` | Reminder text; may contain `:palworld_…:` symbol tokens. | ### Symbol entries Each entry of `symbols`: | Property | Type | Description | | --- | --- | --- | | `token` | `string` | The full inline token as it appears in rich text (`":palworld_act:"`). | ## Example card Foxparks, Light of Courage, trimmed to two printings with one image each: ```json { "id": "pw-2b062b5618e4f713d60f", "slug": "foxparks-light-of-courage", "name": "Foxparks – Light of Courage", "setCode": "EBP01", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/palworld/assets/pw-2b062b5618e4f713d60f-card-bec1d0aec12ede40ac986126217b21e2ba15f33c6ce2115b091d4f81c9cc1887.webp" } ], "printings": [ { "id": "ebp01-006", "setCode": "EBP01", "number": "006", "releaseDate": "2026-07-30", "variants": [ { "id": "ebp01-006:normal", "kind": "normal" } ], "metadata": { "cardNumber": "EBP01-006", "rarity": "u" } }, { "id": "epr-012", "setCode": "PR2026", "number": "012", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/palworld/assets/epr-012-card-3ced9e1cc51be19e109e289e7616edc96c30500dc1532c8d72a13077bc249101.webp" } ], "variants": [ { "id": "epr-012:normal", "kind": "normal" } ], "metadata": { "cardNumber": "EPR-012", "rarity": "pr" } } ], "hasImage": true, "game": { "color": "red", "cardType": "pal", "subtype": "normal", "isLucky": false, "deckCopyLimit": null, "cost": 2, "power": 200, "strike": 1, "elements": ["fire"], "workSuitability": ["kindling"], "traits": [], "keywords": ["brave"], "orientation": "portrait", "setId": "EBP01", "collectorNumber": "006", "variantSuffix": null, "rarity": "u", "printingRarities": ["u", "sr", "pr"], "isProvisional": false, "legalities": { "standard": "legal", "standard_future": "legal" }, "defaultPrintingId": "ebp01-006", "text": ":palworld_auto:[Brave 300] (:palworld_on_attack:This card gets :palworld_power:+300 until end of turn)", "textPlain": "{auto}[Brave 300] ({on_attack}This card gets {power}+300 until end of turn)" } } ``` ## Common recipes ::: code-group ```js [Cost curve] // Calculator: copies at each cost, 6+ grouped. export default function compute(pile, cardsById) { const buckets = [0, 0, 0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; if (typeof game.cost !== "number") { return; // Souls print no cost. } buckets[Math.min(game.cost, 6)] += pile[ref]; }); return { widgets: [ { kind: "histogram", label: "Cost curve", buckets: buckets, labels: ["0", "1", "2", "3", "4", "5", "6+"], }, ], }; } ``` ```js [Count by element] // Calculator: Pal copies per element. A Pal with two elements counts for both. export default function compute(pile, cardsById) { const counts = {}; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; (game.elements || []).forEach((element) => { counts[element] = (counts[element] || 0) + pile[ref]; }); }); return { widgets: [ { kind: "donut", label: "Elements", segments: Object.keys(counts).map((element) => ({ label: element, value: counts[element], })), }, ], }; } ``` ```js [Standard legal] // Card rule: not banned in Standard. A card with no entry counts as legal. export default function validateCard(card) { const legalities = (card.game && card.game.legalities) || {}; if (legalities.standard !== "banned") { return true; } return { valid: false, issues: [{ message: card.name + " is banned in Standard." }], }; } ``` ```js [Colour with globals] // Card rule: red cards only. Uses the colour's display name when globals exist. export default function validateCard(card, ctx) { const game = card.game || {}; if (game.color === "red") { return true; } const globals = ctx && ctx.globals; const red = globals && globals.colors && globals.colors.red ? globals.colors.red.label : "red"; return { valid: false, issues: [{ message: card.name + " is not a " + red + " card." }], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/pokemon description: "Every field a script can read on a Pokémon TCG card and in its game globals." --- # Pokémon TCG card data Ruleset and calculator scripts get Pokémon TCG cards as plain objects straight from the card catalog. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs A Pokémon card in the catalog is a **card identity**: one playable card with all of its printings (reprints, alternate arts, promos) listed under `printings`. Two ids matter: - The **identity id**, `card.id`: a name slug plus a hash, like `pikachu-ex--1f29b66b68bc`. - A **printing id**: `-`, like `sv2-11` or `svp-106`. Decks store **printing ids**, so a deck is a map like `{ "me2pt5-276": 2, "svp-106": 2 }`. `cardsById` is keyed by those same printing ids, and each one points to its **identity**. In that example both refs are Pikachu ex, so `cardsById["me2pt5-276"]` and `cardsById["svp-106"]` are the same card and share one `card.id`: - Count copies of "the same card" by `card.id` (or `card.name`), not by ref. The deck above runs 4 Pikachu ex. - To read the printing a ref points to, find it in the list: `card.printings.find((p) => p.id === ref)`. - `ctx.globals.printings[ref]` gives the identity id for any printing id, when globals are available. A card rule gets the identity card itself, so `card.id` is always the identity id, never a printing id. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to the Pokémon TCG lives on `card.game`. The type tokens (`supertype`, `subtypes`, `types`, Energy costs, weakness types) are English in every language, so they are safe to compare. Names and text follow the viewer's language. Watch for two things: - `supertype` is `"Pokemon"`, without the accent. Compare against both spellings if in doubt. - `hp`, `damage` and `level` are strings, as printed (`"60+"`). Convert with `Number()` before doing math. | Property | Type | Description | | --- | --- | --- | | `associatedCardRefs?` | `string[]` | Reserved for related-card ids; not emitted by the catalog today. | | `abilities?` | `PokemonAbilityPayload[]` | Abilities, in printed order. | | `artist?` | `string` | Illustrator of the default printing. | | `attacks?` | `PokemonAttackPayload[]` | Attacks, in printed order. | | `clientName?` | `string` | Pokémon TCG Live display name when it differs from the printed name. | | `convertedRetreatCost?` | `number` | Number of Energy in the retreat cost (length of `retreatCost`). | | `defaultPrintingId?` | `string` | Printing id of the identity's representative (default art) printing. | | `digitalOnly?` | `boolean` | True when every printing exists only in Pokémon TCG Live. | | `evolvesFrom?` | `string` | Printed "Evolves from" name (`"Pikachu"`). | | `evolvesFromIds?` | `string[]` | Catalog ids of the identities this card evolves from. | | `evolvesTo?` | `string[]` | Printed "Evolves to" names. | | `evolvesToIds?` | `string[]` | Catalog ids of the identities this card evolves into. | | `flavorText?` | `string` | Flavor text, markup removed. | | `hp?` | `string` | Printed HP as a string (`"120"`); convert with `Number()` before comparing. | | `identityAliases?` | `string[]` | Older identity ids that now point to this card (ids it had before its Western release), so saved refs to them keep working. | | `inMarket?` | `boolean` | False when the card has no printing in this language's market (for example a Japan-only card in the English catalog). Absent means in-market. | | `isProvisional?` | `boolean` | True while the card is an unofficial pre-release entry, read off an official reveal before card data is published. Cleared when the official data lands. | | `isLiveAvailable?` | `boolean` | True when at least one printing is playable in Pokémon TCG Live. | | `legalities?` | `JsonObject` | Format key (`standard`, `expanded`, `unlimited`, `standard-jp`, `expanded-jp`, `standard-future`) to `"Legal"`, `"Illegal"` or `"Banned"`. Compare case-insensitively. | | `level?` | `string` | Printed level on older cards (`"45"`). | | `liveCardId?` | `string` | Pokémon TCG Live card id. | | `nationalPokedexNumbers?` | `number[]` | National Pokédex numbers of the Pokémon on the card (`[25]`); several for tag teams. | | `number` | `string` | Collector number of the default printing (`"276"`); the set is the card's `setCode`. | | `rarity?` | `string` | Rarity of the default printing as printed (`"Rare"`, `"Special Illustration Rare"`). | | `regulationMark?` | `string` | Regulation mark letter (`"G"`, `"H"`), which drives Standard rotation. | | `resistances?` | `PokemonResistancePayload[]` | Resistances, usually zero or one. | | `retreatCost?` | `string[]` | Energy type per retreat-cost Energy (`["Colorless", "Colorless"]`). | | `rules?` | `string[]` | Rule-box lines (Pokémon ex / V / Tera rules, Trainer rules). | | `subtypes?` | `string[]` | Stage and kind tokens (`["Basic", "ex"]`, `["Stage 1"]`, `["Item"]`, `["Supporter"]`). | | `supertype` | `string` | `"Pokemon"` (unaccented), `"Trainer"` or `"Energy"`. | | `types?` | `string[]` | Energy types of a Pokémon (`["Psychic"]`); absent on Trainers and Energy. | | `weaknesses?` | `PokemonWeaknessPayload[]` | Weaknesses, usually zero or one. | ### Abilities Each entry of `abilities`: | Property | Type | Description | | --- | --- | --- | | `name` | `string` | Ability name (`"Quick Search"`). | | `text` | `string` | Effect text. | | `type` | `string` | `"Ability"`, `"Poké-Power"`, `"Poké-Body"` etc., as printed. | ### Attacks Each entry of `attacks`: | Property | Type | Description | | --- | --- | --- | | `convertedEnergyCost?` | `number` | Number of Energy the attack needs (length of `cost`). | | `cost?` | `string[]` | Energy type per required Energy (`["Lightning", "Colorless"]`). | | `damage?` | `string` | Printed damage as text (`"30"`, `"60+"`, `"×"`); absent when the attack does no printed damage. | | `name` | `string` | Attack name. | | `text?` | `string` | Effect text. | ### Weaknesses Each entry of `weaknesses`: | Property | Type | Description | | --- | --- | --- | | `type` | `string` | Energy type the Pokémon is weak to (`"Fighting"`). | | `value` | `string` | Printed modifier (`"×2"`, `"+20"`). | ### Resistances Each entry of `resistances`: | Property | Type | Description | | --- | --- | --- | | `type` | `string` | Energy type the Pokémon resists (`"Metal"`). | | `value` | `string` | Printed modifier (`"-30"`). | ## Globals (`ctx.globals`) The catalog's globals hold set details and the printing index that maps every printing id to its identity. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them. ::: | Property | Type | Description | | --- | --- | --- | | `printings?` | `Record` | Printing id → owning card identity id, covering every emitted printing. | | `sets?` | `Record` | Sets by set code (`"sv2"`, `"me2pt5"`). | ### Set entries Each entry of `sets`: | Property | Type | Description | | --- | --- | --- | | `images?` | `PokemonSetImagesPayload` | Set logo and symbol image URLs. | | `label` | `string` | Set name in the catalog locale (`"Paldea Evolved"`). | | `printedTotal?` | `number` | Card count printed on the cards (the `/193` in `001/193`). | | `ptcgoCode?` | `string` | PTCGO/PTCG Live set abbreviation (e.g. "PAL") used in text deck lists. | | `releaseDate?` | `string` | Release date as `YYYY/MM/DD`. | | `series?` | `string` | Series (`"Scarlet & Violet"`). | | `total?` | `number` | Total cards in the set, secret rares included. | ### Set images A set entry's `images`: | Property | Type | Description | | --- | --- | --- | | `logo?` | `string` | Set logo image URL. | | `symbol?` | `string` | Set symbol image URL. | ## Example card Pikachu ex, trimmed to two printings, one image each and two identity aliases: ```json { "id": "pikachu-ex--1f29b66b68bc", "name": "Pikachu ex", "setCode": "me2pt5", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/pokemon/assets/me2pt5-276-en-card-685c27781bd507cac386d4a882d063dedea2430e20472857fe1881360eae4777.webp" } ], "printings": [ { "id": "me2pt5-276", "setCode": "me2pt5", "number": "276", "releaseDate": "2026/01/30", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/pokemon/assets/me2pt5-276-en-card-685c27781bd507cac386d4a882d063dedea2430e20472857fe1881360eae4777.webp" } ], "variants": [], "metadata": { "rarity": "Special Illustration Rare", "regulationMark": "H", "artist": "booota" } }, { "id": "svp-106", "setCode": "svp", "number": "106", "releaseDate": "2023/01/01", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/pokemon/assets/svp-106-en-card-6834a96f03cf2394d164d4c948035eddc63428fcfd0c08d201e14064fe9b21dd.webp" } ], "variants": [], "metadata": { "rarity": "Promo", "regulationMark": "H", "artist": "takuyoa" } } ], "game": { "supertype": "Pokemon", "subtypes": ["Basic", "ex"], "hp": "200", "types": ["Lightning"], "rules": [ "Pokémon ex rule: When your Pokémon ex is Knocked Out, your opponent takes 2 Prize cards." ], "attacks": [ { "name": "Thunderbolt", "cost": ["Lightning", "Lightning", "Colorless"], "convertedEnergyCost": 3, "damage": "120" } ], "weaknesses": [{ "type": "Fighting", "value": "×2" }], "retreatCost": ["Colorless"], "convertedRetreatCost": 1, "number": "276", "nationalPokedexNumbers": [25], "rarity": "Special Illustration Rare", "regulationMark": "H", "artist": "booota", "legalities": { "expanded": "Legal", "expanded-jp": "Legal", "standard": "Legal", "standard-future": "Legal", "standard-jp": "Legal", "unlimited": "Legal" }, "identityAliases": ["pikachu-ex--1f4e7709a44c", "pikachu-ex--3f6f59171eb0"], "defaultPrintingId": "me2pt5-276" } } ``` ## Common recipes ::: code-group ```js [Count by supertype] // Calculator: Pokémon, Trainer and Energy counts. export default function compute(pile, cardsById) { const counts = { Pokémon: 0, Trainer: 0, Energy: 0 }; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const supertype = game.supertype === "Pokemon" ? "Pokémon" : game.supertype; if (counts[supertype] !== undefined) { counts[supertype] += pile[ref]; } }); return { widgets: [ { kind: "donut", label: "Supertypes", segments: Object.keys(counts).map((name) => ({ label: name, value: counts[name], })), }, ], }; } ``` ```js [Standard legal] // Card rule: legal in Standard. Legality text is compared case-insensitively. export default function validateCard(card) { const legalities = (card.game && card.game.legalities) || {}; const standard = String(legalities.standard || "").toLowerCase(); if (standard === "legal") { return true; } return { valid: false, issues: [{ message: card.name + " is not legal in Standard." }], }; } ``` ```js [Check a rarity] // Card rule: no Special Illustration Rares or Hyper Rares. export default function validateCard(card) { const rarity = (card.game && card.game.rarity) || ""; if (rarity !== "Special Illustration Rare" && rarity !== "Hyper Rare") { return true; } return { valid: false, issues: [{ message: card.name + " is a " + rarity + "." }], }; } ``` ```js [Copies across printings] // Calculator: copies per card identity, so reprints count together. export default function compute(pile, cardsById) { const copies = {}; const names = {}; Object.keys(pile).forEach((ref) => { const card = cardsById[ref]; const id = card ? card.id : ref; copies[id] = (copies[id] || 0) + pile[ref]; names[id] = card ? card.name : ref; }); return { widgets: [ { kind: "table", label: "Copies", columns: ["Card", "Copies"], rows: Object.keys(copies).map((id) => [names[id], copies[id]]), }, ], }; } ``` ```js [Average HP] // Calculator: average HP of the Pokémon in the deck. export default function compute(pile, cardsById) { let total = 0; let count = 0; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const hp = Number(game.hp); if (hp > 0) { total += hp * pile[ref]; count += pile[ref]; } }); return { widgets: [ { kind: "stat", label: "Average HP", value: count > 0 ? Math.round(total / count) : 0, }, ], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/riftbound description: "Every field a script can read on a Riftbound card and in its game globals." --- # Riftbound card data Ruleset and calculator scripts get Riftbound cards as plain objects straight from the card catalog. This page lists every field on those objects and in the catalog globals, with a real example and a few recipes. Where the cards show up: - **Card rules** receive one card as their first argument. - **Deck and deck set rules** receive `cardsById`, an object keyed by card ref that holds every card in the deck (it can hold more). - **Calculators** receive `cardsById` as their second argument. See the [ruleset script API](https://docs.turny.gg/reference/scripting/rulesets) and the [calculator script API](https://docs.turny.gg/reference/scripting/calculators) for the full function signatures. ## Card keys and deck refs A Riftbound card in the catalog is a **card identity**: one playable card with all of its printings (showcase, signature and alternate-art prints, reprints in later sets) listed under `printings`. Two kinds of id matter: - The **identity id**, `card.id`: `rb-` plus a hash, like `rb-34ece2975dc9e4adcb5e`. - A **printing id**: set, collector number and set size, like `ogn-030-298`. Treatments add a suffix: `ogn-030a-298` is the alternate art. Promo printings (sets `OPP`, `PR` and `JDG`) carry their TCGplayer product id in `printing.metadata.tcgplayerId`. Other printings have no `metadata`. Decks store **printing ids** (decks saved before printing refs existed may still use identity ids). `cardsById` is keyed by the deck's refs, and each one points to its **identity**, so two printings of the same card in one deck resolve to the same object: - Count copies of "the same card" by `card.id`, not by ref. - To read the printing a ref points to, find it in the list: `card.printings.find((p) => p.id === ref)`. - `ctx.globals.aliases[ref]` gives the identity id for any printing or variant id, when globals are available. A card rule gets the identity card itself, so `card.id` is always the identity id. The `game` fields describe the card's **default printing**, the first entry of `printings` (`game.defaultPrintingId`). That matters for per-printing fields such as `rarity`, `variant` and `artistName`. Guard against a missing card before reading from it: `cardsById[ref]` can be `undefined` when the catalog doesn't know a ref. ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to Riftbound lives on `card.game`. Riftbound is English only, so classification values (`type`, `rarity`, `domains`) are lower-case tokens you can compare directly; look them up in the globals for display names. | Property | Type | Description | | --- | --- | --- | | `type?` | `RiftboundCardType` | Card type: `"unit"`, `"spell"`, `"gear"`, `"battlefield"`, `"rune"` or `"legend"`. Champions are units with `supertype: "Champion"`. | | `supertype?` | `string` | Printed supertype when there is one: `"Champion"`, `"Signature"`, `"Basic"`, `"Token"`. | | `rarity?` | `RiftboundRarity` | Rarity of the default printing: `"common"`, `"uncommon"`, `"rare"`, `"epic"`, `"showcase"`, … | | `domains?` | `RiftboundDomain[]` | Domains (colors): `["fury"]`, `["calm", "mind"]`. A card with no domain carries `["colorless"]`; a Neutral card (goes in a deck of any domain) carries `["neutral"]`. | | `tags?` | `string[]` | Printed tags such as champion names and factions (`["Jinx", "Zaun"]`). | | `englishName?` | `string` | The English display name (`"Lee Sin - Blind Monk"`), the interchange name deck lists carry: Piltover Archive and event tools read English names in every locale. Present on every card of a translated catalog (`zh-cn`, `ko`), where `name` is localized or falls back to English; absent in the English catalog, where `name` is the English name. | | `energy?` | `number` | Energy cost. | | `might?` | `number` | Might (combat strength); units only. | | `power?` | `number` | Power cost: the domain-rune part of the cost, paid on top of energy. | | `collectorNumber?` | `string` | Collector number of the default printing within its set, without leading zeros (`"30"`). | | `defaultPrintingId?` | `string` | Id of the default printing (`"ogn-030-298"`): the first regular printing, from the earliest set, with the `normal` treatment. Always the first entry of `printings`. | | `legalities?` | `RiftboundCardLegalities` | Legality per format (`{ standard: "legal" }`, `"banned"`, or `"not_legal"` while `isProvisional`). A missing format counts as legal. | | `isProvisional?` | `boolean` | True while the card is announced but not yet released: none of its printings is in a set whose release date has passed (as of catalog generation). Such a card is `not_legal` in Standard and legal in the Standard (Future) ruleset. Absent once any printing's set has released, or when the set carries no release date. Same name and meaning as Pokémon's `isProvisional`, so the Standard (Future) rule script reads both games the same way. Viewer-independent (ADL §42), so it rides the public card JSON. | | `cardSideboard?` | `RiftboundCardSideboardRules` | Present only on a card that lets the deck designate extra cards beside it (Neeko, Blending In: `{ maxCards: 3, cardType: "legend" }`). The deck keeps the picks in its `cardSideboards` under this card's ref; they are not deck cards. Rules read `maxCards` (the most picks allowed) and `cardType` (the type every pick must have). | | `text?` | `string` | Rules text as HTML, with `[Keyword]` markers and `:rb_…:` symbol tokens. | | `textPlain?` | `string` | Rules text without HTML tags; `[Keyword]` markers stay and `:rb_…:` tokens become `{…}` (`{energy_1}`). | | `flavorText?` | `string` | Flavor text. | | `keywordRefs?` | `string[]` | Keywords in the rules text, as `globals.keywords` keys (`["accelerate", "assault"]`); `[Assault 2]` becomes `"assault"`. | | `orientation?` | `RiftboundCardOrientation` | `"portrait"`, or `"landscape"` for battlefields. | | `variant?` | `string` | Treatment of the default printing: `"normal"`, `"foil"`, `"showcase"`, `"ultimate"`, `"alternate_art"` or `"signature"`. | | `foil?` | `boolean` | True when the default printing is foil. | | `alternateArt?` | `boolean` | True when the default printing is an alternate-art print. | | `signature?` | `boolean` | True when the default printing is a signature print. | | `artistName?` | `string` | Artist of the default printing. | ## Globals (`ctx.globals`) The catalog's globals are lookup tables for the values on a card (`domains: ["fury"]` resolves through `ctx.globals.domains.fury`), the keyword glossary, the rules-text symbols and the printing alias map. ::: warning When globals are available Globals are passed to ruleset scripts as `ctx.globals` (the last argument). Calculators may not receive `ctx` at all, and a ruleset can run without it too. Always check `ctx && ctx.globals` before using them and fall back to the raw value. ::: | Property | Type | Description | | --- | --- | --- | | `domains?` | `Record` | Domains by `domains` value (`"fury"` → Fury). | | `rarities?` | `Record` | Rarities by `rarity` value (`"epic"` → Epic). | | `types?` | `Record` | Card types by `type` value (`"unit"` → Unit). | | `sets?` | `Record` | Sets by the card's `setCode` (`"OGN"` → Origins). | | `formats?` | `Record` | Formats by `legalities` key (`"standard"`). | | `keywords?` | `Record` | Keyword glossary, keyed by normalized keyword id; filtered to keywords the ingested catalog actually references. | | `symbols?` | `Record` | Inline symbol-token lexicon (`:rb_...:`), keyed by token key. | | `aliases?` | `Record` | Printing or variant id → owning card identity id (`"ogn-030-298"` → `"rb-34ece2975dc9e4adcb5e"`); identity ids map to themselves. Deck refs may be either. | ### Lookup entries `domains`, `rarities`, `types`, `sets`, `formats` and `keywords` map a key to an entry with these fields: | Property | Type | Description | | --- | --- | --- | | `label` | `string` | Display name (`"Fury"`, `"Origins"`). | | `color?` | `string` | Display color set by an operator override; usually absent. | | `icon?` | `string \| null` | Icon image URL set by an operator override; usually absent. | | `order?` | `number` | Sort position in filters and lists, lowest first. | | `showInFilter?` | `boolean` | Whether the entry is offered as a filter option; absent means shown. | | `metadataRef?` | `RiftboundCatalogMetadataReference` | Anchor an operator override is matched on. | ### Keyword entries `keywords` entries also have: | Property | Type | Description | | --- | --- | --- | | `description?` | `string` | Reminder text; may contain `:rb_…:` symbol tokens. | ### Symbol entries Each entry of `symbols`: | Property | Type | Description | | --- | --- | --- | | `token` | `string` | The full inline token as it appears in rich text, e.g. `":rb_energy_1:"`. | ## Example card Jinx, Demolitionist, trimmed to two printings with one image each: ```json { "id": "rb-34ece2975dc9e4adcb5e", "name": "Jinx - Demolitionist", "setCode": "OGN", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/riftbound/assets/rb-34ece2975dc9e4adcb5e-card-80a26a1b25235660a480721f141f212244485ad006bbd2602247425901e8b11e.webp" } ], "printings": [ { "id": "ogn-030-298", "setCode": "OGN", "number": "30", "releaseDate": "2025-10-31", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/riftbound/assets/rb-34ece2975dc9e4adcb5e-card-80a26a1b25235660a480721f141f212244485ad006bbd2602247425901e8b11e.webp" } ], "variants": [{ "id": "ogn-030-298:normal", "kind": "normal" }] }, { "id": "ogn-030a-298", "setCode": "OGN", "number": "30", "releaseDate": "2025-10-31", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/riftbound/assets/ogn-030a-298-card-03360e2876cef6388860f6cd8445bd352c6a95eea244e015019869cd5d693365.webp" } ], "variants": [ { "id": "ogn-030a-298:alternate_art", "kind": "alternate_art" } ] } ], "hasImage": true, "game": { "type": "unit", "supertype": "Champion", "rarity": "rare", "domains": ["fury"], "tags": ["Jinx", "Zaun"], "energy": 3, "might": 4, "power": 1, "collectorNumber": "30", "defaultPrintingId": "ogn-030-298", "legalities": { "standard": "legal" }, "text": "

[Accelerate] (You may pay :rb_energy_1::rb_rune_fury: as an additional cost to have me enter ready.)
[Assault 2] (+2 :rb_might: while I'm an attacker.)
When you play me, discard 2.

", "textPlain": "[Accelerate] (You may pay {energy_1}{rune_fury} as an additional cost to have me enter ready.)[Assault 2] (+2 {might} while I'm an attacker.)When you play me, discard 2.", "keywordRefs": ["accelerate", "assault"], "orientation": "portrait", "variant": "normal", "artistName": "Kudos Productions" } } ``` ## Common recipes ::: code-group ```js [Count by type] // Calculator: cards per type, with champions split out. export default function compute(pile, cardsById) { const counts = {}; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; const type = game.supertype === "Champion" ? "champion" : game.type || "other"; counts[type] = (counts[type] || 0) + pile[ref]; }); return { widgets: [ { kind: "donut", label: "Card types", segments: Object.keys(counts).map((type) => ({ label: type, value: counts[type], })), }, ], }; } ``` ```js [Energy curve] // Calculator: main-deck copies at each energy cost, 7+ grouped. export default function compute(pile, cardsById) { const buckets = [0, 0, 0, 0, 0, 0, 0, 0]; Object.keys(pile).forEach((ref) => { const game = (cardsById[ref] && cardsById[ref].game) || {}; if (typeof game.energy !== "number") { return; // Legends, runes and battlefields have no energy cost. } buckets[Math.min(game.energy, 7)] += pile[ref]; }); return { widgets: [ { kind: "histogram", label: "Energy curve", buckets: buckets, labels: ["0", "1", "2", "3", "4", "5", "6", "7+"], }, ], }; } ``` ```js [Check a rarity] // Card rule: commons and uncommons only. Legends, runes and battlefields pass. export default function validateCard(card) { const game = card.game || {}; const exempt = ["legend", "rune", "battlefield"]; if (exempt.indexOf(game.type) !== -1) { return true; } if (game.rarity === "common" || game.rarity === "uncommon") { return true; } return { valid: false, issues: [{ message: card.name + " is " + game.rarity + "." }], }; } ``` ```js [Standard legal] // Card rule: not banned in Standard. A card with no entry counts as legal. export default function validateCard(card) { const legalities = (card.game && card.game.legalities) || {}; if (legalities.standard !== "banned") { return true; } return { valid: false, issues: [{ message: card.name + " is banned in Standard." }], }; } ``` ```js [Domain with globals] // Card rule: Fury cards only. Uses the domain's display name when globals exist. export default function validateCard(card, ctx) { const domains = (card.game && card.game.domains) || []; if (domains.indexOf("fury") !== -1) { return true; } const globals = ctx && ctx.globals; const fury = globals && globals.domains && globals.domains.fury ? globals.domains.fury.label : "fury"; return { valid: false, issues: [{ message: card.name + " is not a " + fury + " card." }], }; } ``` ::: --- url: https://docs.turny.gg/reference/card-data/tft description: "Every field on a Teamfight Tactics champion in the card catalog and in its globals, plus the team code formats." --- # Teamfight Tactics card data The Teamfight Tactics catalog holds one card per champion of a set. This page lists every field on those champion objects and in the catalog globals, with a real example, and explains the two team codes. TFT does not run scripts yet: there are no TFT calculators or team rules. The fields below are the same ones other games pass to their scripts, so they are also what a future TFT script will read. ## Card keys A TFT card is one champion **in one set**. The same champion in another set is a different card with its own cost, traits and ability, so Ahri from Set 16 and Ahri from Set 18 have different ids. - The **card id**, `card.id`: `tft-` plus a hash, like `tft-e1515e1ff433a3ee708c`. - The **printing id**: the set, then the source character id, like `tftset18-da-18-morgana`. A champion has exactly one printing. `card.setCode` is the set mutator (`TFTSet18`), and `game.setNumber` is the bare number (`18`). ## Card fields Every card, in every game, has these top-level fields: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Catalog id of the card identity (`"01DE012"` in LoR, `"pikachu-ex--1f29b66b68bc"` in Pokémon). | | `slug?` | `string` | The card's public URL segment (#2189, ADL §64): a frozen English slug, identical in every locale. Equals `id` for a game whose readable slugs are off (`readableCardSlugsEnabled` in `@turny/game-adapters`) or a card that has no readable slug yet. Pokémon keeps its `--` id as its slug; LoR's switch stays off for good, so its URLs stay its card codes. A page whose route param already equals `slug` renders; any other known key (the id, a history slug, an alias) redirects to it, so a card whose slug equals its id never redirects to itself.

The catalog export (#2193) writes it only for a switched-on game and only when it differs from `id`, so an absent slug means the id: always read it through `cardSlugOf` (`@turny/game-adapters`). | | `name` | `string` | Display name in the catalog locale. | | `setCode` | `string` | Set of the card, or of its default printing (`"set1"`, `"sv2"`, `"OGN"`). | | `collectible?` | `boolean` | False for cards that can't go in a deck (LoR tokens and level-ups). | | `assets?` | `CardCatalogCardAssetContract[]` | Images of the card's default printing. | | `printings?` | `CardPrintingContract[]` | Every printing of the identity, default printing first (only some on a partial card, see `partialPrintings`). Absent in LoR. | | `printingCount?` | `number` | Lean list files (#1323), which omit `printings`, partial cards (see `partialPrintings`) and per-identity core files (#1522): how many printings the full card has. Absent on full cards and in games without printings. | | `printingSetCodes?` | `string[]` | Lean list files (#1323), partial cards and per-identity core files: the distinct set codes across the full card's printings, in printing order. Absent on full cards. | | `printingsFile?` | `string` | Per-identity core files (#1522) only: the card's printings file (`identities/.printings..json`, relative to the locale directory, see `cardCatalogIdentityPrintingsFileName`), in place of `printings`. Absent when the printings are inline in the core file. | | `partialPrintings?` | `boolean` | True on a partial card (the featured-cards bundle, #1330): `printings` holds only some of the identity's printings (its default printing plus the ones the featured content references), while `printingCount` / `printingSetCodes` summarize all of them. Absent on full and list cards. | | `hasImage?` | `boolean` | False when none of the card's printings has an image in this language. Absent means it has one. | | `languages?` | `CardLanguageEntry[]` | Catalog locales that hold real text for this card (#2552). A locale whose entry is only fallback text is absent. Absent on older exports and in single-locale games. | | `game?` | `TGameData` | Game-specific fields; see the per-game `*CardGameData` type. | Each entry of `languages` (`CardLanguageEntry`): | Property | Type | Description | | --- | --- | --- | | `locale` | `string` | Catalog locale (`"zh-tw"`, `"de_de"`), not an app locale. | | `status` | `CardLanguageStatus` | Where the text comes from: `official` (printed) or `unofficial` (a translation). | Values of a language entry's `status` (`CardLanguageStatus`): | Member | Value | Description | | --- | --- | --- | | `Official` | `"official"` | Printed in this language by the publisher. | | `Unofficial` | `"unofficial"` | Real text the publisher did not print in this language: a reconstruction or a translation. | ### Printings Each entry of `printings` (`CardPrintingContract`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Printing id; deck refs use it (`"sv2-11"` for Pokémon, `"ogn-030-298"` for Riftbound). | | `setCode` | `string` | Set the printing belongs to (`"sv2"`, `"OGN"`). | | `number?` | `string` | Collector number within the set. | | `language?` | `string` | Language of the printing, when it is not the catalog's own. | | `releaseDate?` | `string` | Release date as the source gives it (`"2023/06/09"`). | | `assets?` | `CardCatalogCardAssetContract[]` | This printing's own images. | | `variants?` | `CardVariantContract[]` | Treatments of this printing (foil, alternate art, …). | | `metadata?` | `JsonObject` | Extra per-printing data (rarity, artist, store ids); game-specific. | Each entry of a printing's `variants`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Variant id, usually `:` (`"ogn-030-298:normal"`). | | `kind?` | `string` | Treatment kind (`"normal"`, `"foil"`, `"alternate_art"`); values are per game. | | `label?` | `string` | Display label, when the kind alone is not enough. | | `metadata?` | `JsonObject` | Extra per-variant data; game-specific. | Each entry of `assets` (on the card and on each printing): | Property | Type | Description | | --- | --- | --- | | `kind` | `CardAssetKind` | What the image shows: `"card"` (framed render), `"full"` (full art), `"icon"`, `"banner"`, `"slice"`, `"portrait"`, … | | `url` | `string` | Image URL. | | `format?` | `CardAssetFormat` | Image format (`"webp"`), when known. | | `width?` | `number` | Width in pixels, when known. | | `height?` | `number` | Height in pixels, when known. | | `metadata?` | `JsonObject` | Extra per-asset data; game-specific. | ## Game fields (`card.game`) Everything specific to TFT lives on `card.game`: the shop cost, the traits, the ability, the 1-star combat stats and the Team Planner id. A few champions pick an origin in game (Set 18 Lux chooses one of nine). The catalog keeps one card for the champion and lists each choice under `variants`, with its own traits. All the variants share the base card's planner id, so a team code still round-trips. | Property | Type | Description | | --- | --- | --- | | `characterId` | `string` | Source character id (`"DA_Cinderling18"`), stable within a set; the identity key input. | | `setNumber` | `number` | Set number (`18`). | | `setMutator` | `string` | Set mutator the card comes from (`"TFTSet18"`). | | `cost` | `number` | Shop cost, 1 to 5 (a few special units cost more). | | `traits` | `TftTraitRefContract[]` | Traits in printed order. | | `plannerCode?` | `number` | The client's 12-bit Team Planner id (`1015` → `"3f7"` in a team code), when the set has a planner roster. Absent on sets without one (every set before 17) and on non-roster units. | | `role?` | `string` | Source role hint (`"ADTank"`, `"APCaster"`). When the source has no role, ingest derives `"Tank"` for a melee unit (range 1) that starts combat with at least 20 mana; any other unit without a source role has none. | | `ability?` | `TftChampionAbilityContract` | The champion's ability. | | `stats?` | `TftChampionStatsContract` | Combat stats at 1 star. | | `variants?` | `TftChampionVariantContract[]` | Origin variants sharing this card's planner id (see `TftChampionVariantContract`). | | `legalities?` | `TftCardLegalities` | Legality per format (`{ standard: "legal" }`; a rotated set is `"not_legal"`). | | `defaultPrintingId?` | `string` | Id of the default (only) printing. | ### Traits Each entry of `traits` (and of a variant's `traits`): | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Trait api name, the key into `globals.traits`. | | `name` | `string` | Trait display name in the catalog locale. | | `breakpoints?` | `number[]` | The trait's breakpoints (`minUnits` of each tier, ascending), baked onto the champion so code without the globals (the archetype selector) can tell which traits a board activates. | ### Ability The `ability` object: | Property | Type | Description | | --- | --- | --- | | `name` | `string` | Ability name in the catalog locale. | | `descriptionHtml?` | `string` | Ability text as HTML. | | `descriptionPlain?` | `string` | Ability text without markup. | ### Stats The `stats` object, at 1 star: | Property | Type | Description | | --- | --- | --- | | `hp?` | `number` | Health. | | `damage?` | `number` | Attack damage. | | `armor?` | `number` | Armor. | | `magicResist?` | `number` | Magic resist. | | `attackSpeed?` | `number` | Attacks per second. | | `range?` | `number` | Attack range in hexes. | | `mana?` | `number` | Mana needed to cast the ability. | | `initialMana?` | `number` | Mana the champion starts combat with. | ### Origin variants Each entry of `variants`: | Property | Type | Description | | --- | --- | --- | | `characterId` | `string` | Source character id of the variant (`"DA_18_Lux_Coven"`). | | `name` | `string` | Variant display name in the catalog locale. | | `traits` | `TftTraitRefContract[]` | The variant's traits, in printed order. | ## Globals (`ctx.globals`) The catalog's globals are lookup tables for the values on a champion: the sets, the full trait entries with their breakpoints, the items, the formats, the printing alias map and the live set's planner ids. | Property | Type | Description | | --- | --- | --- | | `sets?` | `Record` | Sets by mutator (`"TFTSet18"`). | | `traits?` | `Record` | Traits by api name, only those a catalog champion references. | | `formats?` | `Record` | Formats by `legalities` key (`"standard"`). | | `aliases?` | `Record` | Printing id → card identity id; identity ids map to themselves. | | `plannerCodes?` | `Record` | Live set's planner id → card identity id, for team-code import. | | `items?` | `Record` | Items by api name (`"TFT_Item_InfinityEdge"`), the names Riot boards and team codes carry. | ### Set entries Each entry of `sets`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | The set mutator (`"TFTSet18"`), also the card's `setCode`. | | `name` | `string` | Set display name in the catalog locale. | | `number` | `number` | Set number (`18`). | | `isLive` | `boolean` | True for the set the live client plays. | | `hasPlannerCodes` | `boolean` | True when the client's Team Planner carries ids for this set (team codes work). | ### Trait entries Each entry of `traits`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Trait api name (`"DA_18_Coven"`). | | `name` | `string` | Trait display name in the catalog locale. | | `slug?` | `string` | Readable URL key from the English name and set (`coven-set-18`), the same in every locale. Absent on catalogs exported before the field existed. | | `descriptionHtml?` | `string` | Trait text as HTML, with `@Var@` placeholders resolved where the source gives values. | | `descriptionPlain?` | `string` | Trait text without markup. | | `breakpoints` | `TftTraitBreakpointContract[]` | Breakpoints in ascending `minUnits` order. | | `setMutator` | `string` | Set mutator the trait belongs to. | | `icon?` | `string` | Trait icon (PNG URL), absent when the source has none. | | `unitTeamSlots?` | `number` | Team slots a champion with this (unique) trait takes up; absent means 1. | | `traitCountBonuses?` | `Record` | Extra trait count a champion with this trait adds, by trait id (Apex Predator: Riftbeast +2). | ### Trait breakpoints Each entry of a trait's `breakpoints`: | Property | Type | Description | | --- | --- | --- | | `minUnits` | `number` | Fewest units with the trait that reach this breakpoint. | | `maxUnits?` | `number` | Most units this breakpoint covers; the top breakpoint uses a large sentinel (`25000`). | | `style?` | `number` | Source style tier: 1 bronze, 3 silver, 4 unique, 5 gold, 6 prismatic. | | `teamSizeBonus?` | `number` | Extra max team size while this breakpoint is the reached one (Riftbeast 10: 2). | ### Item entries Each entry of `items`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Api name, stable within a set (`"TFT_Item_InfinityEdge"`, `"DA_18_EmblemCoven"`). | | `name` | `string` | Item display name in the catalog locale. | | `slug?` | `string` | Readable URL key from the English name (`infinity-edge`), the same in every locale and shared by the copies one item keeps under two api names. Absent on catalogs exported before the field existed. | | `kind` | `TftItemKind` | What the item is: component, completed item, emblem and so on. | | `icon?` | `string` | Item icon (PNG URL). | | `composition?` | `string[]` | The two component api names a completed item or emblem is built from. | | `descriptionHtml?` | `string` | Item text as HTML. | | `descriptionPlain?` | `string` | Item text without markup. | | `grantsTraitId?` | `string` | Trait id an emblem grants its holder. | | `teamSizeBonus?` | `number` | Extra max team size the item gives while held (the Tactician's items: 1). | | `setMutators?` | `string[]` | Set mutators whose item list references this api name, newest set first. Absent on catalogs exported before the field existed. | ### Format entries Each entry of `formats`: | Property | Type | Description | | --- | --- | --- | | `id` | `string` | Format id, the key into a card's `legalities` (`"standard"`). | | `name` | `string` | Format display name. | ## Team codes A TFT team is a board of distinct champions, at most one per hex (28). Turny reads and writes two codes for it. ### Turny team code (`TFT1`) The canonical code. It lists each champion by the hash of its card id, sorted, and can add a unit segment for any unit with stars, items or a hex: ```text TFT1.tft:[,…][.u:[,…]] unit = [@]~[][~…] ``` - `@` is the hex: row `0` (front) to `3` (back), then column `0` to `6`. - `` is `1` to `4`, or empty when unknown. - Items are api names (`DA_AdaptiveHelm`), up to three, in the order the unit holds them. Units with nothing to add are left out of the unit segment, so a champions-only team is just the champion list. Morgana, Elise and Camille from Set 18, with a 2-star Morgana holding Adaptive Helm on the back-left hex: ```text TFT1.tft:229ca46967cb818f9cec,e1515e1ff433a3ee708c,e3d8b6d025323d452c43.u:e1515e1ff433a3ee708c@30~2~DA_AdaptiveHelm ``` ### Team Planner code The code the TFT client's Team Planner shares. It holds up to ten champions and nothing else: no stars, items or hexes. ```text 02 TFTSet ``` Each slot is a champion's `game.plannerCode` in hex, and `000` marks an empty slot. The same three champions: ```text 024183fd3f5000000000000000000000TFTSet18 ``` The team builder accepts either code on import. A Team Planner code maps back to cards through `globals.plannerCodes` (keyed by the planner id in decimal), so it only works for a set that has planner ids (`hasPlannerCodes` on the set entry; every set before 17 has none) and only for the set it names. Copying a Team Planner code drops stars, items and hexes, and a team of more than ten champions only copies as a `TFT1` code. ## Example card Morgana from Set 18, trimmed to one image: ```json { "id": "tft-e1515e1ff433a3ee708c", "slug": "morgana-set-18", "name": "Morgana", "setCode": "TFTSet18", "collectible": true, "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/tft/assets/tft-e1515e1ff433a3ee708c-card-4648d2f98916641f192d53148b2e67bb24479b87ba70d538fcc49d38f3490e9f.webp" } ], "printings": [ { "id": "tftset18-da-18-morgana", "setCode": "TFTSet18", "assets": [ { "kind": "card", "url": "https://cdn.turny.gg/cards/tft/assets/tft-e1515e1ff433a3ee708c-card-4648d2f98916641f192d53148b2e67bb24479b87ba70d538fcc49d38f3490e9f.webp" } ], "metadata": { "characterId": "DA_18_Morgana" } } ], "hasImage": true, "game": { "characterId": "DA_18_Morgana", "setNumber": 18, "setMutator": "TFTSet18", "cost": 4, "traits": [ { "id": "DA_18_Coven", "name": "Coven", "breakpoints": [3, 4, 5, 7] }, { "id": "DA_18_Invoker", "name": "Invoker", "breakpoints": [2, 3, 4, 5] } ], "plannerCode": 1048, "ability": { "name": "Withering Curse", "descriptionHtml": "Passive: Gain [Omnivamp] Omnivamp.

Active: Fire a dark blast at [NumEnemiesCursed] nearby enemies, …", "descriptionPlain": "Passive: Gain [Omnivamp] Omnivamp.\n\nActive: Fire a dark blast at [NumEnemiesCursed] nearby enemies, …" }, "stats": { "hp": 1100, "damage": 45, "armor": 60, "magicResist": 60, "attackSpeed": 0.75, "range": 2, "mana": 65, "initialMana": 0 }, "legalities": { "standard": "legal" }, "defaultPrintingId": "tftset18-da-18-morgana" } } ``` Ability text keeps the source's bracketed placeholders, such as `[MagicDamageCalc1]`, where the game fills in a number that scales with star level. --- url: https://docs.turny.gg/reference/search/cyberpunk description: "Card search syntax for Cyberpunk TCG: every field, is: shortcut and operator, with example queries." --- # Cyberpunk TCG card search The search box on the [Cyberpunk TCG Cards page](https://cyberpunk.turny.gg/cards) and in the [deck builder](https://cyberpunk.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "red units that cost 2 or less" in one line: `t:unit c:red cost<=2`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name, subtitle included. Unquoted text is typo-tolerant. | Any text | | `text` | `o`, `oracle` | Text | Rules text. | Any text | | `type` | `t` | Value | Card type: legend, unit, gear or program. | `legend`, `unit`, `gear`, `program` | | `color` | `c` | Value | Card colour, which is also its RAM colour: red, blue, green or yellow. | `red`, `blue`, `green`, `yellow` | | `cost` | `mv`, `cmc` | Number | Eddie cost. Legends printed without one have none. | A number | | `ram` | | Number | RAM value, in the card's colour. | A number | | `power` | `pow` | Number | Power. Programs print none. | A number | | `rarity` | `r` | Value | Rarity of any printing (a Nova Rare or Iconic alternate's too). Comparisons use the order of the allowed values. | `common`, `uncommon`, `rare`, `epic`, `secret`, `nova_rare`, `iconic_legend`, `iconic_other`, `iconic_secret` | | `set` | `e` | Value | A set the card is printed in, by short code, such as `wnc`. | Values come from the card catalog. | | `keyword` | `kw` | Value | Keyword, in lowercase, such as `blocker` or `go-solo`. | `play`, `attack`, `call`, `defeated`, `spend`, `blocker`, `quick`, `go-solo`, `adrenaline` | | `tag` | | Value | A classification printed on the card, such as `Merc`. | Values come from the card catalog. | | `format` | `f`, `legal` | Value | A format the card is legal in (`standard` or `sealed`). | `standard`, `sealed` | `c` is short for colour, not cost: write `cost` (or `mv`) for the Eddie cost. Keywords are written in lowercase with `-` in place of spaces, such as `kw:go-solo`. A rarity matches any printing, so `r:nova_rare` finds a card whose Nova Rare is an alternate art. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:sellable` | Cards with the sell tag (can be sold for 1 Eddie). | | `is:unreleased` | Announced cards that are not out yet. | | `is:maindeck` | Cards that go in the main deck (leaves out Legends). | ## Examples | Query | Finds | | --- | --- | | `t:unit c:red cost<=2` | Red units that cost 2 Eddies or less. | | `t:legend c:blue` | Blue legends. | | `kw:blocker power>=4` | Blockers with 4 Power or more. | | `kw:go-solo` | Cards with Go Solo. | | `o:draw t:program` | Programs whose text mentions "draw". | | `tag:arasaka` | Cards classified Arasaka. | | `is:sellable t:gear` | Gear you can sell for an Eddie. | | `ram>=3` | Cards with a RAM value of 3 or more. | | `t:program -kw:quick` | Programs without Quick. | | `r:iconic` | Cards with an Iconic printing. | | `johny` | Johnny Silverhand, despite the typo. | --- url: https://docs.turny.gg/reference/search/fab description: "Card search syntax for Flesh and Blood: every field, is: shortcut and operator, with example queries." --- # Flesh and Blood card search The search box on the [Flesh and Blood Cards page](https://fab.turny.gg/cards) and in the [deck builder](https://fab.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "red Guardian attacks" in one line: `cl:guardian t:attack p:1`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name. Unquoted text is typo-tolerant. | Any text | | `text` | `x` | Text | Rules text. | Any text | | `type` | `t` | Value | Card type, such as `action`, `attack`, `hero`, `weapon` or `defense_reaction`. | `hero`, `demi_hero`, `weapon`, `equipment`, `action`, `attack`, `attack_reaction`, `defense_reaction`, `instant`, `resource`, `block`, `mentor`, `token`, `aura`, `item`, `ally`, `companion`, `event`, `macro` | | `subtype` | `st` | Text | Subtype from the type line, such as `aura`, `item`, `arrow` or `2h`. | Any text | | `class` | `cl` | Value | Class, such as `guardian` or `ninja`. Generic cards match `generic`. | `adjudicator`, `assassin`, `bard`, `brute`, `guardian`, `illusionist`, `mechanologist`, `merchant`, `necromancer`, `ninja`, `pirate`, `ranger`, `runeblade`, `shapeshifter`, `thief`, `warrior`, `wizard`, `generic` | | `talent` | | Value | Talent, such as `light` or `draconic`. | `chaos`, `draconic`, `earth`, `elemental`, `ice`, `light`, `lightning`, `mystic`, `revered`, `reviled`, `royal`, `shadow` | | `pitch` | `p` | Number | Pitch value: `1` (red), `2` (yellow) or `3` (blue). | A number | | `color` | `colour` | Value | Colour bar: `red`, `yellow` or `blue`. | `red`, `yellow`, `blue` | | `rarity` | `r` | Value | Rarity of the card's main printing. | `common`, `rare`, `super_rare`, `majestic`, `legendary`, `fabled`, `token`, `basic`, `marvel`, `promo` | | `set` | `e` | Value | Set code, such as `WTR` or `MST`. | Values come from the card catalog. | | `cost` | `c` | Number | Resource cost. | A number | | `power` | `pow`, `attack` | Number | Attack power. | A number | | `defense` | `d`, `def` | Number | Defense value. | A number | | `intellect` | `i` | Number | A hero's intellect (cards drawn up to). | A number | | `life` | `h`, `health` | Number | Life: a hero's starting life, or an ally's. | A number | | `keyword` | `kw` | Text | A keyword on the card, such as `Go again` or `Dominate`. | Any text | | `format` | `f`, `legal` | Value | A format the card is legal in: `cc`, `blitz`, `ll` or `silver_age`. | `cc`, `blitz`, `ll`, `silver_age` | `c` is short for cost and `x` searches the rules text. Pitch is a number (`p:1` is red, `p:3` is blue); `colour` takes the colour name instead. Types written with spaces use `_`, such as `t:defense_reaction`, and a keyword with a space needs quotes: `kw:"go again"`. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:hero` | Heroes, adult and young. | | `is:young` | Young heroes (Blitz and Silver Age). | | `is:unreleased` | Announced cards that are not out yet. | | `is:collectible` | Cards you can put in a deck (leaves out tokens). | ## Examples | Query | Finds | | --- | --- | | `cl:guardian t:attack p:1` | Red Guardian attacks. | | `is:hero cl:ninja` | Ninja heroes. | | `kw:"go again" power>=6` | Go again cards with 6 power or more. | | `t:defense_reaction d>=4` | Defense reactions with 4 defense or more. | | `talent:draconic t:action` | Draconic actions. | | `st:arrow` | Arrows. | | `e:MST r:legendary` | Legendary cards from Part the Mistveil (`MST`). | | `f:silver_age is:hero` | Heroes legal in Silver Age. | | `x:arcane cl:wizard c<=1` | Wizard cards that cost 1 or less and mention "arcane". | | `dorintea` | Dorinthea, despite the typo. | --- url: https://docs.turny.gg/reference/search/hs description: "Card search syntax for Hearthstone: every field, is: shortcut and operator, with example queries." --- # Hearthstone card search The search box on the [Hearthstone Cards page](https://hs.turny.gg/cards) and in the [deck builder](https://hs.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "Standard Mage spells that cost 2 or less" in one line: `c:mage t:spell cost<=2 is:standard`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name. Unquoted text is typo-tolerant. | Any text | | `text` | `o`, `oracle` | Text | Rules text. | Any text | | `type` | `t` | Value | Card type: minion, spell, weapon, hero or location. | `minion`, `spell`, `weapon`, `hero`, `location` | | `rarity` | `r` | Value | Rarity. Comparisons use the order free, common, rare, epic, legendary. | `free`, `common`, `rare`, `epic`, `legendary` | | `set` | `e`, `s` | Value | Set code, such as `CORE` or `TITANS`. A card matches every set it was printed in. | Values come from the card catalog. | | `cost` | `mana`, `mv`, `cmc` | Number | Mana cost. | A number | | `class` | `c` | Value | Class, such as `mage` or `deathknight`. A dual-class card matches both classes; a card with no class is `neutral`. | `deathknight`, `demonhunter`, `druid`, `hunter`, `mage`, `paladin`, `priest`, `rogue`, `shaman`, `warlock`, `warrior`, `neutral` | | `attack` | `atk` | Number | Attack. | A number | | `health` | `hp` | Number | Health of a minion, location or hero. | A number | | `durability` | `dur` | Number | A weapon's durability. | A number | | `armor` | | Number | Armor a hero card gives. | A number | | `keyword` | `kw` | Value | Keyword the card has or its text mentions, with `_` for spaces, such as `taunt` or `divine_shield`. | Values come from the card catalog. | | `race` | `tribe`, `miniontype` | Value | Minion type, such as `dragon` or `mechanical`. An Amalgam counts as every type. | `beast`, `demon`, `draenei`, `dragon`, `elemental`, `mechanical`, `murloc`, `naga`, `pirate`, `quilboar`, `totem`, `undead`, `all` | | `school` | `spellschool` | Value | Spell school, such as `fire` or `shadow`. | `arcane`, `fel`, `fire`, `frost`, `holy`, `nature`, `shadow` | | `format` | `f`, `legal` | Value | A format the card is legal in: `standard` or `wild`. | `standard`, `wild` | | `rune` | `runes` | Symbols | Death Knight rune cost: `B` Blood, `F` Frost, `U` Unholy. `rune:BB` needs at least two Blood runes; `rune<=BBU` fits a deck with those runes; a number compares the total. | A number, or symbols | `c` is short for class, not cost: write `cost` (or `mana`) for the mana cost. Keywords use `_` in place of spaces, such as `kw:divine_shield`. ## Rune symbols With symbols, `rune:` matches any one cost on the card that contains at least the listed mix. | Symbol | Meaning | | --- | --- | | `B` | Blood | | `F` | Frost | | `U` | Unholy | ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:neutral` | Neutral cards, which any class can play. | | `is:multiclass` | Cards shared by two or more classes. | | `is:legendary` | Legendary cards. | | `is:minion` | Minions. | | `is:spell` | Spells. | | `is:weapon` | Weapons. | | `is:hero` | Hero cards. | | `is:location` | Locations. | | `is:standard` | Cards legal in Standard. | | `is:wild` | Cards legal in Wild. | | `is:unreleased` | Announced cards that are not out yet. | | `is:tourist` | Tourists, which let another class's cards into your deck. | ## Examples | Query | Finds | | --- | --- | | `c:mage t:spell cost<=2 is:standard` | Standard Mage spells that cost 2 or less. | | `kw:taunt atk>=5 is:minion` | Taunt minions with 5 Attack or more. | | `race:dragon is:legendary` | Legendary Dragons. | | `school:fire` | Fire spells. | | `rune:BB` | Death Knight cards that need at least two Blood runes. | | `is:neutral kw:divine_shield is:standard` | Standard neutral cards with Divine Shield. | | `o:"draw a card" c:priest` | Priest cards whose text says "draw a card". | | `t:weapon dur>=3` | Weapons with 3 Durability or more. | | `is:tourist` | Tourists. | | `e:CORE r:epic` | Epic cards from the Core set. | --- url: https://docs.turny.gg/reference/search/lor description: "Card search syntax for Legends of Runeterra: every field, is: shortcut and operator, with example queries." --- # Legends of Runeterra card search The search box on the [Legends of Runeterra Cards page](https://lor.turny.gg/cards) and in the [deck builder](https://lor.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "Demacia units that cost 2 or less" in one line: `t:unit cost<=2 region:demacia`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name. Unquoted text is typo-tolerant. | Any text | | `text` | `o`, `oracle` | Text | Rules text, including a champion's level-up text. | Any text | | `type` | `t` | Value | Card type: Unit, Spell, Landmark, Ability, Equipment and so on. | `Unit`, `Spell`, `Landmark`, `Ability`, `Equipment` | | `rarity` | `r` | Value | Rarity. Comparisons use the order Common, Rare, Epic, Champion. | `Common`, `Rare`, `Epic`, `Champion` | | `set` | `e` | Value | Set code, such as `set1` or `set6cde`. | Values come from the card catalog. | | `cost` | `mv`, `cmc` | Number | Mana cost. | A number | | `region` | `c`, `color` | Value | Region, such as `Demacia` or `ShadowIsles`. | `Demacia`, `Freljord`, `Ionia`, `Noxus`, `PiltoverZaun`, `ShadowIsles`, `Bilgewater`, `Shurima`, `Targon`, `BandleCity`, `Runeterra` | | `keyword` | `kw` | Value | Keyword, written as one word with no spaces, such as `QuickStrike` or `LastBreath`. | Values come from the card catalog. | | `supertype` | | Value | Supertype. `Champion` is the only one in use. | `Champion` | | `format` | `f`, `legal` | Value | A format the card is legal in: `standard` or `eternal`. | `standard`, `eternal` | Regions and keywords use their English names written as one word, the same in every language: `region:piltoverzaun`, `region:shadowisles`, `kw:quickstrike`. Because `:` means contains, `region:shadow` is enough. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:champion` | Champion units (not their spells or abilities). | | `is:landmark` | Landmarks. | | `is:unit` | Units, champions included. | | `is:spell` | Spells. | | `is:equipment` | Equipment. | | `is:collectible` | Cards you can put in a deck (leaves out tokens, abilities and level-ups). | | `is:runeterra` | Cards whose region is Runeterra. | ## Examples | Query | Finds | | --- | --- | | `t:unit cost<=2 region:demacia` | Demacia units that cost 2 or less. | | `is:champion (region:freljord or region:ionia)` | Freljord or Ionia champions. | | `kw:elusive -is:champion` | Elusive units that are not champions. | | `t:spell o:"draw 1"` | Spells whose text says "draw 1". | | `r>=epic e:set1` | Epic and Champion rarity cards from the first set. | | `jnx` | Jinx, despite the typo. | | `n:!vi` | Only the card named exactly Vi. | | `kw:strike` | Quick Attack and Double Attack cards (`QuickStrike`, `DoubleStrike`). | | `is:landmark region:shurima` | Shurima landmarks. | | `region:bandle t:spell` | Bandle City spells. | --- url: https://docs.turny.gg/reference/search/mtg description: "Card search syntax for Magic: The Gathering: every field, is: shortcut and operator, colors and mana costs as symbols, and example queries." --- # Magic: The Gathering card search The search box on the [Magic: The Gathering Cards page](https://mtg.turny.gg/cards) and in the [deck builder](https://mtg.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "green creatures with mana value 2 or less" in one line: `t:creature c:g mv<=2`. Players who know Scryfall will recognize most of it, but only the fields and shortcuts on this page work. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name. Unquoted text is typo-tolerant. | Any text | | `type` | `t` | Text | Type line, supertypes and subtypes included: `t:legendary`, `t:elf`. Every face of a multi-face card counts. | Any text | | `text` | `o`, `oracle` | Text | Rules text, on every face of the card. | Any text | | `rarity` | `r` | Value | Rarity of the card's default printing. Comparisons use the order of the allowed values. | `common`, `uncommon`, `rare`, `mythic`, `special`, `bonus` | | `set` | `e`, `s` | Value | Set code of the card's default printing, such as `dmu` or `mh3`. A reprinted card matches only that one set. `e:dmu` also matches codes that contain `dmu`; `e:!dmu` matches the set exactly. | Values come from the card catalog. | | `color` | `c` | Symbols | Colors, as the letters `W` `U` `B` `R` `G`: `c:wu` is at least white and blue, `c=r` is exactly red. A colorless card never matches; use `is:colorless`. | Symbols | | `identity` | `id` | Symbols | Color identity (the colors in the cost and rules text), as letters, compared like `color`. A colorless card never matches. | Symbols | | `mana` | `m` | Symbols | Mana cost symbols, such as `m:{2}{W}{W}`. Generic mana and hybrid, Phyrexian or colorless symbols need braces: `m:{3}`, `m:{W/U}`, `m:{C}`. | Symbols | | `mv` | `cmc`, `manavalue` | Number | Mana value (converted mana cost). Lands and other cards with no mana cost have 0. | A number | | `power` | `pow` | Number | Power. A value such as `*` is not a number and never matches. | A number | | `toughness` | `tou` | Number | Toughness. A value such as `*` is not a number and never matches. | A number | | `loyalty` | `loy` | Number | Starting loyalty of a planeswalker. A value such as `X` is not a number and never matches. | A number | | `keyword` | `kw` | Value | Keyword ability, such as `flying`, `ward` or `"first strike"`. | Values come from the card catalog. | | `format` | `f`, `legal` | Value | A format the card is legal in, such as `standard` or `modern`. A card restricted to one copy counts as legal. `standard_future` is Standard plus announced cards bound for a Standard set. | `standard`, `pioneer`, `modern`, `legacy`, `vintage`, `pauper`, `commander`, `standard_future` | `t:` searches the whole type line as text, so `t:legendary`, `t:creature` and `t:elf` all work, and `t:"legendary creature"` needs the words in that order. Keywords use Scryfall's names; quote the ones with a space, such as `kw:"first strike"`. A card in the catalog stands for every printing of it, but `set` and `rarity` read only its **default printing** (`game.defaultPrintingId` in the [card data](https://docs.turny.gg/reference/card-data/mtg)). A card reprinted in many sets is found under one of them. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:split` | Split cards, such as Fire // Ice. | | `is:legendary` | Legendary cards: Legendary on the type line of any face. | | `is:colorless` | Cards with no colors. | | `is:multicolored`, `is:multicolor` | Cards with two or more colors. | | `is:land` | Lands: Land on the type line of any face, so a spell with a land back face counts. | | `is:creature` | Creatures: Creature on the type line of any face, so artifact creatures and adventure creatures count. | | `is:dfc` | Cards with more than one face: double-faced cards, and also split, adventure and flip cards. | | `is:unreleased` | Announced cards that are not out yet. | | `is:collectible` | Cards you can put in a deck (leaves out tokens). | ## Colors and mana cost `c` (color), `id` (color identity) and `m` (mana cost) compare **symbols** rather than text or numbers. ### Colors Colors are the letters **W** (white), **U** (blue), **B** (black), **R** (red) and **G** (green), in any order and either case. Full color names don't work: `c:white` finds nothing. | You type | It finds cards whose colors are | | -------- | ------------------------------------------------------- | | `c:wu` | At least white and blue: white-blue, Esper, five-color. | | `c>=wu` | The same as `c:wu`. | | `c=wu` | Exactly white and blue. | | `c<=wu` | Only white, only blue, or white and blue. | | `cwu` | White, blue and at least one more color. | | `c!=wu` | Anything except exactly white and blue. | Colorless cards have no colors, so they never match `c` or `id`, not even `c<=wu` or `c!=wu`. Find them with `is:colorless`, and add them to a color search with `or`: `(c<=wu or is:colorless)`. `id` works the same way on a card's color identity, the colors in its cost and rules text. `id<=wu` lists the cards a white-blue Commander deck can run, apart from those with a colorless identity. A double-faced card's colors are the colors of both faces together. ### Mana cost `m` matches the symbols in a card's mana cost, written as on the card. Colored mana can be plain letters, and everything else goes in braces: | Symbol | Write it | | ---------------- | ----------------------------------------- | | One colored mana | `W`, `U`, `B`, `R`, `G` (or `{W}`) | | Generic mana | The whole number in braces: `{2}`, `{10}` | | Variable mana | `X`, or `{X}` | | Hybrid | `{W/U}`, `{2/W}` | | Phyrexian | `{W/P}` | | Colorless mana | `{C}` (a plain `C` works too) | Some details: - **Generic mana is one symbol, not a count.** `{2}` matches a cost with `{2}` in it, not one with `{3}`, and `{1}{1}` is not the same as `{2}`. To search by total cost, use `mv`. - **A digit outside braces is a count.** `m:2W` means two white mana, the same as `m:WW`, not "two generic and one white". - **A plain number never matches.** `m:3` finds nothing; write `mv=3` for mana value 3, or `m:{3}` for a cost with `{3}` in it. The comparison operators compare the mix of symbols: | You type | It finds a mana cost that is | | -------------- | ------------------------------------------------------------- | | `m:{2}{W}{W}` | At least `{2}{W}{W}`, possibly with more symbols. | | `m>={2}{W}{W}` | The same as `m:`. | | `m={2}{W}{W}` | Exactly `{2}{W}{W}`. | | `m<={2}{W}{W}` | Made only of symbols from the list: `{W}`, `{2}{W}` and more. | | `m!={2}{W}{W}` | Anything except exactly `{2}{W}{W}`. | A card with more than one face matches when its full cost or any one face's cost fits. A split card's full cost is both halves together: Fire // Ice is `{1}{R}{1}{U}`. ## Examples | Query | Finds | | --- | --- | | `t:creature c:g mv<=2` | Green creatures with mana value 2 or less. | | `c=r t:instant` | Mono-red instants. | | `c:wu` | Cards that are at least white and blue, including three-color ones. | | `is:legendary t:creature id=wub` | Legendary creatures with exactly a white, blue and black color identity. | | `m=UU` | Cards that cost exactly two blue mana, like Counterspell. | | `m:{X}` | Cards with X in their mana cost. | | `m:{W/U}` | Cards with a white-blue hybrid symbol in their cost. | | `kw:flying pow>=4` | Flyers with 4 power or more. | | `t:instant o:"draw a card"` | Instants whose text says "draw a card". | | `r:mythic e:!mh3` | Mythic rares whose default printing is in Modern Horizons 3. | | `is:colorless t:artifact mv<=2` | Colorless artifacts with mana value 2 or less. | | `bonecrushr` | Bonecrusher Giant, despite the typo. | --- url: https://docs.turny.gg/reference/search/palworld description: "Card search syntax for Palworld TCG: every field, is: shortcut and operator, with example queries." --- # Palworld TCG card search The search box on the [Palworld TCG Cards page](https://palworld.turny.gg/cards) and in the [deck builder](https://palworld.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "red Pals that cost 2 or less" in one line: `t:pal c:red cost<=2`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name. Unquoted text is typo-tolerant. | Any text | | `text` | `o`, `oracle` | Text | Rules text. | Any text | | `type` | `t` | Value | Card type: pal, structure, gear, event or soul. | `pal`, `structure`, `gear`, `event`, `soul` | | `color` | `c` | Value | Card colour: red, blue, green, purple or colorless. | `red`, `blue`, `green`, `purple`, `colorless` | | `rarity` | `r` | Value | Rarity of any printing (a parallel's too). Comparisons use the order of the allowed values. | `c`, `u`, `r`, `rr`, `td`, `tdr`, `sr`, `tsr`, `osr`, `sp`, `tsp`, `ssp`, `sss`, `pr` | | `set` | `e` | Value | A set the card is printed in, such as `EBP01` or `ETD02`. | Values come from the card catalog. | | `cost` | `mv`, `cmc` | Number | Printed cost. | A number | | `power` | `pow` | Number | A Pal's Power, or a Structure's durability. | A number | | `strike` | `str` | Number | A Pal's Strike. | A number | | `element` | `el` | Value | A Pal's element. A Pal with two elements matches both. | `neutral`, `fire`, `water`, `grass`, `electric`, `ground`, `ice`, `dark`, `dragon` | | `work` | `w` | Value | Work suitability, such as `kindling` or `transporting`. | `harvesting`, `crafting`, `collecting`, `transporting`, `kindling`, `cooling`, `farming`, `electricity` | | `trait` | | Value | Trait tags, such as `Legendary`. | Values come from the card catalog. | | `keyword` | `kw` | Value | Keyword, in lowercase, such as `quick` or `brave`. | Values come from the card catalog. | | `format` | `f`, `legal` | Value | A format the card is legal in (`standard`). | `standard` | `c` is short for colour, not cost: write `cost` (or `mv`) for the printed cost. Power is printed in hundreds, so compare it that way: `power>=500`. A rarity matches any printing, so `r:sr` finds a card whose SR is a parallel. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:lucky` | Cards with the lucky icon (a deck holds at most 8). | | `is:unreleased` | Announced cards that are not out yet. | | `is:collectible` | Cards with a printing you can collect (Souls included). | | `is:maindeck` | Cards that go in the 50-card main deck (leaves out Souls). | ## Examples | Query | Finds | | --- | --- | | `t:pal c:red cost<=2` | Red Pals that cost 2 or less. | | `el:fire strike>=2` | Fire Pals with 2 Strike or more. | | `w:kindling` | Cards with Kindling work suitability. | | `is:lucky` | Lucky Pals. | | `kw:taunt power>=400` | Cards with Taunt and 400 Power or more. | | `t:event c:blue` | Blue events. | | `o:"draw"` | Cards whose text mentions "draw". | | `r>=sr e:EBP01` | SR or rarer cards from Dawn of Palpagos (`EBP01`). | | `trait:legendary` | Cards with the Legendary trait. | | `chilet` | Chillet, despite the typo. | --- url: https://docs.turny.gg/reference/search/pokemon description: "Card search syntax for the Pokémon TCG: every field, is: shortcut and operator, attack costs with energy symbols, and example queries." --- # Pokémon TCG card search The search box on the [Pokémon TCG Cards page](https://pokemon.turny.gg/cards) and in the [deck builder](https://pokemon.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "Water Pokémon with 120 HP or more" in one line: `t:water hp>=120`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name. Unquoted text is typo-tolerant. | Any text | | `text` | `o`, `oracle` | Text | Rules text, plus the names and text of abilities and attacks. | Any text | | `type` | `t` | Value | A Pokémon's energy type. Trainers have none. | `Grass`, `Fire`, `Water`, `Lightning`, `Psychic`, `Fighting`, `Darkness`, `Metal`, `Fairy`, `Dragon`, `Colorless` | | `rarity` | `r` | Value | Printed rarity. Comparisons use the order of the allowed values; any other rarity never matches a comparison. | `Common`, `Uncommon`, `Rare`, `Double Rare`, `Ultra Rare`, `Illustration Rare`, `Special Illustration Rare`, `Hyper Rare` | | `set` | `e` | Value | Set code, such as `sv1` or `sm11`. | Values come from the card catalog. | | `cost` | `attackcost`, `energy`, `mv`, `cmc` | Symbols | Attack cost. A number compares the total energy of the card's cheapest attack; energy symbols match the exact typed cost of any one attack. | A number, or symbols | | `hp` | | Number | Hit points. | A number | | `damage` | `dmg` | Number | Highest printed base damage among the card's attacks. A `+` or `×` after the number is ignored. | A number | | `stage` | | Value | Evolution stage. `final` matches Pokémon that do not evolve any further, on pages that load the whole card pool. | `Basic`, `Stage 1`, `Stage 2`, `Final` | | `retreat` | | Number | Retreat cost, as a number of energy. | A number | | `weakness` | `weak` | Value | The energy type the card is weak to. | `Grass`, `Fire`, `Water`, `Lightning`, `Psychic`, `Fighting`, `Darkness`, `Metal`, `Fairy`, `Dragon`, `Colorless` | | `regmark` | `reg` | Value | Regulation mark letter. Comparisons use the order of the allowed values. | `A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`, `W`, `X`, `Y`, `Z` | | `subtype` | | Text | Any subtype, ignoring case: `Supporter`, `Item`, `Stadium`, `Pokémon Tool`, `ex`, `V` and so on. | Any text | | `format` | `f`, `legal` | Value | A format the card is legal in: `standard`, `expanded`, `unlimited`, the Japan-schedule `standard-jp` and `expanded-jp`, or `standard-future` (Standard plus cards that rotate in next). | `standard`, `expanded`, `unlimited`, `standard-jp`, `expanded-jp`, `standard-future` | `t:` is a Pokémon's energy type, not its card type. To find Trainers by kind, search the subtype: `subtype:supporter`, `subtype:item`, `subtype:stadium`, `subtype:"pokémon tool"`. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:ex` | Pokémon ex (the modern, lowercase mechanic). | | `is:v` | Pokémon V. | | `is:vmax` | Pokémon VMAX. | | `is:vstar` | Pokémon VSTAR. | | `is:v-union` | Pokémon V-UNION. | | `is:gx` | Pokémon-GX. | | `is:EX` | Pokémon-EX (the older, uppercase mechanic). Type it in capitals: `is:ex` finds the modern mechanic. | | `is:break` | Pokémon BREAK. | | `is:radiant` | Radiant Pokémon. | | `is:"prism star"` | Prism Star cards. | | `is:"ace spec"` | ACE SPEC cards. | | `is:mega` | Mega Evolution Pokémon. | | `is:tera` | Tera Pokémon. | | `is:ancient` | Ancient cards. | | `is:future` | Future cards. | | `is:"fusion strike"` | Fusion Strike cards. | | `is:"single strike"` | Single Strike cards. | | `is:"rapid strike"` | Rapid Strike cards. | | `is:"tag team"` | TAG TEAM cards. | | `is:"ultra beast"` | Ultra Beasts. | | `is:"team plasma"` | Team Plasma cards. | | `is:sp` | Pokémon SP. | | `is:"delta species"` | Delta Species Pokémon. | | `is:unreleased` | Announced cards that are not out yet. | | `is:collectible` | Cards you can put in a deck (leaves out announced cards). | `is:ex` and `is:EX` are different shortcuts: lowercase finds the modern Pokémon ex, capitals find the older Pokémon-EX. The `subtype` field ignores case, so `subtype:ex` finds both. ## Attack cost `cost` (also `energy`, `attackcost`, `mv` or `cmc`) reads a card's attacks in two ways, depending on what you type. **A number** compares the total energy of the card's cheapest attack, of any type: `cost:1` finds cards whose cheapest attack costs one energy, and `cost<=2` finds cards with an attack for two or less. **Energy symbols** describe the exact mix of energy an attack costs. Write each symbol once per energy (`RCC`) or put a count in front (`1R2C`); both mean one Fire and two Colorless. Symbols are capital letters, so `cost:rcc` finds nothing. For a full energy name, use braces: `cost:{Fire}{Colorless}`. With symbols, `cost:` matches any one cost on the card that is exactly the listed mix. | Symbol | Meaning | | --- | --- | | `R` | Fire | | `W` | Water | | `L` | Lightning | | `G` | Grass | | `P` | Psychic | | `F` | Fighting | | `D` | Darkness | | `M` | Metal | | `Y` | Fairy | | `N` | Dragon | | `C` | Colorless | A `*` stands for one energy of any type, so `cost:RR*` finds attacks costing two Fire plus any one more energy. With symbols, the comparison operators compare the mix rather than a number: | You type | It finds an attack whose cost is | | ----------- | ---------------------------------------------------------------------- | | `cost:RCC` | Exactly one Fire and two Colorless. | | `cost=RCC` | The same: exactly one Fire and two Colorless. | | `cost>=RCC` | At least one Fire and two Colorless, possibly with more energy. | | `cost>RCC` | At least one Fire and two Colorless, with at least one more energy. | | `cost<=RCC` | Made only of energy from the list: `R`, `C`, `RC` and `RCC` all count. | | `cost=R` leaves out every card with an attack that needs Fire. ## Examples | Query | Finds | | --- | --- | | `t:water hp>=120` | Water Pokémon with 120 HP or more. | | `is:ex t:fire` | Fire Pokémon ex. | | `subtype:supporter o:"search your deck"` | Supporters that search your deck. | | `cost:RCC` | Pokémon with an attack that costs exactly one Fire and two Colorless. | | `cost>=RR damage>=200` | Pokémon with an attack needing at least two Fire, and an attack printed for 200 or more (not necessarily the same one). | | `cost:1 damage>=60` | Pokémon whose cheapest attack costs one energy and that have an attack printed for 60 or more. | | `retreat=0 stage:basic` | Basic Pokémon with free retreat. | | `stage:2 weakness:fighting` | Stage 2 Pokémon weak to Fighting. | | `pkachu` | Pikachu cards, despite the typo. | | `is:"ace spec"` | ACE SPEC cards. | | `not:ex t:psychic stage:basic reg:h` | Basic Psychic Pokémon with regulation mark H that are not Pokémon ex. | --- url: https://docs.turny.gg/reference/search/riftbound description: "Card search syntax for Riftbound: every field, is: shortcut and operator, with example queries." --- # Riftbound card search The search box on the [Riftbound Cards page](https://riftbound.turny.gg/cards) and in the [deck builder](https://riftbound.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a card by name, and fields let you ask for things like "Fury units that cost 3 or less" in one line: `domain:fury t:unit cost<=3`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The card's name. Unquoted text is typo-tolerant. | Any text | | `text` | `o`, `oracle` | Text | Rules text. | Any text | | `type` | `t` | Value | Card type: unit, spell, gear, rune, legend or battlefield. | `unit`, `champion`, `spell`, `gear`, `battlefield`, `rune`, `legend` | | `rarity` | `r` | Value | Rarity. Comparisons use the order of the allowed values. | `common`, `uncommon`, `rare`, `epic`, `legendary`, `showcase`, `ultimate` | | `set` | `e` | Value | Set code, such as `OGN` or `SFD`. | Values come from the card catalog. | | `cost` | `mv`, `cmc`, `energy` | Number | Energy cost. | A number | | `domain` | | Value | Domain. A card with two domains matches both. | `body`, `calm`, `chaos`, `fury`, `mind`, `order`, `colorless`, `neutral` | | `supertype` | | Text | Supertype, such as `Champion`, `Signature`, `Basic` or `Token`. | Any text | | `tag` | | Value | Tags, such as a region (`Demacia`) or a champion (`Yasuo`). | Values come from the card catalog. | | `keyword` | `kw` | Value | Keyword, in lowercase with `_` for spaces, such as `deflect` or `quick_draw`. | Values come from the card catalog. | | `might` | | Number | Might, a unit's combat strength. | A number | | `power` | `pow` | Number | Power cost: the domain-colored part of a card's cost, paid on top of its Energy cost. | A number | | `format` | `f`, `legal` | Value | A format the card is legal in. `standard` is the only one so far; banned and announced cards are left out. | `standard` | Riftbound's cost is a plain number: `cost` (or `energy`) is the Energy cost and `power` is the Power cost. Keywords are written in lowercase with `_` in place of spaces, such as `kw:quick_draw`. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:champion` | Cards with the Champion supertype: champion units and legends. | | `is:unreleased` | Announced cards that are not out yet. | | `is:collectible` | Cards you can put in a deck (leaves out tokens). | ## Examples | Query | Finds | | --- | --- | | `domain:fury t:unit cost<=3` | Fury units that cost 3 Energy or less. | | `is:champion domain:calm` | Calm champion units and legends. | | `t:legend` | Every legend. | | `kw:deflect might>=4` | Cards with Deflect and 4 Might or more. | | `t:spell o:"draw 1"` | Spells whose text says "draw 1". | | `tag:demacia` | Cards tagged Demacia. | | `r>=epic e:OGN` | Epic or rarer cards from Origins (`OGN`). | | `domain:mind domain:order` | Cards in both Mind and Order. | | `t:gear -kw:equip` | Gear without Equip. | | `power>=2` | Cards with a Power cost of 2 or more. | --- url: https://docs.turny.gg/reference/search/tft description: "Champion search syntax for Teamfight Tactics: every field, is: shortcut and operator, with example queries." --- # Teamfight Tactics card search The search box on the [Teamfight Tactics Cards page](https://tft.turny.gg/cards) and in the [team builder](https://tft.turny.gg/deck-builder) understands a small query language. A plain word is enough to find a champion by name, and fields let you ask for things like "live-set Juggernauts that cost 2 or less" in one line: `t:juggernaut c<=2 is:live`. ## How search works Type a query into the search box on the Cards page or in the deck builder. A query is one or more terms separated by spaces, and a card has to match every term. - **A plain word** searches card names and rules text: `draw`. - **`field:value`** searches one field: `t:spell`. Every field has a full name and usually a short alias, so `type:spell` and `t:spell` are the same search. Field names and values ignore upper and lower case unless this page says otherwise. The fields, shortcuts and examples for this game are further down the page. ## Matching text How you write a value decides how strictly it has to match. | You type | It matches | | ------------------- | --------------------------------------------------------------------------------------------------------------- | | `word` | Names close to `word`, typos allowed, plus any card whose name or rules text contains `word`. | | `n:word` | Names close to `word`, typos allowed. | | `"two words"` | Names or rules text containing exactly `two words`. Quotes turn typo tolerance off and let a value hold spaces. | | `field:"two words"` | That field contains exactly `two words`. | | `field:!value` | That field is exactly `value`, not just containing it. | | `field:/pattern/` | That field matches a regular expression, ignoring case: `n:/^the /` finds names starting with "The". | Some details: - **Only names are typo-tolerant.** Every other field matches when its value contains what you typed, so `o:draw` finds "draws" and "Draw 1". - **Best matches come first.** When a query has a plain word or a `n:` term, the closest names are listed first. A query with only fields keeps the page's normal order, and a sort you pick yourself always wins. - **Use `!` and `/…/` with a field.** On a plain word they compare against a card's name and rules text all at once, which rarely matches. - **The word `or` is special** (see below). To search for it, quote it: `"or"`. ## Combining terms | You type | It means | | ------------ | ------------------------------------------------------------------------------------------- | | `a b` | Both `a` and `b` must match. | | `a or b` | Either `a` or `b` must match. `OR` works too. | | `-a` | Leave out cards that match `a`. Works before any term or group: `-t:spell`, `-(a or b)`. | | `(a or b) c` | Parentheses group terms: `c` plus either `a` or `b`. | | `a b or c` | Terms next to each other are joined first, so this is `(a b) or c`. Add parentheses if not. | ## Comparing numbers and ranks Number fields such as cost take a comparison: | Operator | Meaning | Example | | --- | --- | --- | | `:` | Has this value: contains for text and values, equal for numbers | `cost:3` | | `=` | Equal to | `cost=3` | | `!=` | Not equal to | `cost!=3` | | `<` | Less than | `cost<3` | | `<=` | Less than or equal to | `cost<=3` | | `>` | Greater than | `cost>3` | | `>=` | Greater than or equal to | `cost>=3` | A field whose allowed values are listed in order, such as rarity, can be compared the same way: `r>=rare` finds Rare and everything ranked above it in the list shown in the fields table. A value that is not in that list never matches a comparison, though it still matches with `:`. ## Shortcut syntax `is:name` finds a whole kind of card in one term. `not:name` is the same as `-is:name`. If a shortcut's name has a space, quote it: `is:"two words"`. Each game's shortcuts are listed below. A field or shortcut the game doesn't have matches no cards, so check the spelling if a search comes back empty. ## Field kinds | Kind | How it matches | | --- | --- | | Text | Free text, such as a name or rules text. `:` means contains (names also allow typos). | | Value | One of a set of values, such as a type or region. `:` means contains, so part of a value is enough. When the allowed values are listed, comparisons follow their order. | | Number | A number. `:` means equal, and every comparison operator works. | | Symbols | A mix of symbols, such as an attack cost or a card's colors. Some of these fields also take a plain number. A game with symbol fields explains them below its fields table. | ## Fields | Field | Aliases | Kind | Description | Values | | --- | --- | --- | --- | --- | | `name` | `n` | Text | The champion's name. Unquoted text is typo-tolerant. | Any text | | `cost` | `c`, `tier` | Number | Shop cost, 1 to 5: `cost>=4`. | A number | | `trait` | `t`, `tr` | Value | A trait the champion has, such as `trait:coven`. A champion that picks an origin matches every origin it can pick. | Values come from the card catalog. | | `set` | `e`, `s` | Value | The champion's set, by number (`set:18`) or code (`set:TFTSet18`). | Values come from the card catalog. | In TFT, `t` is short for `trait`, not type. A champion that picks an origin in game (Set 18 Lux) matches every trait it can pick, so `trait:coven` finds Lux. `set` takes either the number or the full set code: `set:18` and `set:TFTSet18` find the same champions. A plain word also searches trait names and ability text, so `laser` finds champions whose ability fires one. ## Shortcuts | Shortcut | Finds | | --- | --- | | `is:live` | Champions of the set the live game plays. | ## Examples | Query | Finds | | --- | --- | | `trait:coven` | Coven champions, Lux included through her Coven origin. | | `is:live cost>=4` | 4 and 5 cost champions of the live set. | | `set:18 cost:1` | Set 18's 1 cost champions. | | `t:juggernaut c<=2 is:live` | Live-set Juggernauts that cost 2 or less. | | `t:blossom or t:elderwood` | Champions with Blossom or Elderwood. | | `trait:conduit set:17` | Set 17's Conduit champions. | | `n:ahri -is:live` | Ahri from sets the live game no longer plays. | | `morgna` | Morgana, despite the typo. | | `laser` | Champions whose ability text mentions a laser, such as Lux. |