Spec: the shared artifact
Every platform (Swift core, Kotlin core, Rust server) reads these files and must agree on them.
| Folder | Holds | Read by |
|---|---|---|
decks/ |
One JSON file per deck: its ranks, suits, jokers and canonical order. The file name is its id (format) |
The Swift, Kotlin and Rust cards modules, through each core’s deck tests |
games/ |
One JSON file per game: the decks it may be played with. The file name is its id (format) |
Each core’s game declaration (CanastaGame), through its deck tests |
rulesets/ |
One JSON file per rule set. The file name is its id. |
Swift, Kotlin and Rust RuleSet models and tests |
scenarios/ |
Rule scenarios: rule set, start, moves, expected outcome (format) | Swift, Kotlin and Rust scenario tests |
parity/ |
Reference vectors every core must reproduce exactly: random numbers, shuffles, deals, seeded bot games, hand orders and selections (format) | Swift, Kotlin and Rust parity tests |
parity-long/ |
The same, too slow for every run: 1,000 bot games per rule set (format) | The parity tests, only with CANASTA_PARITY_LONG=1 |
behaviour/ |
Bun tests that drive each platform’s CLI, headless (format) | bun test, once per CLI |
bots.md |
The computer players’ brief: Easy and Normal, decision by decision | Swift, Kotlin and Rust bots |
protocol/ |
cli.md: the CLI protocol every platform’s CLI speaks; server.md: the game server’s WebSocket protocol |
The Swift, Kotlin and Rust CLIs; the behaviour suite; rust/canasta-server |
online/ |
The online client: the Session and TableClient state machines and their transcripts | The web (web/src/online), and with #258 and #259 Swift (HomefeltOnline) and Kotlin (kotlin/online) |
saves/ |
Example saved games: every core loads each one and saves it back unchanged | Swift, Kotlin and Rust saved-game tests; the behaviour suite |
app-status/ |
The app-status feed (https://homefelt.io/app-status/v1.json) that tells installed apps about updates, maintenance, news and sunsets: its README, authoring schema.json, examples/ and select cases/ |
bin/test app-status; Swift, Kotlin and web AppStatus tests |
ads/ |
When the apps may show a full-screen ad: the README with the adSlot contract, placements.json (breaks, caps and grace as data) with its schema.json, and decision cases/ |
bin/test ads; Swift, Kotlin and web Ads tests (#236) |
purchases/ |
The “Remove ads” entitlement: the README with the EntitlementState reducer’s contract, the device cache’s schema.json and examples/, and reducer cases/ |
bin/test ads; Swift, Kotlin and web Entitlements tests (#236) |
tutorials/ |
Guided hands: a scripted deal, the steps a coach walks a person through and the computer seats’ scripted replies (format) | Swift, Kotlin and Rust Tutorial loaders and tests; the CLIs and the Wasm build, which offer them (protocol/cli.md) |
invalid/ |
Known-bad rule set, scenario, parity, saved-game, tutorial, app-status, ad placement and entitlement cache files that every runner must reject (app-status ones by bin/test app-status, ads and purchases ones by bin/test ads, and each platform’s parser) (format) |
Swift, Kotlin and Rust spec tests |
Rule sets
official.json follows Pagat’s Classic Canasta.
family.json is our house rules, from the “Family rules” table in the product requirements.
modern-american.json follows Pagat’s Modern American Canasta
(the 2017 description), for 4 players only; docs/plans/modern-american.md
maps each of its rules to a setting. In the table below, “both rule sets” means official and
family, whose values keep Classic play; modern-american sets the Modern American value each row
names.
Every rule set has every field: there are no defaults, so a reader can compare two files line
by line. Every file in rulesets/ is a Canasta rule set (the game canasta).
The deck comes first. Decoding a rule set checks deck before any other field, and before it
decodes the rest: when the file is a JSON object, a missing deck fails with deck: missing
(there is no default deck); a deck that is not one of the strings french, spanish-40 and
spanish-48 (null, a number, "French", "italian-40") fails with
deck: not french, spanish-40 or spanish-48; and a deck that is not one of the game’s decks
fails with deck: canasta is not played with <id> (deck: canasta is not played with spanish-40).
Only then are the other fields decoded, and their failures are each platform’s own decoding
messages. Once they decode, the first tables[] entry whose teams is below 1 fails with
tables[<i>].teams: below 1, i counting from 0 (tables[1].teams: below 1): every seat plays for
side seat % teams, so a table needs a side. Then a rule set whose deal.upcard is none with
deal.hiddenCardsUnderUpcard above 0 fails with deal.hiddenCardsUnderUpcard: above 0 with no upcard: hidden cards lie under an upcard, so a pile cannot start with them alone. Then the first of
initialMeld.bonusCards’ first, second and minStock below 0 fails with
initialMeld.bonusCards.<field>: below 0 (initialMeld.bonusCards.second: below 0). Then the first
specialHands.hands[] entry with a groups item below 1 fails with
specialHands.hands[<i>].groups: below 1, i counting from 0. Every core’s production loader (the apps, the CLIs,
the Wasm session and the server read rule-set files through it) makes these checks, not only its
tests.
| Field | Meaning |
|---|---|
deck |
The id of the deck the game is played with: one of the game’s decks. Canasta’s only deck is french, so a Canasta rule set naming spanish-40 or spanish-48, or naming no deck, fails to decode (see above) |
tables[] |
Per player count: teams, decks (each 52 cards + 2 jokers, see Cards), cardsDealt, canastasToGoOut, gameTarget. A player count with no entry cannot be dealt. The rule set’s player counts are the entries’ players, in file order ([4, 6] in both rule sets) |
drawPerTurn |
Cards drawn from the stock per turn |
deal.hiddenCardsUnderUpcard |
The Family cut: cards moved face down from the stock to the discard pile after the hands and before the upcard. They are never turned, so wilds and red threes among them stay there unseen |
deal.upcard |
turned: the deal turns an upcard onto the pile (The deal, step 5); none: it turns none, so the pile starts empty (Modern American; with hidden cards above 0 the rule set does not load, see above). turned in both rule sets |
deal.upcardWildOrRedThree |
turnAnother: a wild or laid-out three turned as the upcard stays in the pile (a wild or red three freezes it) and another card is turned on top, until a natural card that is not a laid-out three shows |
initialMeld.minimums[] |
Points needed for a side’s first meld, in rising fromScore order; the first entry, and only it, has fromScore: null (any score below the next band), so every score has a band; a missing fromScore is null |
initialMeld.pileCardsCount |
Which cards of an opening take count toward the minimum: topCardOnly (the top card, the take’s cards and its melds), all (the same, and a take’s melds may also draw cards from the rest of the pile, see take) or none (the top card counts nothing; the take’s cards count only when they form a meld by themselves, and its melds count: the opening is laid wholly from the hand before the pile is taken, Modern American). topCardOnly in both rule sets |
initialMeld.requires |
A meld the opening must hold (Sides and melds): nothing; naturalMeld, a meld with no wild (the Canasta League’s “clean triple”); or naturalOrWildMeld, a meld with no wild or one of only wilds (Pagat’s Modern American). nothing in both rule sets |
initialMeld.canastaWaivesMinimum |
If true, an opening holding a natural or wild canasta laid from the hand needs no minimum (Modern American’s “splash”). false in both rule sets |
initialMeld.bonusCards |
null (no bonus cards; both rule sets, and a missing bonusCards is null) or { "first", "second", "minStock" }: a side’s opening turn that does not go out ends with the opener dealt a face-down talon of first cards (second once another side has opened) while the stock holds at least minStock cards, and its opening may leave one card in the hand (Pagat’s Modern American: 4, 3 and 9). Each is an integer of 0 or more, or the rule set does not load |
discardPile.alwaysFrozen |
If true, the pile can only be taken with a natural pair matching the top card |
discardPile.takeWithNaturalAndWild / takeByAddingToMeld |
Extra ways to take an unfrozen pile |
melds.minNaturals, melds.maxWilds |
Limits for ordinary melds |
melds.wildsOnNaturalCanasta |
Whether wilds may be added to a finished natural canasta (it becomes mixed) |
melds.maxCards |
The most cards a meld may hold, wild melds included, or null for no limit; a missing maxCards is null (Modern American’s 7: a side with a meld of 5 or 6 cards of the top card’s rank cannot take the pile with a pair, since the take meld would overfill it). null in both rule sets |
melds.closedRank |
open: a natural canasta changes nothing for its rank; dead: once any side holds a natural canasta of a rank, that rank is dead and no side may begin or add to a meld of it (Modern American). open in both rule sets |
melds.naturalsBeforeWildAfterOpening |
Modern American’s “rule of five”: after a side’s opening, a wild may join one of its melds (new or existing, other than the wild meld) only when that meld holds at least this many naturals once the move is done; 0 = no limit. 0 in both rule sets |
melds.naturalOnlyRanks[] |
Ranks whose melds never take a wild (Modern American’s sevens). [] in both rule sets |
melds.wildsOnlyInOpeningRanks[] |
Ranks whose melds take wilds only when laid with them in the side’s opening; such a meld laid without one never takes one (Modern American’s aces). [] in both rule sets |
wildCanastas |
allowed; mustBeLaidComplete (a meld of only wilds must have 7 cards when it is laid, see Sides and melds); the default bonus; exactBonuses[] for specific joker/two mixes; and blocksOtherWilds: while the side’s wild meld holds fewer than 7 cards, no wild may join any of its other melds (Modern American; false in both rule sets) |
canastaBonus |
natural and mixed; naturalByRank[], each { "rank", "bonus" }: a natural canasta of that rank scores bonus in place of natural (Modern American’s 2500 for aces and sevens; [] in both rule sets) |
goingOut |
askPartner: whether a player may (optional), must (required) or may not (never) ask partner “may I go out?” before going out (ask); mustDiscard: whether going out needs a final discard, so that a take, lay or add may not empty the hand (Going out; false in both rule sets, so going out by melding every card is allowed); bonus for going out; concealedBonus, which replaces bonus for going out concealed |
discards.wild |
allowed: any wild may be discarded; goingOutOrOnlyWilds: a wild may be discarded only as the last card of the hand or from a hand of only wilds (discard; Modern American). allowed in both rule sets |
discards.onEmptyPile.ranks |
Ranks (A, 3 … K, 2, JK) whose cards may not be discarded on an empty pile while the hand holds another card that may be discarded (discard; Modern American’s ["A", "7"]). [] in both rule sets |
discards.onEmptyPile.dead |
Whether a card of a dead rank (a rank some side holds a natural canasta of, with melds.closedRank dead) is held back on an empty pile like the ranks cards (discard; Modern American). false in both rule sets |
redThrees |
each, allTotals[] (total when a side holds count of them), negativeWithoutMeld, and byCanastas: the threes count against a side with no canasta, nothing for a side with one, and for a side with two or more (Modern American; replaces negativeWithoutMeld, see Scoring; false in both rule sets). With blackThrees.layOut the same table scores the laid black threes too, colour by colour |
blackThrees |
meldOnlyWhenGoingOut, minToMeld, and layOut: black threes are laid out like red threes, dealt, drawn or taken, onto the seat’s blackThrees, and never melded or discarded (Modern American). false in both rule sets |
cardValues |
Points per card group |
unfinishedCanastaPenalty |
Points lost, at the end of a hand, for each of a side’s melds that is not a canasta (0 = none) |
unfinishedMeldPenalties[] |
Each { "kind", "rank", "minJokers", "penalty" }: points lost, at the end of a hand, for each of a side’s melds that is not a canasta and is matched by the entry (see Scoring), on top of unfinishedCanastaPenalty. kind is natural, mixed or wild; rank is a rank (A, 4 … K) or null, which only a wild meld matches; a missing rank is null. [] in both rule sets |
cardsInHandPenalties[] |
Each { "rank", "count", "penalty" }: points lost, at the end of a hand, for each seat whose hand holds at least count cards of rank (Modern American’s 1500 for three or more sevens, or aces, in one hand). [] in both rule sets |
meldsWithoutCanasta |
add: a side’s melded cards always score their points; subtract: a side that holds no canasta loses them instead (Modern American). add in both rule sets |
stockEmpty |
handEndsWhenPlayerMustDraw: a player who draws from an empty stock ends the hand (The stock runs out); lastThreeInHand: the same, and a three drawn as the stock’s last card stays in the hand instead of being laid out (Modern American). handEndsWhenPlayerMustDraw in both rule sets |
specialHands.keepThree |
Whether a seat whose side holds no meld keeps one laid-out three in its hand, to collect a straight (Pagat’s Modern American). false in both rule sets |
specialHands.hands[] |
Each { "name", "score", "groups", "requiredRanks", "forbiddenRanks" }: a special hand a seat whose side holds no meld may declare after drawing, ending the hand; name names it to the apps, score is what the side scores. Ranks are written A, 2 … 10, J, Q, K, JK. Pagat’s Modern American has four (straight, pairs, pairsWithWilds, garbage). [] in both rule sets |
Decks
A deck is one pack of cards as it is sold, written down in decks/<id>.json. Decks belong to no
game: a rule set names its deck with deck, and a game’s own settings say how many copies it uses
(Canasta’s tables[].decks). Every key below is required.
| Key | Value |
|---|---|
id |
The deck’s id, the file name: french, spanish-40 or spanish-48 |
name |
The deck’s name, for people |
ranks |
The rank codes, in canonical order |
suits |
The suit codes, in canonical order |
jokers |
How many jokers one pack holds |
order |
One pack in canonical order: for each suit of suits in order, each rank of ranks in order (rank code then suit code), then jokers times JK |
| Deck | Ranks | Suits | Jokers | Cards |
|---|---|---|---|---|
french |
A 2 3 4 5 6 7 8 9 10 J Q K |
C D H S: clubs, diamonds, hearts, spades |
2 | 54 |
spanish-40 |
1 2 3 4 5 6 7 10 11 12: 10 is the sota, 11 the caballo, 12 the rey |
or co es ba: oros, copas, espadas, bastos |
0 | 40 |
spanish-48 |
1 to 12: spanish-40 plus the 8s and 9s |
as spanish-40 |
2 | 50 |
The Spanish packs follow Wikipedia’s Spanish-suited playing cards: most packs hold 40 or 48 cards, the faces are sota, caballo and rey (numbered 10, 11 and 12 here), and 48-card packs have been sold with two jokers since the mid-20th century. The suits are in their traditional order, oros, copas, espadas, bastos. A game that plays without the jokers, or without some ranks, says so in its own rule set; the deck stays the pack.
Card codes. A card is written as its rank code then its suit code, with no separator and nothing
else; a joker is JK and has no suit. So AS, 10H, 3D and 2C are French cards, and 1or (as de
oros), 7co (siete de copas), 11ba (caballo de bastos) and 12es (rey de espadas) are Spanish ones.
Codes are case-sensitive, and a deck’s parser reads only its own deck’s codes: exactly the codes in
its order, compared Unicode scalar by Unicode scalar, with no normalization and no canonical
equivalence. So "\u212aS" (the Kelvin sign, U+212A, then S) is not KS, although a Swift String
== would call the two equal: a Swift parser compares unicodeScalars or utf8. Anything else
is not a card of that deck: 1H, TH, as, JKS, 3X and "\u212aS" are not French cards;
8or, 9ba and JK are not spanish-40 cards (8or and JK are spanish-48 cards); and no
French code is a Spanish card or the other way round, since French suits are one capital letter and
Spanish suits two small ones. Formatting a card gives back the code it was parsed from.
The scalar-by-scalar rule is the cards module’s, for card codes. Deck and game ids hold no character
that has a canonically equivalent spelling, so they compare the same either way. The other strings
of spec files and protocols (object keys, rule-set ids and enum values such as do, method, rank,
view or level) are not yet pinned against canonically equivalent spellings, and no file in
spec/ depends on how they are read; a later checkpoint pins them.
parity/cards.json pins every deck’s codes and a set of non-codes; parity/shuffle-spanish.json
shuffles both Spanish decks (Shuffle).
Every core builds the three decks into its cards module (types, codes and canonical order), and its
deck tests check each built-in deck against its file: the same id, name, ranks, suits,
jokers and order, one file per deck and one deck per file.
Deck is not the “Deck” display setting. The apps, the web game and the site have a display
setting called Deck, with the choices Four colours and Red and black (the default everywhere). It is
only the colour scheme French cards are drawn in. It is not a deck id, it never changes a rule
set’s deck, and no file in spec/ names it.
Games
A game is a set of rules played with particular decks, written down in games/<id>.json. A rule set
belongs to a game, and its deck must be one of that game’s decks. Every key below is required.
| Key | Value |
|---|---|
id |
The game’s id, the file name |
name |
The game’s name, for people |
decks |
The deck ids the game may be played with, a non-empty list, each a file in decks/ |
| Game | Decks |
|---|---|
canasta |
french |
Canasta needs the 52 French cards and their jokers, so it takes no Spanish deck. A Spanish-deck game
(Chinchón, say) will list spanish-40 and spanish-48 and no French deck. Every core builds its
game’s declaration in (CanastaGame: its id, name and decks), and its deck tests check it
against games/canasta.json and check that games/ holds exactly the games the core knows.
Scenarios, parity cases other than shuffle and cards, and saved games name a rule
set, and the rule set names its deck, so none of them names a deck itself: the save format stays at
version 1.
Cards
Canasta is played with the french deck: ranks A 2 3 4 5 6 7 8 9 10 J Q K, suits C D H S
(clubs, diamonds, hearts, spades), so AS, 10H, 3D, 2C, and JK for a joker, which has no suit.
- Wild: a joker or any 2.
- Red three:
3Dor3H. Black three:3Cor3S. - Natural: any card that is not wild.
Deck order. decks copies of the french deck’s canonical order, one copy after another. One
copy is the suits in the order C, D, H, S, each suit A, 2, 3 … 10, J, Q, K, then JK, JK. So 2 decks start
AC 2C 3C … KC AD … KS JK JK AC 2C … and hold 108 cards; 3 decks hold 162.
Random numbers: PCG32
Every core uses the same generator, so the same seed gives the same game everywhere. It is
pcg32 (XSH RR, 64-bit state, 32-bit output) from the
PCG reference implementation
by Melissa O’Neill. All arithmetic is unsigned and wraps modulo 2^64 (state) or 2^32 (output).
new(seed, stream): # both unsigned 64-bit state = 0 inc = (stream << 1) | 1 next() state = state + seed next()
next() -> UInt32: old = state state = old * 6364136223846793005 + inc xorshifted = UInt32(((old >> 18) ^ old) >> 27) # keep the low 32 bits rot = UInt32(old >> 59) return (xorshifted >> rot) | (xorshifted << ((32 - rot) & 31))
nextBounded(bound) -> UInt32: # uniform in 0 ..< bound, bound >= 1 threshold = (2^32 - bound) % bound loop: r = next(); if r >= threshold: return r % boundSeeds and streams in spec files are JSON integers from 0 to 2^53 − 1 (9007199254740991), so every
JSON reader keeps them exact. Every core publishes that bound as maxSeed (the largest seed or
stream newGame takes, protocol/cli.md), so an app that picks a seed never
hard-codes it.
Reference vector. new(42, 54) followed by six next() calls gives 0xa15c02b7 0x7b47f409 0xba1d3330 0x83d2f293 0xbfa4784b 0xcbed606e, the published output of the reference
pcg32-demo (first round,
32bit: line). It is the first case in parity/pcg32.json; the other cases there were derived from
the algorithm above.
Shuffle
Fisher–Yates over a list of cards, from the last index down. Canasta shuffles its stock in
deck order; a shuffle parity case shuffles decks copies of its deck’s canonical order
(Decks). The algorithm is the same for every deck:
for i from count - 1 down to 1: j = nextBounded(i + 1) swap cards[i] and cards[j]The shuffled list is the stock, and index 0 is its top card, the next one drawn.
The deal
Seats are numbered 0 ..< players clockwise. “The dealer’s left” is seat (dealer + 1) % players.
A hand lists its cards in the order the player received them. The steps, in this order:
- Checks. No
tables[]entry forplayers→unsupportedPlayerCount. Otherwisedealeroutside0 ..< players→invalidSeat. Otherwise, for a stacked stock (see Scenarios), a card not left in the deck →cardNotInDeck. - Stock. Build
decksdecks in deck order and shuffle them withnew(seed, stream), or stack them. - Hands. Deal
cardsDealtcards to each seat one at a time from the top of the stock, starting with the dealer’s left and going clockwise: the k-th card drawn (k from 0) goes to seat(dealer + 1 + k) % players. - Hidden cards. Move
deal.hiddenCardsUnderUpcardcards, one at a time, from the top of the stock onto the discard pile, face down. Each goes on top of the one before. - Upcard. With
deal.upcardturned, move the top card of the stock onto the pile, face up. While that card is wild or a laid-out three (a red three, or a black one withblackThrees.layOut), it stays and the next stock card is turned on top of it (turnAnother). Withnone, nothing is turned and the pile stays empty (a rule set withnonehas no hidden cards). - Threes. Seat by seat, starting with the dealer’s left and going clockwise, each player
lays out every laid-out three in their hand (in hand order, a red three onto
their own
redThrees, a black one ontoblackThrees; the rest of the hand keeps its order) and draws as many replacements from the top of the stock, appended to the hand. A player who draws such a three repeats this step before the next seat starts. - Turn. The dealer’s left plays first, at
turnStagedraw. Every side starts withgameScore0 and no melds (sideshasteamsentries). Every seat’smeldedis false;wentOutis false,concealedtrue,turnMelds0 andquestionnotAsked. (The next hand deals the same way, with the sides’ new game scores.)
A step of 3 to 6 that needs a card from an empty stock → stockExhausted, and nothing is dealt. No
rule set deals that many cards (a hand of cardsDealt per seat, the hidden cards and the upcards
always leave cards in the stock), so no scenario reaches it; each core’s unit tests pin it with a
rule set changed in memory.
Every pile in JSON lists its top card first. The discard pile pile holds the face-up cards and,
at its end, the pileHidden face-down cards: a Family deal with one upcard has
pile = [upcard, hidden4, hidden3, hidden2, hidden1] and pileHidden = 4.
Game state
The JSON form of a position, used by scenario starts. Every field is required.
| Field | Meaning |
|---|---|
dealer |
The dealer’s seat |
turn |
The seat to play |
turnStage |
draw (the seat must draw or take the pile), play (it has drawn: it melds, then discards), answer (it has asked partner “may I go out?” and waits for the answer) or handOver (the hand is over: a player went out, or the stock ran out; no move is accepted) |
seats[] |
One per seat, in seat order: hand (cards), redThrees (cards laid out, in the order laid), blackThrees (black threes laid out with blackThrees.layOut, in the order laid), bonusCards (the seat’s face-down bonus cards, in the order dealt; empty without initialMeld.bonusCards) and melded (whether the seat has laid a meld or added cards to one in this hand). blackThrees and bonusCards are the only fields a position may leave out, as [], so every older position still reads; present, each is a list of cards, never null |
sides[] |
One per side, in side order: gameScore (the side’s game score before this hand) and melds[], each { "cards": [cards] }, in the order the side laid them |
stock |
The stock, top first |
pile |
The discard pile, top first, hidden cards last |
pileHidden |
How many cards at the end of pile are face down |
wentOut |
Whether the hand ended by turn going out: false while the hand is in play, and when it ended because the stock ran out |
concealed |
Whether the seat to play can still go out concealed this turn |
turnMelds |
How many melds the seat to play has laid this turn: they are the last turnMelds melds of its side. When it is above 0 and equal to the number of the side’s melds, this is the side’s opening turn |
question |
“May I go out?” this turn: notAsked (not asked, and it may still be asked), tooLate (the seat has melded since its draw without asking), asked (waiting for partner’s answer), yes or no (partner’s answer) |
A position must have a tables[] entry for its number of seats, and exactly that entry’s teams
sides; a runner fails a scenario whose position does not. Cores do not check positions further
(card counts, melds), so a position is taken as written; a saved game’s position is
checked more when it loads.
Sides and melds
Sides. Seat s plays for side s % teams (teams from the tables[] entry for the number of
seats): with 4 players seats 0 and 2 are side 0, 1 and 3 side 1; with 6 players seats 0 and 3, 1
and 4, 2 and 5. Melds belong to the side: partners add to each other’s melds, never to an
opponent’s. A side has opened once it holds at least one meld.
Card points (from cardValues): JK joker; any 2 two; any A ace; K Q J 10 9 8
kingToEight; 7 6 5 4 sevenToFour; a black three blackThree; a red three 0 (red threes score
on their own, see Scoring).
Threes laid out. A red three, and with blackThrees.layOut a black three, is a laid-out
three: it never stays in a hand. One dealt is laid out at the deal (The deal), one
drawn is laid out and replaced (draw), and one taken with the pile is laid out and not
replaced (take); a red three goes onto the seat’s redThrees, a
black one onto its blackThrees. No meld takes one (notSameRank, below), and a black one is
never discarded while another card may be (discard). The exceptions are
stockEmpty lastThreeInHand, where a three drawn as the stock’s last card stays in the hand and
ends it (The stock runs out), and a kept three.
A kept three. With specialHands.keepThree (Pagat’s Modern American: “it is permissible to
retain just one three in your hand … for the purpose of collecting a straight”), a seat whose side
holds no meld keeps one laid-out three in its hand:
-
At the deal (step 6 of The deal) the first laid-out three of each hand, in hand order, stays in it; the others are laid out and replaced as usual, and a replacement three is laid out too.
-
A laid-out three drawn (
draw, a replacement included) stays in the hand, as the drawn card and not replaced, when the seat’s side holds no meld and the hand holds no laid-out three. A three drawn as the stock’s last card is not kept: it ends the hand as before. -
Pagat: “As soon as your team has melded you must lay down any three you are holding at your next opportunity”, and when the partner makes the meld, “at the start of your next turn”. So:
- right after a seat’s own
takeorlaythat leaves its side holding a meld (the move that opens the side), each laid-out three left in its hand, in hand order, is taken out, laid out and replaced exactly as a talon’s three is, in the same move; if a replacement ends the hand, the rest stay laid out unreplaced; - when the turn passes to a seat whose side holds a meld (its partner opened the side), after its talon joins, the same happens before the seat draws.
So a three kept by the seat that opens its side is never left in a hand that ends before that seat’s next turn. Eduardo confirmed this reading on 2026-11-25.
- right after a seat’s own
The three is kept at first; a player who does not want it lays it out with
layOutThree (Pagat: “If you have been holding a three in
your hand and decide you no longer wish to keep it, then during your turn you may lay the three face
up … and draw a replacement card”). Where Pagat is silent the engine keeps it simple: once the side
has a meld, the three is laid out at the start of the seat’s next turn, so a player who opens keeps
theirs until then unless they lay it out; and with blackThrees.layOut it is never discarded while
another card may be. A three still in a hand when the hand ends counts cardValues.blackThree in
cardsInHand (Scoring).
A meld is a list of cards. Its rank is the rank of its first natural card; a meld with no
natural card is a wild meld and has no rank. A side holds at most one meld per rank and at most
one wild meld. Its kind is natural (no wilds), mixed (naturals and wilds) or wild (only
wilds). It is a canasta when it holds 7 cards or more. Its canasta bonus is 0 when it is not
a canasta; otherwise, for a natural one, the bonus of the first canastaBonus.naturalByRank entry
whose rank is the meld’s rank, else canastaBonus.natural; canastaBonus.mixed for a mixed one;
and for a wild one the bonus of the first wildCanastas.exactBonuses entry whose jokers and
twos equal the meld’s exact counts of jokers and 2s, else wildCanastas.bonus.
A rank is dead when melds.closedRank is dead and some side (either) holds a natural canasta
of that rank before the move (Pagat: “closed”); with open no rank is dead.
A new meld (laid, or formed by taking the pile) is checked in this order; the first failing check is the error. “Hand after” is the size of the mover’s hand once the whole move is done (for a take, including the pile cards it brings in).
- Fewer than 3 cards →
meldTooSmall. - More than
melds.maxCardscards (when it is notnull) →meldFull. - Only wilds (a wild meld):
wildCanastas.allowedfalse →tooFewNaturals; the side already holds a wild meld (or one laid earlier in the same move) →rankAlreadyMelded;wildCanastas.mustBeLaidCompletetrue and fewer than 7 cards →wildCanastaIncomplete. Otherwise valid: a wild meld is exempt frommelds.maxWildsandmelds.minNaturals. - Naturals of more than one rank, or a laid-out three among them →
notSameRank. - The rank is dead →
rankDead. - The side already holds a meld of that rank (or one laid earlier in the same move) →
rankAlreadyMelded. - Rank 3 (black threes): any wild →
tooManyWilds; fewer thanblackThrees.minToMeldcards →tooFewBlackThrees;blackThrees.meldOnlyWhenGoingOutand hand after ≥ 2 →blackThreesOnlyWhenGoingOut(with 0 or 1 card left the player can only go out, see Going out). Otherwise valid. - A wild among them and the rank is in
melds.naturalOnlyRanks→naturalOnlyRank. - A wild among them, the rank is in
melds.wildsOnlyInOpeningRanks, and the side had opened before the move (so the meld is not part of its opening) →wildsOnlyInOpening. - A wild among them, the side had opened before the move, and fewer naturals than
melds.naturalsBeforeWildAfterOpening→wildNotYet. - More than
melds.maxWildswilds →tooManyWilds. - Fewer than
melds.minNaturalsnaturals →tooFewNaturals.
Cards added to an existing meld are checked in this order:
- A wild meld: any natural among them →
notSameRank; more thanmelds.maxCardscards after the addition →meldFull. Otherwise valid (no limit on its wilds). - A natural that is not of the meld’s rank, or is a laid-out three →
notSameRank. - More than
melds.maxCardscards after the addition (when it is notnull) →meldFull. - The meld’s rank is dead →
rankDead. - The meld is a natural canasta before the addition, a wild is among the added cards, and
melds.wildsOnNaturalCanastais false →wildOnNaturalCanasta. - A wild among the added cards and the rank is in
melds.naturalOnlyRanks→naturalOnlyRank. - A wild among the added cards, the rank is in
melds.wildsOnlyInOpeningRanks, and the meld holds no wild before the addition →wildsOnlyInOpening. - A wild among the added cards and fewer naturals in the meld after the addition than
melds.naturalsBeforeWildAfterOpening→wildNotYet(an addition is always after the opening). - The meld’s wilds after the addition exceed
melds.maxWilds(0 for a meld of black threes) →tooManyWilds.
A wild meld blocks other wilds when wildCanastas.blocksOtherWilds is true. After a move’s new
melds and additions pass the checks above, if the side’s wild meld after the move holds fewer than 7
cards and a wild of the move went into any other meld (a take meld, a new meld, or an addition) →
wildMeldUnfinished. The check reads the side’s melds once the whole move is done, so the order
of a lay’s melds never matters, and a wild meld laid in the same move counts.
An addition never re-runs the black-three checks (blackThrees.minToMeld,
meldOnlyWhenGoingOut): the meld reached minToMeld when it was laid, and with
meldOnlyWhenGoingOut it was laid with at most one card left, so any addition is that player’s last
card, which goes out (scenarios/threes/black-three-added-going-out.json).
Initial meld. A side’s first meld (opening) must reach a minimum: the points of the last
initialMeld.minimums entry whose fromScore is null or ≤ the side’s gameScore (so −5 → 15,
0 → 50, 1495 → 50, 1500 → 90, 3000 → 120). The points are the card points of every card in every
meld of the opening move. When the opening takes the pile (pileCardsCount: topCardOnly), they are
the top card, the take’s hand cards and the take’s melds; the rest of the pile never counts.
With pileCardsCount: none the top card counts nothing, so the opening is made wholly from the hand
and must reach the minimum before the pile is taken (Pagat’s Modern American). The take’s cards
count only when they form a meld by themselves: 3 or more cards, at most melds.maxWilds wilds
and at least melds.minNaturals naturals (the checks of a new meld; they are always of one natural
rank). Pagat: “The pair that you use to take the pile could be within one of the melds you are using
to meet the initial meld requirement.” A natural pair is not a meld, so it counts nothing. Several melds may be laid in one opening. Short →
initialMeldTooLow. One exception (Pagat’s going out concealed): a lay by a side that has not
opened which is a going-out move (it leaves fewer than 2 cards in the hand) needs no minimum. It goes out, so it still needs
the canastas to go out (Going out). A lay that leaves one card while bonus cards
are due is not a going-out move, so it needs the minimum. A take always needs the minimum, except for the
splash below.
The opening’s counted melds are the melds whose cards count toward the minimum: a lay’s
melds; a take’s take meld and its melds, or with pileCardsCount: none its cards when they
form a meld by themselves, then its melds. The opening’s hand melds are a lay’s melds; a
take’s melds with topCardOnly; with none its cards when they form a meld by themselves, then
its melds; and none with all (whose melds may hold pile cards), so with all a take never
splashes. The take meld itself (with the top card) is never a hand meld. Two more settings shape the opening,
checked in this order after the melds themselves:
- The minimum, as above, unless
initialMeld.canastaWaivesMinimumis true and a hand meld is a natural or wild canasta (7 or more cards, no wild or only wilds): that opening needs no minimum (Pagat’s “splash”). Short →initialMeldTooLow. - The required meld,
initialMeld.requires, which applies even when the minimum does not (going out concealed, or a splash): withnaturalMeld, no counted meld holds no wild →initialMeldNeedsNaturalMeld; withnaturalOrWildMeld, no counted meld holds no wild or only wilds →initialMeldNeedsNaturalOrWildMeld. A meld of black threes holds no wild.nothingrequires no meld.
scenarios/initial-meld/ pins each setting with overrides.
The pile is frozen for everyone when discardPile.alwaysFrozen is true, or one of its face-up
cards (the first pile.count - pileHidden) is wild or a red three. It is frozen against a side
that has not opened. A frozen pile can only be taken with a natural pair.
Moves
A move is one seat doing one action. Every action is checked in full first; on any error nothing changes. The checks below run in the order written, after these, which every action starts with:
- The position has no
tables[]entry for its number of seats, or not exactly that entry’steamssides →unsupportedPlayerCount. A runner never builds such a position (see Game state), so no scenario reaches this; it keepsapplyfrom failing any other way. - The seat is outside
0 ..< seats→invalidSeat. - It is not the seat to act →
notYourTurn. The seat to act isturn, except atturnStageanswer, when it is the asker’s partner, seat(turn + teams) % seats(every table has 2 seats per side: with 4 players seat 0 asks seat 2, with 6 players seat 0 asks seat 3). turnStageis not the one the action needs (drawfordrawandtake;playforlay,add,discard,askanddeclare;draworplayforlayOutThree;answerforanswer;handOveraccepts nothing) →wrongTurnStage. Once the hand is over,turnis still the seat that went out (or that ended the hand by drawing), so that seat getswrongTurnStageand every other seatnotYourTurn.
Cards named in an action are taken out of the hand one at a time, in the order the action lists them
(for a take, cards first, then each of melds in order), each removing the first copy of that
card left in the hand; the rest of the hand keeps its order. A card with no copy left →
cardNotInHand. Cards drawn or brought in are appended to the end of the hand.
Turn fields. A move that succeeds also updates melded, concealed, turnMelds and
question as follows (ask and answer set question and turnStage as their sections say):
take,layandaddset the mover’smeldedto true. Each new meld they lay adds 1 toturnMelds: a take’s take meld when it is laid as a new meld, and each meld of a take’s or a lay’smelds.- A
takewhose take meld is added to an existing meld, and anaddto a meld that is not one of the lastturnMeldsmelds of the side (so one laid before this turn), setconcealedto false. lay,add, and atakewith a non-emptymelds, changequestionfromnotAskedtotooLate; any otherquestionstays. Atakewith nomeldsleavesquestionas it is.- A
discardthat passes the turn to seatnsetsconcealedto the opposite ofseats[n].melded,turnMeldsto 0 andquestiontonotAsked. - A move that empties the hand sets
turnStagetohandOverandwentOutto true (except adiscardthat does not go out while bonus cards are due, which passes the turn);turn,concealed,turnMeldsandquestionkeep their values, so the position still says how the player went out.
draw
The stock is empty → The stock runs out. Otherwise draw drawPerTurn cards
one at a time from the top of the stock. A laid-out three drawn is laid out
(appended to the seat’s redThrees, or blackThrees for a black one) and another card is drawn in
its place. If the stock is empty right after such a three is drawn, the hand ends at once (Pagat: the
player may not meld or discard): turnStage becomes handOver and wentOut stays false; with
stockEmpty lastThreeInHand that last three goes into the hand instead of being laid out. If the
stock runs out after any other card, the draw stops there. Otherwise turnStage becomes play.
take: the whole discard pile
Fields: method (naturalPair, naturalAndWild or addToMeld), cards (the hand cards used with
the top card), melds (more new melds from the hand, laid in the same move; usually the rest of an
opening; may be empty).
- The pile is empty →
pileEmpty. - The top card is wild or a black three →
pileBlocked. naturalAndWildwithdiscardPile.takeWithNaturalAndWildfalse, oraddToMeldwithdiscardPile.takeByAddingToMeldfalse →takeMethodNotAllowed.- The pile is frozen for everyone or against the mover’s side, and the method is not
naturalPair→pileFrozen. - A card of
cardsormeldsis not in the hand →cardNotInHand. cardsdoes not fit the method →takeCardsInvalid. Every card ofcardsmust be a natural of the top card’s rank or a wild, in any order; withnthe naturals among them,naturalPairneedsn≥ 2,naturalAndWildn= 1 and at least one wild, andaddToMeldno cards at all. All ofcardsgo into the take meld, as at a real table: taking KH with KS KD KC lays KH KS KD KC, and with KS KD 2C the mixed KH KS KD 2C. A frozen pile (step 4) is still taken only by the natural pair; wilds with it join the take meld. Only steps 8 and 10 limit the wilds:melds.maxWilds,melds.minNaturals,melds.wildsOnNaturalCanastawhen the take meld is added to a natural canasta, and the other wild checks of a new meld or an addition.addToMeldand the side has no meld of the top card’s rank →noSuchMeld.- The take meld is the top card followed by
cards. If the side holds a meld of the top card’s rank, the take meld is added to it (checked as an addition); otherwise it is a new meld, laid beforemelds(checked as a new meld). - Each of
melds, in order, is checked as a new meld. - A wild meld blocks other wilds →
wildMeldUnfinished. - The side has not opened → the initial meld minimum, then its required meld.
- Going out (a hand after below 2).
Then: the cards leave the hand; the take meld is added or laid, then melds, in order; the rest of
the pile (everything under the top card, face-down cards included) goes, in pile order, top first,
red threes to the seat’s redThrees and, with blackThrees.layOut, black threes to its
blackThrees (not replaced), and every other card to the end of the hand.
pile becomes empty and pileHidden 0. turnStage becomes play (or handOver).
With pileCardsCount: all, step 5 changes for melds only: each card of melds, in order, takes the
first copy left in the hand, else the first copy left in the rest of the pile (from the top, face-down
cards included), else → cardNotInHand. Cards taken from the pile this way go straight into the
meld: they never reach the hand, are not counted in “hand after”, and are not part of the rest of the
pile that goes to the hand. All of melds counts toward the minimum either way. cards always comes
from the hand. No rule set uses all yet, and no scenario pins it yet (one can, through a
scenario’s overrides).
lay: new melds from the hand
Field: melds, one or more card lists. An empty list → meldTooSmall. Then cardNotInHand; each
meld in order as a new meld; a wild meld blocking other wilds; if the side has not opened, the initial meld minimum (unless the hand
after has fewer than 2 cards, see Sides and melds) and its required meld; going out. The
melds are appended to the side’s melds, in order, each keeping its cards in the order given.
turnStage stays play (or becomes handOver).
add: cards onto an own-side meld
Fields: rank (the meld’s rank, or wild for the side’s wild meld) and cards. An empty cards →
meldTooSmall. Then cardNotInHand; no own-side meld with that rank (a rank of 2 or JK never
has one) → noSuchMeld; the addition checks; a wild meld blocking other wilds; going out. The cards are appended to the meld in the
order given.
discard
Field: card. Checked in this order:
- Not in the hand →
cardNotInHand. - If it is the last card, going out applies; otherwise, when
questionisyes→mustGoOut. While bonus cards are due, a last card whose going-out checks fail is discarded without going out: the hand stays empty until the talon joins it. - The card may not be discarded (Discardable cards): a laid-out three (red
or black; a red one is in a hand only as a kept three), with
blackThrees.layOut, from a hand that holds a card that is not a three →cannotDiscardThree; else a wild, withdiscards.wildgoingOutOrOnlyWilds, from a hand that holds a card that is neither wild nor such a black three →cannotDiscardWild; else a card held back on an empty pile (its rank is indiscards.onEmptyPile.ranks, or, withdiscards.onEmptyPile.dead, its rank is dead), on an empty pile, from a hand that holds another card that may be discarded →cannotDiscardOnEmptyPile.
The card goes on top of the pile. Then, if the discard went out, turnStage becomes handOver and turn
stays; otherwise the seat’s bonus cards are dealt when they are due, turn becomes
(seat + 1) % seats, that seat’s talon joins its hand, and turnStage becomes draw. Discarding a wild
freezes the pile (it stays face up in it); a black three only blocks the next take while it is on
top.
ask: “may I go out?”
No fields. The seat to play asks its partner whether it may go out (Pagat: right after drawing or taking the pile, before any other meld; the answer binds for the rest of the turn). After the checks every action starts with:
goingOut.askPartnerisnever→askNotAllowed.questionisasked,yesorno(partner was asked this turn) →alreadyAsked.questionistooLate→askTooLate.- The hand holds fewer than 2 cards →
askTooLate. Only atakecan leave one card atplay, and it was then already a going-out move; anowould leave that card with no legal move.
Then question becomes asked and turnStage answer; turn stays with the asker. Pagat lets a
player ask only when they can go out, but the engine does not check that here: a person asks only
when they can, and a bot only when its plan goes out (spec/bots.md). A yes to a player with no
way out does not bind, so an asker who cannot go out can still end the turn.
answer
Field: answer, yes or no, given by the asker’s partner (check 2 above). question becomes the
answer and turnStage play; turn is still the asker’s. A yes means the asker must go out this
turn, a no that it may not (see Going out).
declare: a special hand
No fields. The seat to play shows its whole hand as a special hand and ends the hand (Pagat: “you may make the first and only meld for your team by laying down your entire hand without a discard”). After the checks every action starts with:
- The mover’s side holds a meld →
specialHandAfterMeld. - The hand matches no entry of
specialHands.hands→noSpecialHand(always, with both rule sets’ emptyhands). questionisno→partnerSaidNo; elsegoingOut.askPartnerisrequiredandquestionis notyes→mustAskPartner.
Then turnStage becomes handOver and wentOut true; turn, the hand (face up now) and every
other field stay. So a hand is over by a declared special hand exactly when it is over with
wentOut true and the hand of turn is not empty. The declared hand is the matching entry with
the highest score, the first in file order on a tie. Only a seat that has drawn can declare: a take
lays a meld, so its side then holds one.
layOutThree: a kept three laid out
No fields; allowed at draw or play. The seat lays out the first laid-out three of its hand, a
kept three, and draws a replacement from the stock as in draw (a
replacement three is laid out and replaced too, never kept, and a three drawn as the stock’s last
card ends the hand). After the checks every action starts with: without specialHands.keepThree,
with no laid-out three in the hand, or with an empty stock → noKeptThree. turnStage, melded,
question and the other turn fields stay (laying a three is not a meld), except when the hand
ends.
Special hands
A hand matches a specialHands.hands entry when its cards, all of them, fall into groups of one
rank each, a different rank for each group (a joker’s rank is JK, a two’s 2, and threes of both
colours are 3), whose sizes are the entry’s groups in any order; no card is of a rank in
forbiddenRanks; and every rank of requiredRanks has a group. Put another way: the number of
cards of each rank the hand holds, sorted, equals groups sorted. Pagat’s four special hands are
hands of 14 cards, so they match only after the draw:
name |
Pagat | groups |
requiredRanks |
forbiddenRanks |
score |
|---|---|---|---|---|---|
straight |
One card of every rank: A-2-3-4-5-6-7-8-9-10-J-Q-K-joker | 14 × 1 | every rank | none | 3000 |
pairs |
Seven pairs, without wild cards, jokers or threes | 7 × 2 | none | JK, 2, 3 |
2500 |
pairsWithWilds |
Seven pairs with twos, sevens and aces, without jokers or threes | 7 × 2 | 2, 7, A |
JK, 3 |
2000 |
garbage |
Two fours of a kind and two threes of a kind, without wild cards or threes | 4, 4, 3, 3 | none | JK, 2, 3 |
2000 |
Pagat contradicts itself on sevens and aces in plain pairs: its example pairs hand is
“4-4-5-5-7-7-8-8-9-9-10-10-Q-Q”, with sevens, while its table rules say “Some players allow the pairs
hand to include sevens or aces but never threes or wild cards”. The rule set follows the example, so
pairs may hold sevens and aces (Eduardo’s choice, 2026-11-25); a hand that holds a pair each of
twos, sevens and aces matches pairsWithWilds too, and the higher score is declared.
Where Pagat is silent, these choices are the engine’s, confirmed by Eduardo on 2026-11-25:
- two groups never share a rank, so four nines are not two pairs;
- a hand matching several entries is declared as the highest
score, the first in file order on a tie; layOutThreeis refused with an empty stock (no replacement can be drawn);- a declare follows partner’s answer, like going out (refused after a “no”; needs a “yes” when asking is required). A special hand may hold cards of a dead rank (Pagat says so), and nothing checks one. Pagat’s table rules (a pair of jokers among the wilds, 3500 for pairs and garbage, garbage with two wilds, a 14th card from a one-card pile) are other entries or other values, and are not in the rule set.
Going out
A player goes out by emptying their hand: melding every card, or discarding the last one. With
goingOut.mustDiscard (Pagat’s Modern American; false in both rule sets) only the discard does: a
take, lay or add that leaves no card in the hand → mustDiscardToGoOut, after the meld and
opening checks and before the checks below, and the player keeps one card to discard. A going-out move is a take, lay or add
that leaves fewer than 2 cards in the hand, or a discard that leaves none, with one exception: while
bonus cards are due after it, a take, lay or add that leaves exactly one card is
not one (Pagat: the opening “entitles you to draw three or four bonus cards … and use those to
continue play”). It is checked, in this order:
- The mover’s side holds fewer than
canastasToGoOutcanastas (from thetables[]entry) after the move →cannotGoOut. So without enough canastas a player always keeps one card to discard and one to hold. questionisno→partnerSaidNo.goingOut.askPartnerisrequiredandquestionis notyes→mustAskPartner.
When question is yes, the player must go out while they can: a discard that keeps cards →
mustGoOut when the mover has a way out. Without one the discard is played as usual (the yes
lapses with the turn), so a yes never leaves the turn without a legal move.
A way out is a going-out add or lay by the mover that would succeed now, every check of
Moves passing, going out included. Only these candidates are tried, for each leftover
(no card, or any one card of the hand), with rest the hand without the leftover’s first copy, in
hand order; an empty rest gives no candidate:
- An
addof all of rest onto each own-side meld (rankits rank, orwildfor the wild meld). - A
layof rest sorted into melds bygroupMelds, with the side’s melds assideMelds: one meld per rank among rest’s naturals (black threes are rank 3), in the order of each rank’s first card in rest, holding that rank’s cards in hand order. Then each wild of rest, in hand order, joins the first of those melds open to a wild that holds fewer than 3 cards; else the first open to a wild; else it joins one wild meld, laid after the others (the only meld when rest holds no naturals).
Every candidate that would succeed and leaves the mover’s side canastasToGoOut canastas is a real
exit: it leaves at most one card, and discarding that card then goes out too. (The canastas matter
only while bonus cards are due: a candidate that keeps one card is legal then
without going out.) The candidates are not every way to go out: a hand that needs two moves (an
add, then a lay) has no way out until the first is played, so the yes binds once one move can
finish. scenarios/going-out/ pins both sides.
When the hand is empty, turnStage becomes handOver, wentOut true, and turn stays
on that seat.
Going out concealed (Pagat): the player melds their whole hand in one turn, had not melded earlier
in the hand, adds nothing to partner’s melds, and puts down at least one canasta of their own. Taking
the pile on that turn is allowed when its take meld is a new meld. In the position’s terms: the hand
is over with wentOut true, concealed is true, and one of the last turnMelds melds of the side of
turn is a canasta. It scores goingOut.concealedBonus in place of goingOut.bonus.
Bonus cards
With initialMeld.bonusCards (Pagat’s Modern American; null in both rule sets) the player who
makes their side’s opening and does not go out is dealt bonus cards after the turn’s discard. Pagat:
“If your team is the first to meld you draw four bonus cards; if the other team has already melded
you draw only three … You are not allowed to use these bonus cards in the turn in which you make the
initial meld. At the start of your next turn to play you add the bonus cards of your talon to your
hand, place any threes that you find in among them face up … and replace them”. In the position’s
terms:
- Bonus cards are due for the seat to play when
initialMeld.bonusCardsis set, it is the side’s opening turn (after the move being checked, for atake,layoradd) and the stock holds at leastminStockcards. Pagat’s turn card is the stock’sminStockth card from the bottom: once it is drawn, no bonus cards are dealt. - The opening may leave one card: a
take,layoraddafter which bonus cards are due and one card is left is not a going-out move; the player discards that card, and the discard does not go out unless its going-out checks pass (discard). - The talon. A
discardthat does not go out, played while bonus cards are due, dealsbonusCards.firstcards to the seat’sbonusCards, orbonusCards.secondwhen another side has a meld, one at a time from the top of the stock and in that order (as many as the stock holds). They are face down: no seat sees them, the player included, and Meldable and Discardable cards ignore them. - It joins the hand when the turn passes to the seat: its
bonusCardsare appended to the hand, in order, and emptied. Then each laid-out three among them, in that order, is taken out of the hand, laid out and replaced by drawing from the stock exactly as indraw: a laid-out three drawn as a replacement is laid out and replaced at once, and a three drawn as the stock’s last card ends the hand at once without going out (turnStagehandOver,wentOutfalse,turnthe seat; withstockEmpty: lastThreeInHandthat three stays in the hand). Once the stock is empty, or the hand has ended, the talon’s remaining threes are laid out unreplaced; with an empty stock the hand goes on, and the seat’sdrawthen finds the stock as it is. OtherwiseturnStageisdrawas usual. - A side that opens on a later turn than the first side gets
second; a third side (6 players) getssecondtoo. A seat that goes out on its opening turn gets none. - A hand that ends while a seat holds bonus cards counts them in
cardsInHandlike cards left in its hand (Scoring).
The stock runs out
With stockEmpty: handEndsWhenPlayerMustDraw (both rule sets, after Pagat), a draw from an empty
stock:
- →
mustTakePileif the take{ "method": "addToMeld", "cards": [], "melds": [] }by the same seat would succeed now (every check oftakepasses: the rule set allowsaddToMeld, the pile is not frozen, and its top card fits an own-side meld). This is Pagat’s compulsory take. Family rules never reach it (takeByAddingToMeldis false). - Otherwise the hand ends:
turnStagebecomeshandOver,wentOutstays false andturnstays. Nobody went out, so no side scores a going-out bonus.
While the stock is empty a player may still take the pile by any legal method instead of drawing, and
play goes on that way until someone draws. A laid-out three drawn as the last
stock card also ends the hand (see draw); it counts as a laid three. With stockEmpty
lastThreeInHand (Modern American, after Pagat) it stays in the drawer’s hand instead, so it counts
in cardsInHand: cardValues.blackThree points against, a red three as much as a black one.
Scoring
A hand is scored once it is over (turnStage handOver); before that, scoring → handNotOver. Each
side gets one row per line of the paper score sheet, all integers:
| Row | Points |
|---|---|
melds |
The card points of every card in the side’s melds; negated when meldsWithoutCanasta is subtract and none of the side’s melds is a canasta |
canastas |
The sum of the side’s melds’ canasta bonuses |
redThrees |
The threes row (red and black threes share it; Eduardo decided on 2026-11-25 to keep this key, and the apps label the row “Threes” where blackThrees.layOut is on and “Red 3s” elsewhere). With T(n) 0 when n is 0, otherwise the total of the redThrees.allTotals entry whose count is n, or n × each when no entry has that count: T(red) + T(black), with red and black the red and black threes laid out by the side’s seats (black is 0 without blackThrees.layOut). With redThrees.byCanastas it is negated for a side with no canasta, 0 for a side with exactly one, and kept for a side with two or more; otherwise it is negated when redThrees.negativeWithoutMeld is true and the side holds no meld |
goingOut |
For the side of turn, when wentOut is true: goingOut.concealedBonus if it went out concealed, else goingOut.bonus. 0 for every other side, and for all sides when the stock ran out |
cardsInHand |
Minus the card points of every card left with the side’s seats: in their hands and among their bonus cards (a red three left there, which only lastThreeInHand, bonus cards and a kept three leave, counting cardValues.blackThree), and minus the penalty of each cardsInHandPenalties entry for each of the side’s seats whose cards left hold count or more cards of the entry’s rank (0 or less) |
unfinishedCanastas |
For each of the side’s melds that is not a canasta: minus unfinishedCanastaPenalty, and minus the penalty of the first unfinishedMeldPenalties entry whose kind is the meld’s kind, whose rank is the meld’s rank (null for a wild meld) and whose minJokers is at most the meld’s jokers, if any entry matches (0 or less; 0 in both rule sets) |
total |
The sum of the six rows above |
A declared special hand (declare): the side of turn scores the
declared hand’s score in goingOut and 0 in every other row, total included the score (Pagat:
“the team that went out scores only the amount shown below for the special hand”); the hand is not
concealed. Every other side scores as usual.
The side’s new game score is its gameScore plus total, and its next minimum the
initial meld minimum for that score. The game is over when any side’s new game
score reaches the table’s gameTarget (≥, so exactly 5000 ends a 4-player game). Its winners
are the sides with the highest new game score, in side order: several on a tie (Pagat gives no tie
rule). While the game goes on there are no winners.
The next hand
Once a hand is over and the game is not, the next hand is dealt with the deal, by the
next dealer (dealer + 1) % seats, with the same players, so seat (dealer + 2) % seats plays
first (after dealer 3 of 4 players, seat 0 deals and seat 1 plays first); then each side’s
gameScore is its new game score. Before the hand is over → handNotOver; once the game is over
→ gameOver. The CLI shuffles hand h of a game (from 1) with new(seed, stream + h − 1), using
the newGame seed and stream (see protocol/cli.md). No scenario plays a next
hand (a scenario move has a seat); the behaviour suite and each core’s unit tests pin it.
For screens
Pure queries that the app screens and the CLI’s game node use, so no screen recomputes a rule. None of them changes a position or checks whose turn it is; the engine’s answer to a move still decides.
Hand order
How a hand is shown, never how it is held: the position’s hand keeps the order the player received
the cards, and moves name cards, not places. sortHand(cards, order) returns the cards in order, a
stable sort (cards with the same notation are interchangeable, so ties never matter):
| Order | Sorted by |
|---|---|
dealt |
Nothing: the cards as given |
rank |
Card order: rank index (JK, 2, A, K, Q, J, 10, 9 … 4, 3), then suit index (S, H, D, C) |
suit |
Suit key (JK 0, S 1, H 2, D 3, C 4), then rank index as for rank: jokers first, then each suit from its 2 down to its 3 |
parity/sort-hand.json pins all three.
Meldable cards
meldable(rules, state, seat) marks each card of the seat’s hand, in hand order, true when it can
go into a meld with the cards of that hand or onto an own-side meld, by shape alone. It is a hint for
highlighting: it does not check the turn, the initial meld minimum, or going out
(beyond the black-three rule below). With the own side’s melds, n(r) the hand’s naturals of rank
r that are not red threes (so n(3) counts black threes only), w the hand’s wilds, and
minNaturals and maxWilds from melds, and these terms:
- An own meld has room when its rank is not dead and it holds fewer than
melds.maxCardscards (null: always, dead ranks aside). - Blocked:
wildCanastas.blocksOtherWildsand the own side holds a wild meld of fewer than 7 cards. - wildsFor(r), the hand’s wilds a new meld of rank
rcould take: 0 whenris inmelds.naturalOnlyRanks, or blocked, or the own side has opened and eitherris inmelds.wildsOnlyInOpeningRanksorn(r)<melds.naturalsBeforeWildAfterOpening; otherwisemin(w, maxWilds). - A natural rank
rforms a meld when it is not dead,n(r)≥minNaturalsandn(r) + wildsFor(r)≥ 3.
With every new setting at its Classic/Family value, these read as before: every meld has room, nothing
is blocked and wildsFor(r) is min(w, maxWilds).
- A red three, and a black three with
blackThrees.layOut, is never meldable: no meld takes a laid-out three (notSameRank, Sides and melds). A hand in play never holds one (it is laid out at once), but a scenario position may (scenarios/meldable/red-threes-official.json,scenarios/meldable/black-threes-laid-out.json). - Otherwise a black three is meldable when the own side holds a meld of rank 3 that has room, or
n(3)≥blackThrees.minToMeldand, withblackThrees.meldOnlyWhenGoingOut, at most one card of the hand is neither a black three nor meldable by the rules here (so laying the threes with the hand’s other meldable cards could leave 0 or 1 card, the going-out case of the black-three check of a new meld). The other marks never depend on black threes, so this reads them first. - Any other natural, of rank
r, is meldable when the own side holds a meld of rankrthat has room, or holds none andrforms a meld. - A wild is meldable when any of these holds:
- the own side holds a meld with a rank other than 3 that has room, holds fewer than
maxWildswilds and is not a natural canasta (or is one andmelds.wildsOnNaturalCanastais true), while not blocked, its rank not inmelds.naturalOnlyRanks, holding a wild already when its rank is inmelds.wildsOnlyInOpeningRanks, and holding at leastmelds.naturalsBeforeWildAfterOpeningnaturals together with the hand’sn(r)(an add of those naturals and the wild is legal), with room undermelds.maxCardsfor the naturals it lacks and the wild; - the own side holds a wild meld of fewer than
melds.maxCardscards (null: any); - the hand holds a natural of some rank
rother than 3 with no own-side meld, with wildsFor(r) ≥ 1 andrforming a meld (son(r)≥ 1 even whenminNaturalsis 0: wilds with no natural make a wild meld, case 4). Each core’s unit testmeldableWildNeedsANatural(meldable_wild_needs_a_naturalin Rust) pins this withminNaturals0, which no rule set has; wildCanastas.allowed, the own side holds no wild meld, andw≥ 7 (mustBeLaidComplete) or ≥ 3 (otherwise).
- the own side holds a meld with a rank other than 3 that has room, holds fewer than
Equal cards are always marked alike. scenarios/meldable/ pins it under both rule sets.
Discardable cards
discardable(rules, state, seat) marks each card of the seat’s hand, in hand order, true when the
card checks of discard (step 3) let it be discarded now. Like the meldable marks it
does not check the turn, going out or mustGoOut. With h the hand and the pile empty when
pile holds no card:
- A laid-out three (a black three, or a red one), with
blackThrees.layOut, may be discarded only when every card ofhis a three (Pagat: threes are never discarded; a hand in play holds one only as a kept three, but a scenario position may). - A wild may be discarded unless
discards.wildisgoingOutOrOnlyWildsandhholds a card that is neither wild nor a black three barred by the rule above. So the last card always may be, and so may any card of a hand of only wilds (and black threes). - Then a card is held back when its rank is in
discards.onEmptyPile.ranks(a wild’s rank is2orJK), or whendiscards.onEmptyPile.deadistrueand its rank is dead:melds.closedRankisdeadand some side holds a natural canasta of that rank. A held-back card may be discarded unless the pile is empty andhholds another card (any other card ofh, an equal one included) that is not held back and that may be discarded by the two rules above (so a black three is never the other card, issue #214). So the only alternative is always discardable: some card of every hand is. - Every other card may be discarded.
Equal cards are always marked alike, and with both rule sets’ values every card is marked true.
The apps grey out the cards marked false while their player may discard (Beginner
aids is not needed). scenarios/discards/ pins the marks with overrides.
Beginner aids
A UI contract, the same on the web, the iPhone and Android (#99, #193). No core reads it and no scenario can pin it; each platform’s tests do (below).
The setting. One switch, Beginner aids, in Settings with Deck, Text size and Language. It is
off by default and per device: the web keeps it in homefelt.settings as "aids": true, the
apps under homefelt.settings.aids (true or false). Anything else, or nothing, reads as off.
It is never sent to the server. Under the switch, display.aids.detail says what it does.
What it turns on: the meldable marks. While aids are on, in a game on this device (solo or
hot-seat) or at an online table that allows them (below), the hand shown marks each card whose meldable mark is true, whenever
the hand is shown, with:
- The mark: a brass (
brass) disc 10 points across with a 1.5-pointonBrassoutline, 10 points below the card’s top (clear of a wild’s brass band) and 4 points in from the right edge of the strip the next card leaves showing (step), so it is never covered. A shape with an outline, never colour alone; the selected card’s ring and check stay as they are. - The legend: one line under the hand’s heading, the same disc followed by
hand.meldableLegend(“Can be melded”, the words a screen reader adds to a marked card; Eduardo, 2026-11-24), inonFeltat the label size. It shows whenever aids are on, marked cards or not, and wraps at large text instead of truncating. Screen readers read its words; the disc is hidden from them. - The screen-reader label: a marked card’s label is
card.meldableof its name (“Ace of spades, can be melded”); on the web a selected card’s iscard.meldableofcard.selected(“Ace of spades, selected, can be melded”).
With aids off nothing of this shows and no label changes.
Online (#194). Each player’s aids are their own: the switch stays on their device, and the
marks come from the meldable of their own seat view, which nobody else receives
(server.md “The seat view”). The host may turn aids off for the whole table,
when creating it or in the lobby (aidsAllowed, the aids host action); once the game starts the
setting is locked for the whole game (Eduardo, 2026-11-24). While it is off the server leaves
meldable out, so no client can show marks. A player with aids on at such a table sees, in the legend’s place,
online.aids.off (“The host has turned beginner aids off at this table.”), so they know why the
marks are gone; a player with aids off sees nothing. The host’s control is online.aids.title
(“Allow beginner aids”) with online.aids.detail under it, in the New table form and the lobby;
everyone else in the lobby, and everyone in the Table sheet during the game, reads online.aids.on
or online.aids.off instead. The
iPhone and Android apps have no online play yet: they carry these strings only.
Pinned by web/test/storageKeys.test.ts, web/e2e/aids.spec.ts and, online, web/e2e/online.spec.ts
and rust/canasta-server/tests/websocket.rs; swift/App/Tests/BeginnerAidsTests.swift
and UITests/BeginnerAidsUITests.swift; kotlin/app/src/test/.../BeginnerAidsTest.kt and
src/androidTest/.../BeginnerAidsUiTest.kt: off by default, kept across a restart, and the marks,
the legend and the labels shown with aids on and gone with aids off.
The coach
A UI contract for playing a tutorial, the same on the web, the iPhone and Android
(#196). The cores and the CLI protocol play the tutorial (protocol/cli.md);
the screens only show the game node’s tutorial key and send moves, so no screen knows a rule.
Each platform’s tests pin it (below).
Starting it. The new-game screen has a Learn to play button (tutorial.learn), under the
lead and above Continue, while the root lists a tutorial. It runs newTutorial with the first one
(canasta-first-hand). The web home page’s Canasta card has the same link, to /canasta/learn.
The first-launch offer. The first time the new-game screen shows on a device, a card at its top
offers the tutorial: tutorial.offer.title, tutorial.offer.detail, a Learn to play button
and Not now (tutorial.offer.later), which hides the card. While the card shows, the plain
Learn to play button does not. The card is not a dialog: it blocks nothing. The device remembers it
was offered as soon as it shows (or once a tutorial starts), where it keeps
Beginner aids: the web as "tutorialOffered": true in homefelt.settings, the
apps under homefelt.settings.tutorialOffered. Anything else reads as not offered yet.
A tutorial game on screen. While the game node’s tutorial is not null:
- The coach bubble sits between the felt and the hand, the width of the hand, and never covers
a card. Its heading is the tutorial’s
titlewithtutorial.stepCount(step+ 1 ofsteps). Its text is the step’scoach; while a computer seat is to act it istutorial.watchingand nothing is highlighted, since the step shown is already the person’s next one. It ends with a Skip tutorial button (tutorial.skip). At large text it wraps; the felt gives way. - The nudge. A move refused with
notTutorialStepshows no refusal card: the bubble addsrefusal.notTutorialStep.titleand.detailunder the coach text, after an icon (never colour alone), until the next move that runs. Any other refusal shows the usual card. - The highlight. Each of the step’s
highlighttargets gets a 3-point dashedbrassoutline, 3 points outside its edge: the stock, the pile, eachhandcard (the first unused card of the shown hand with that code, so twoKSmark two cards), the side’s meld of that rank, the action bar’s button for that action (alayoraddtarget is the Meld or Add button), and the hand’s score. Dashed, so it is a shape, never only a colour, and never mistaken for the selection’s solid ring. A target’s screen-reader label istutorial.lookHereof its usual label. - Screen readers and focus. When a new step starts for the person (its index changes and no computer seat is to act), focus moves to the first target (the score sheet at the last step) and the coach text is announced, after the target’s name where a focus change would cut it off (the iPhone). The nudge is announced when it shows.
- No time pressure. Nothing in the coach times out or moves on by itself. The computer seats’
scripted moves play one every 1500 ms (
tutorialDelay, against 700 ms in a game), so a person can follow them. - Not saved. A tutorial game is never written to the device’s saved game: the save of a real game stays as it was, and Continue offers it again once the tutorial is left.
- Leaving. Skip tutorial returns to the new-game screen with no game in play. The table’s New game button does not show.
- The end. Once the hand is over (the last step,
expectnull), the score shows as after any hand, highlighted, the empty hand and the action bar give way, and the bubble addstutorial.finish.leadand buttons in place of Skip: with Beginner aids off, Play with Beginner aids (tutorial.finish.withAids, turns them on) and Play without aids (tutorial.finish.withoutAids); with them on, Play a real game (tutorial.finish.play); and Not now, which leaves as Skip does. A real game is a new game of the tutorial’s rule set and player count, the person at seat 0 and Normal computers in the other seats, as the new-game screen deals by default.
Names on every platform: CoachBubble (the bubble), TutorialOffer (the card),
highlightedCards (the hand indexes the step points at), and NodeState’s newTutorial(id),
leaveTutorial(), playRealGame(), nudge and tutorialDelay; the stored key tutorialOffered.
Pinned by web/test/coach.test.ts and web/e2e/tutorial.spec.ts;
swift/App/Tests/CoachTests.swift and UITests/TutorialUITests.swift;
kotlin/app/src/test/.../CoachTest.kt and src/androidTest/.../TutorialUiTest.kt: the whole first
hand played through the screen to the score (520 to −170) and the end offer, the nudge on one wrong
move, Skip, and the offer shown once.
Selections
A person picks cards; these turn the pick into a move’s fields, the same way on every screen.
groupMelds(rules, sideMelds, cards)sorts the cards into new melds for alayby a side whose melds before the move aresideMelds, exactly as the way-outlaycandidate sorts rest (Going out, candidate 2): one meld per natural rank, in the order of each rank’s first card, each holding that rank’s cards in the order given; then each wild, in order, joins the first of those melds open to a wild that holds fewer than 3 cards, else the first open to a wild, else one wild meld laid after the others (the only meld when there is no natural). A meld is open to a wild when its rank is not 3 and not inmelds.naturalOnlyRanks, it holds fewer thanmelds.maxWildswilds, and fewer thanmelds.maxCardscards (null: any); whensideMeldsis not empty (the side has opened), also when its rank is not inmelds.wildsOnlyInOpeningRanksand it holds at leastmelds.naturalsBeforeWildAfterOpeningnaturals. No meld is open to a wild whenwildCanastas.blocksOtherWildsis on andsideMeldsholds a wild meld of fewer than 7 cards. No cards → no melds. Dead ranks and the opening minimum are left to the engine.takeSelection(rules, sideMelds, pileTop, cards)gives atake’smethod,cardsandmelds. Withrthe rank ofpileTopwhen it is a natural (none when the pile is empty or its top card is wild), and the naturals of rankramong the cards in the order given: 2 or more →naturalPairwith all of them, in that order; exactly 1 and a wild among the cards →naturalAndWildwith that natural and the first wild, in that order; otherwiseaddToMeldwith none.meldsisgroupMelds(with the samesideMelds) of the cards left oncecardsis taken out (the first copy of each, the rest keeping its order). Then, unless the method isaddToMeldorris inmelds.naturalOnlyRanks, a wild meld of fewer than 3 cards at the end ofmelds(wilds that join no natural meld and could never be laid on their own:meldTooSmall) leavesmelds, and its wilds are appended tocardsin their order, so they go into the take meld: KH with KS KD 2C givesnaturalPairwith KS KD 2C, laid as KH KS KD 2C. A wild thatgroupMeldsputs with other naturals stays there, and 3 or more wilds left over stay a wild meld. WithaddToMeldthe take holds no cards, someldsstays asgroupMeldsgives it.
Neither checks a rule: a selection that makes no legal move gets the engine’s error.
parity/group-melds.json and parity/take-selection.json pin them.
Rule error context
ruleErrorContext(rules, state, move, error) gives the numbers a refusal card shows, for a move
that apply refused with error in position state. It is an object holding only the keys
below; every other error (and a deal’s, nextHand’s or scoring’s) has none, {}. Whatever the
error, the context is also {} when the position fails Moves check 0, its table’s teams is
below 1, or the move has a seat outside 0 ..< seats, since the rows below read the table and the
mover’s side. No scenario reaches this (a runner never builds such a position, no rule set that
decodes has such a teams, and apply refuses such a seat with invalidSeat, whose context is
{} anyway), so each core’s unit test ruleErrorContextOnUnusablePosition (rule_error_context_on_unusable_position in Rust) pins every
case with cannotGoOut, whose context in a usable position is not empty; its teams 0 case gives
the position no sides, so that it passes check 0 and only the teams check can empty it. The keys:
| Error | Keys |
|---|---|
initialMeldTooLow |
minimum: the mover’s side’s initial meld minimum; points: the card points the move offered: every card of a lay’s melds, or a take’s top card, cards and every card of its melds (with initialMeld.pileCardsCount: none, its cards only when they form a meld by themselves, then every card of its melds) |
cannotGoOut |
minimum: the table’s canastasToGoOut |
tooFewNaturals |
minimum: melds.minNaturals |
tooFewBlackThrees |
minimum: blackThrees.minToMeld |
wildCanastaIncomplete |
minimum: 7 |
wildNotYet |
minimum: melds.naturalsBeforeWildAfterOpening |
Scenarios pin it with expect.errorContext (Scenarios); the CLI prints it as the rule
error’s context (protocol/cli.md).
Saved games
A game in progress (the game node’s state) written as JSON text, so
a solo game survives the app closing and a server table survives a restart (checkpoint 7, issue
#54). A resumed game continues exactly as the uninterrupted one would: the same deals and the
same computer moves. So a save holds everything the game node acts on, the computer players’ memory
included: the hand’s log, where Normal reads its signals, and
every seat’s random source as it is now, which Easy’s
discards draw from. Only two things are not in it: the rule set itself, named by its id, and
whether the game plays its computer seats at once (runsComputers, the loader’s choice).
Format, versions 1 and 2
Version 2 (issue #214) adds one key to every seat of position: blackThrees, the seat’s laid
black threes (Game state), required there. A writer writes version 1, without
blackThrees, when no seat holds a laid black three, and version 2 otherwise, so a game that
never lays one (every official and family game) saves exactly as before and older readers still
load it. A version-1 reader that met a version-2 save would refuse it cleanly
(unsupportedVersion) instead of losing the cards. A version-1 save loads with every seat’s
blackThrees empty, and a blackThrees key in it is ignored like any unknown key.
Version 3 (issue #222) adds two actions to the log: {"seat", "do": "declare", "pileTop"}, a
declared special hand, and {"seat", "do": "layOutThree", "pileTop"}, a
kept three laid out. A writer writes version 3 when the log
holds either, and versions 1 and 2 as below otherwise, so a game with neither saves exactly as
before. A version-3 save is read as a version-2 one; a reader takes a declare or layOutThree in any version’s
log (a writer puts one only in version 3).
Version 2 also holds a seat’s bonusCards, its face-down bonus cards (issue #215).
A writer writes version 2 when a seat holds a laid black three or bonus cards, and version 1
otherwise; in version 2 it writes every seat’s bonusCards when a seat holds bonus cards, and
leaves the key out otherwise, so a version-2 save written before #215 (which has none) is still
exactly what a writer writes. In version 2 a missing bonusCards reads as empty and a null one is malformed; a version-1 save
loads with every seat’s bonusCards empty and ignores the key.
One JSON object. Every key below is required. A reader ignores keys it does not know, so a later
version-1 writer may add one, and reads a repeated key as its last occurrence (Repeated
keys); a change that an older reader cannot ignore gets a new version. A
writer writes exactly these keys, in any order: saves are compared as JSON values, never as text.
| Key | Value |
|---|---|
format |
"canastaSave" |
version |
1, or 2 when a seat holds a laid black three or bonus cards, or 3 when the log holds a declare or layOutThree (above) |
ruleSet |
The rule set’s id |
seed, stream |
The game’s seed and stream (hand h is shuffled with new(seed, stream + h − 1)), as canonical decimal strings: "0" to "18446744073709551615", no sign, no leading zero. A server table’s seed uses all 64 bits, more than a JSON number keeps exact |
hand |
The hand being played, from 1 |
controllers |
One per seat, in seat order: human, easy or normal |
view |
all or hotSeat (Viewing) |
handOrder |
dealt, rank or suit (Hand order) |
sheet |
The score sheet rows of the hands already left with nextHand, oldest first: hand − 1 rows (the current hand’s row is never saved; it is scored again from position). Each is the game node’s scoreSheet row: {"hand", "dealer", "wentOut", "concealed", "sides"}, wentOut a seat or null, each side {"side", "melds", "canastas", "redThrees", "goingOut", "cardsInHand", "unfinishedCanastas", "total", "gameScore", "nextMinimum"} |
position |
The current hand’s position: a game state, every key, each meld {"cards"} |
log |
The current hand’s log, oldest first, every seat’s moves (human ones too): one entry per move that succeeded, {"seat", "do", …, "pileTop"}. do and the fields after it are the scenario move fields of its action (do is never bot; a take always has melds); pileTop is the pile’s top card before the move, or null when the pile was empty |
randoms |
One per seat, in seat order: the seat’s bot source as it is now, {"state", "inc"}: its PCG32 state and inc (Random numbers), each as 16 lowercase hex digits; inc is odd. The sources are made as botRandom(seed, stream + hand − 1, seat) when the hand is dealt and move on with every draw, so they are saved as they are, never re-made |
A path names a value: keys joined by ., array items as [i] from 0 (hand,
position.seats[0].hand[3], log[2].pileTop, sheet[0].sides[1].side, randoms[1].inc). A missing
key’s path is the path it would have.
Loading a text, with the loaded rule sets, checks in this order. The first failure is the error, with exactly the message shown:
- Not one strict JSON value (as the CLI’s
badJson, protocol/cli.md) →badJson, messagebadJson. - Not an object, or no
formatequal to"canastaSave"→notSavedGame, messagenotSavedGame. versionmissing, or not a signed 32-bit integer (Numbers;-0is not one) →malformed, messagemalformed: version. An integer other than 1, 2 or 3 →unsupportedVersion, messageunsupportedVersion: <n>(unsupportedVersion: 4).- Every other key, in the table’s order, depth first, array items in order (a position’s keys in
Game state order; a seat’s
hand,redThrees, in version 2blackThreesand (when present)bonusCards, thenmelded; a side’sgameScore,melds; a log entry’sseat,do, its action’s fields in the scenario move table’s order, thenpileTop; a sheet row’s keys and each side’s in the order above;state, theninc). The first value that is missing, of the wrong JSON type, an integer that breaks Numbers (signed 32-bit), a-0(not a canonical integer, so not one at all), a card that is not a card, a string that is not one of those listed (doone ofdraw,take,lay,add,discard,ask,answer,declare,layOutThree;method,rank,answeras in the scenario move table;turnStageandquestionas in Game state), aseedorstreamthat is not canonical decimal up to 2^64 − 1, astateorincthat is not 16 lowercase hex digits, an eveninc, ahandbelow 1, or apileHiddenorturnMeldsbelow 0 →malformed, messagemalformed: <path>. ruleSetis not theidof a loaded rule set →unknownRuleSet, messageunknownRuleSet: <id>.- Then, with
seatsthe length ofposition.seats→inconsistent, messageinconsistent: <path>, at the first of: the rule set has notables[]entry forseats(position.seats);position.sidesdoes not have that entry’steamsentries (position.sides); a meld with no cards (position.sides[<j>].melds[<k>].cards, the first in side then meld order: every meld holds at least one card);position.dealer, thenposition.turn, outside0 ..< seats;position.pileHiddenabove the pile’s length; the position’s cards (every seat’shand, then itsredThrees, then itsblackThrees, then itsbonusCards, then every side’s melds’cards, thenstock, thenpile, in that order) not the table entry’s deck (decksdecks of 54, Cards): the first card that is one copy more than the deck holds (its path,position.stock[12]: a duplicated or invented card), else fewer cards than the deck holds (position);position.turnMeldsabove the number of melds of the side ofturn, or above 0 atturnStagedraw;position.questionaskedat aturnStageother thananswer, other thanaskedatanswer, or other thannotAskedatdraw; the hand ofturnempty atturnStageplayoranswer(position.seats[<turn>].hand: the seat has to play and discard);controllers, thenrandoms, not of lengthseats; alog[i].seatoutside0 ..< seats;sheetnot of lengthhand − 1(sheet); then row by row, asheet[i].handother thani + 1, asheet[i].dealeroutside0 ..< seats, asheet[i].wentOutthat is notnulland outside0 ..< seats, asheet[i].sideswithoutteamsentries, asheet[i].sides[j].sideother thanj.
Otherwise the loaded game is the save as written, like a scenario position: nothing else is checked
(melds, the log against the position). A computer seat that still cannot act on such a position
stops with a rule error, never a crash (Computer seats). Its
sheet rows are hands that did not end the game (nextHand refuses once it is over), so each has
gameOver false and no winners. Loading what a core saved gives back the same game (load(save(game)) equals game, with the loader’s runsComputers), so it continues the
same; saving what a core loaded gives back the same JSON value. saves/ pins the second on every
core and parity/saved-games.json the first, against an uninterrupted game.
Spec files. Every *.json file directly in saves/ must load with the rule sets of
rulesets/ (runsComputers false), and saving the loaded game must give the file’s own JSON value
(a mismatch names the file). Each core’s unit test loadIgnoresUnknownKeys
(load_ignores_unknown_keys in Rust) adds a key extra at the top, in position and in a log
entry of one of them, and checks that it loads to the same game.
The game node’s seed and stream (protocol/cli.md) are the
save’s, so after a resume they may exceed maxSeed (a server table’s do); a JSON reader that keeps
numbers as doubles cannot read them exactly, and no screen shows them.
| Save error | When |
|---|---|
badJson |
The text is not one strict JSON value |
notSavedGame |
The value is not an object with format "canastaSave" |
unsupportedVersion |
version is an integer other than 1, 2 or 3 |
malformed |
A value is missing, of the wrong type or out of its range, including a version that is not an integer |
unknownRuleSet |
ruleSet names no loaded rule set |
inconsistent |
Values that do not fit together: the seats, sides, an empty meld, the position’s cards against the deck, the turn’s melds, question and hand against its stage, controllers, sources, log seats and score sheet rows |
Tutorials
A tutorial is a guided hand (issue #195): a deal stacked for teaching, against computer seats, where
a coach shows the person the next thing to do. One file per tutorial in tutorials/; the file name
is its id (canasta-first-hand). The computer seats never choose: they play the file’s scripted
moves, so a tutorial plays the same on every platform. The words come from design/strings/; the
file holds only their keys. The coach on screen (#196) reads the step from the game node
(protocol/cli.md).
Format
One JSON object. Every key below is required; a reader ignores keys it does not know.
| Key | Value |
|---|---|
title |
The strings key of the tutorial’s name |
ruleSet |
The id of the rule set it is played with |
seat |
The seat the person plays. Every other seat is a computer seat that plays the script |
start |
{ "deal": { … } }, a scenario’s seeded or stacked deal (Scenarios): players, dealer, and either stack (these cards on top of the stock, the rest of the decks in deck order) or seed and stream |
steps |
The steps, in order |
Each step:
| Key | Value |
|---|---|
coach |
The strings key of what the coach says |
highlight |
What the step points at: a list of targets (below), possibly empty |
expect |
The move the step expects of the person: a scenario move (seat, do and its fields; a take always has melds, as in a save’s log). null at the last step, and only there: the last step has nothing to do but read the score |
then |
The computer seats’ moves that follow expect, in order, each a scenario move; [] when the person plays on, and at the last step |
| Target | Points at |
|---|---|
{ "target": "stock" } |
The stock |
{ "target": "pile" } |
The discard pile |
{ "target": "hand", "cards": [cards] } |
These cards of the person’s hand |
{ "target": "meld", "rank": "A" } |
The person’s side’s meld of that rank (A, 3 to 10, J, Q, K), or wild for its wild meld |
{ "target": "button", "action": "lay" } |
The button of a game action: draw, take, lay, add, discard, ask or answer |
{ "target": "score" } |
The score sheet |
The script is every step’s expect (when not null) followed by its then, in step order. A
tutorial game plays nothing else: every move of its hand is the script’s next one.
Loading
Loading a tutorial’s text with the loaded rule sets checks, in this order. The first failure is the
error, with exactly the message shown; paths are written as in saved games
(steps[2].then[0].seat).
- Not one strict JSON value →
badJson. - Not an object →
malformed. - Every key of the format, in the tables’ order, depth first (a move’s keys in the scenario move
table’s order;
stackwhen the deal has it, elseseed, thenstream). The first value that is missing, of the wrong JSON type, a number that breaks Numbers (seedandstreamfrom 0 to 9007199254740991, every other one signed 32-bit), a card that is not a card, or a string that is not one of those listed (a target’starget,rankandactionas above; a move’sdo,method,rankandansweras in the scenario move table) →malformed: <path>. ruleSetis not theidof a loaded rule set →unknownRuleSet: <id>.- The deal fails →
start.deal: <rule error>(start.deal: cardNotInDeck). seatoutside0 ..< players→inconsistent: seat. No steps →inconsistent: steps.- Then the script is played from the deal, step by step. At each step, in the position where it
starts: an
expectthat isnullat a step other than the last, or notnullat the last →inconsistent: steps[<i>].expect; ahandtarget naming a card the person’s hand does not hold (each copy counts once) →inconsistent: steps[<i>].highlight[<j>].cards; ameldtarget with no such meld on the person’s side →inconsistent: steps[<i>].highlight[<j>].rank; anexpectwhoseseatis notseat→inconsistent: steps[<i>].expect.seat, and one the rules refuse →steps[<i>].expect: <rule error>; then eachthenmove byseat→inconsistent: steps[<i>].then[<j>].seat, and one the rules refuse →steps[<i>].then[<j>]: <rule error>. At the last step, once itsexpectis checked: a hand that is not over →inconsistent: steps[<last>](so a tutorial of one step, which plays nothing, fails too), and athenthat is not[]→inconsistent: steps[<last>].then.
So a tutorial that loads plays from its deal to the end of its hand, each step waiting for the
person (a computer seat still to act would refuse the next expect with notYourTurn).
Playing
With played the moves played since the deal (the game’s log length):
- The current step is the first step whose
expecthas not been played yet; once every one has, the last step. - The scripted move is the script’s move at index
played, or none once the script is over. - A move matches a step when the step has an
expect, the move is by the same seat with the samedo, and:drawandaskneed nothing more;discardthe same card;answerthe same answer;addthe samerankand the same cards, in any order;laythe same melds, in any order, each with the same cards in any order;takethe samemethod, the samecardsin any order and the samemeldsas alay’s. - Checking a move gives the current step’s
expectwhen the scripted move is thatexpect(the script waits for the person) and the move matches it; otherwise →notTutorialStep.
Every core has the same names: Tutorial.load(id, text, ruleSets), tutorial.deal(),
tutorial.currentStep(played), tutorial.scriptedMove(played), tutorial.checkMove(played, move)
and TutorialStep.matches(move) (in Rust Tutorial::load, current_step, scripted_move,
check_move). A tutorial game (protocol/cli.md) checks a person’s move
by the rules first, as any game does, and refuses it with that rule error; a legal move is then
checked against the step, and the step’s own expect is played, so the position is the script’s
whatever order the person picked the cards in.
The first hand
tutorials/canasta-first-hand.json plays the Family rules, the rule set the apps
start a new game with (the first one loaded and the first one the new-game screen offers), at 4
players: the person at seat 0 with partner seat 2, and dealer 3, so the person plays first. The
stack deals the hands one card per seat in turn, then the 4 hidden cards, the upcard and every card
drawn in the hand, round by round. The person draws, opens with three aces (60, over the minimum of
50), discards, draws again, adds an ace to the meld, and discards. Partner takes the pile with a pair
of eights, so the next pile is small. The person takes it with a pair of kings, adds two kings, a two
and a joker to make a mixed canasta, and discards. On the last turn the person draws, adds the last
ace (one card left: a going-out move, allowed with the canasta) and discards the last card to go
out; the last step shows the score: 520 for the person’s side (melds 250, canasta 300, going out
100, partner’s 18 cards −130) and −170 for the other. The steps’ positions were played on the Rust
engine and pinned in behaviour/tests/tutorial.test.ts; the score was also counted by hand.
Errors
A rule error is a string that scenarios expect and every core’s RuleError uses as its raw value.
A refused move also has a context with the numbers behind some of them.
| Error | When |
|---|---|
unsupportedPlayerCount |
The rule set has no tables[] entry for that many players (for a move, or the position’s sides do not match that entry’s teams) |
invalidSeat |
A seat number outside 0 ..< players |
cardNotInDeck |
A stacked stock names a card the decks do not hold (or hold fewer times) |
notYourTurn |
A move by a seat other than the seat to act: turn, or at turnStage answer the asker’s partner (see Moves, check 2) |
wrongTurnStage |
A move by the seat to act that its turnStage does not allow, including any move by turn once the hand is over |
stockExhausted |
The deal needs a card from an empty stock (see The deal) |
pileEmpty |
A take from an empty pile |
pileBlocked |
A take while the top card is wild or a black three |
takeMethodNotAllowed |
A take method the rule set does not allow |
pileFrozen |
A take of a frozen pile by a method other than a natural pair |
cardNotInHand |
An action names a card the hand does not hold (or holds fewer times) |
takeCardsInvalid |
A take’s cards do not fit its method |
noSuchMeld |
An add, or an addToMeld take, with no own-side meld of that rank |
meldTooSmall |
A new meld of fewer than 3 cards, or a lay or add with nothing in it |
notSameRank |
Naturals of different ranks (or a red three) in one meld, or a natural added to a wild meld |
rankAlreadyMelded |
A second meld of one rank, or a second wild meld, on one side |
tooManyWilds |
More than melds.maxWilds wilds in a meld, or any wild with black threes |
tooFewNaturals |
Fewer than melds.minNaturals naturals, or only wilds when wild canastas are not allowed |
wildOnNaturalCanasta |
A wild added to a natural canasta when melds.wildsOnNaturalCanasta is false |
wildCanastaIncomplete |
A wild meld of fewer than 7 cards when wildCanastas.mustBeLaidComplete is true |
meldFull |
A meld of more than melds.maxCards cards, laid or after an addition (a take onto a meld of 5 or 6 cards with maxCards 7) |
rankDead |
A new meld, or an addition, of a dead rank |
naturalOnlyRank |
A wild in a meld of a rank in melds.naturalOnlyRanks |
wildsOnlyInOpening |
A wild in a meld of a rank in melds.wildsOnlyInOpeningRanks laid after the opening, or added to such a meld laid without one |
wildNotYet |
After the opening, a wild in a meld holding fewer than melds.naturalsBeforeWildAfterOpening naturals |
wildMeldUnfinished |
A wild put into another meld while the side’s wild meld holds fewer than 7 cards, with wildCanastas.blocksOtherWilds |
tooFewBlackThrees |
A meld of fewer than blackThrees.minToMeld black threes |
blackThreesOnlyWhenGoingOut |
Black threes melded by a player who is not going out |
initialMeldTooLow |
An opening below the side’s minimum |
initialMeldNeedsNaturalMeld |
An opening with no meld free of wilds when initialMeld.requires is naturalMeld |
initialMeldNeedsNaturalOrWildMeld |
An opening with no meld free of wilds, and none of only wilds, when initialMeld.requires is naturalOrWildMeld |
cannotGoOut |
Emptying the hand, or keeping fewer than 2 cards, without enough canastas |
mustDiscardToGoOut |
A take, lay or add that empties the hand when goingOut.mustDiscard is true |
cannotDiscardWild |
A wild discarded from a hand that holds a card that is not wild, when discards.wild is goingOutOrOnlyWilds |
cannotDiscardOnEmptyPile |
A card of a discards.onEmptyPile.ranks rank, or with dead of a dead rank, discarded on an empty pile while another card of the hand may be discarded |
cannotDiscardThree |
A laid-out three discarded, with blackThrees.layOut, from a hand that holds a card that is not a three |
mustTakePile |
A draw from an empty stock when the pile could be taken onto an own-side meld |
askNotAllowed |
“May I go out?” when goingOut.askPartner is never |
alreadyAsked |
A second “may I go out?” in one turn |
askTooLate |
“May I go out?” after melding this turn, or with fewer than 2 cards in hand |
partnerSaidNo |
Going out after partner answered no |
mustAskPartner |
Going out without partner’s yes when goingOut.askPartner is required |
mustGoOut |
A discard that keeps cards after partner answered yes, while the mover has a way out |
specialHandAfterMeld |
A declare by a seat whose side holds a meld |
noSpecialHand |
A declare of a hand that matches no specialHands.hands entry |
noKeptThree |
A layOutThree without specialHands.keepThree, with no laid-out three in the hand, or with an empty stock |
handNotOver |
Scoring, or the next hand, before the hand is over |
gameOver |
The next hand once the game is over |
notTutorialStep |
In a tutorial game, a legal move that is not the current step’s (a computer seat’s move included), and nextHand once the hand is over |
Scenarios
One scenario per file, anywhere under scenarios/ (one folder per area, such as scenarios/deal/
or scenarios/pile/). Every *.json file found there, at any depth, is run by every core. A file
with a key this section does not list, at any level, fails, so a typo can never make a scenario
pass quietly.
{ "name": "Official: an unfrozen pile can be taken with one natural and one wild", "ruleSet": "official", "start": { "position": { "...": "a game state" } }, "moves": [ { "seat": 0, "do": "take", "method": "naturalAndWild", "cards": ["JK", "KC"] }, { "seat": 0, "do": "discard", "card": "9C" } ], "expect": { "turn": 1, "pile": ["9C"] }}-
name: what the scenario pins, as a sentence. -
ruleSet: theidof a file inrulesets/. -
overrides(optional): settings of that rule set changed for this scenario only, so a scenario can test a setting’s other value without a new rule set that players would see:"ruleSet": "family", "overrides": { "wildCanastas": { "mustBeLaidComplete": false } }. The runner readsrulesets/<ruleSet>.jsonas JSON and mergesoverridesinto it, key by key: where both hold an object at a key, the two objects merge the same way, at any depth; any other value (a number, string,true,false,nullor list) replaces the rule set’s value whole, so a list such astablesorinitialMeld.minimumsis given in full.{}changes nothing. Then:overridesthat is not a JSON object fails withoverrides: not a JSON object.- Every key of
overrides, at any depth, must be a field the rule set holds at that place (every rule set holds every field, see Rule sets). Any other key fails like an unknown scenario key, withunknown key overrides.<path>(unknown key overrides.wildCanastas.mustBeLaidCompleat). deckcannot be overridden, whatever the value (even the rule set’s own):overrides.deckfails withoverrides.deck: the deck cannot be overridden. A scenario never names a deck (Games); its deck is always its rule set’s.- The merged rule set is then loaded as a rule-set file is: the number checks of
Numbers, then the core’s production loader (the deck check, then decoding). When
it does not load, the scenario fails with
overrides: the rule set does not load: <message>, the message being the loader’s own, as for a file ininvalid/rulesets/.
Key and deck failures come before loading, and all of them are reported. Overrides belong to the scenario: no rule set file changes, and no player ever sees them.
-
start: exactly one ofdeal:players,dealer, and eitherseedandstream(a shuffled stock) orstack(a stacked stock). Run the deal.position: a game state, used as it is.
-
stack: these cards are the top of the stock, in order. The rest of the decks follow in deck order, each stacked card taking the first copy of itself out of them. -
moves: the moves to play after the start, in order. Each is an object withseat,do(the action) and exactly that action’s fields; anything else fails the scenario:
do |
Fields |
|---|---|
draw |
none |
take |
method, cards, and optionally melds (missing means []) |
lay |
melds: a list of card lists |
add |
rank (A, 3 to 10, J, Q, K, 2, JK, or wild) and cards |
discard |
card |
ask |
none |
answer |
answer: yes or no |
declare |
none |
layOutThree |
none |
bot |
level: easy or normal. The seat’s computer player chooses the action and the runner applies it |
-
botRandom(optional):{ "seed", "stream" }, the bot random sources: seatsusesbotRandom(seed, stream, s), made once before the first move. Missing: the seeded deal’sseedandstream, or 0 and 0 for any other start. -
The log. The runner keeps the log of the moves played, starting empty: every move that succeeds, scripted or
bot, appends{ seat, action, pileTop }. Abotmove callschooseAction(seatView(state, seat, log), rules, level, source[seat]). No action fails the scenario withbot: seat <n> is not the seat to act, and an action the core rejects fails it withbot action rejected: <error>, whateverexpectsays: a bot never makes an illegal move. -
expect: either{ "error": "<rule error>" }, optionally witherrorContext, or any of the keys below. Moves run in order and the first failure stops the run. Witherror, the run must fail with exactly that error at the last move (or at the start, whenmovesis empty); a failure anywhere earlier fails the scenario.errorContextis then compared exactly (the same keys, the same integers) withruleErrorContext(rules, state, move, error)for the last move and the position it was refused in (Rule error context); it needserror, a non-emptymovesand a last move that is notbot, or the scenario fails witherrorContext: needs error at a scripted move. Its keys areminimumandpoints, integers. Withouterror, the start and every move must succeed, and each listed key is compared exactly with the state after the last move:
| Key | Compared with |
|---|---|
turn |
The seat to play |
turnStage |
draw, play, answer or handOver |
hands |
{ "<seat>": [cards] }: each listed seat’s hand, in order |
handSizes |
{ "<seat>": n }: each listed seat’s hand size |
redThrees |
{ "<seat>": [cards] }: each listed seat’s red threes, in order |
blackThrees |
{ "<seat>": [cards] }: each listed seat’s laid black threes, in order |
bonusCards |
{ "<seat>": [cards] }: each listed seat’s face-down bonus cards, in order |
melds |
{ "<side>": [meld] }: each listed side’s whole meld list, in order; each meld is { "cards": [cards], "kind": "natural" | "mixed" | "wild", "isCanasta": bool, "bonus": n } (its canasta bonus), all four keys required |
pile |
The whole discard pile, top first |
pileHidden |
The face-down count |
pileFrozen |
Whether the pile is frozen for everyone (true or false) |
stock |
The whole stock, top first |
stockTop |
The first cards of the stock, top first |
stockCount |
The stock size |
question |
notAsked, tooLate, asked, yes or no |
wentOut |
true or false |
concealed |
true or false |
score |
{ "<side>": row }: each listed side’s hand score, with exactly the seven keys melds, canastas, redThrees, goingOut, cardsInHand, unfinishedCanastas, total |
gameScores |
{ "<side>": n }: each listed side’s new game score |
nextMinimums |
{ "<side>": n }: each listed side’s next minimum |
gameOver |
Whether the game is over (true or false) |
winners |
The winning sides, in side order ([] while the game goes on) |
botActions |
The actions the bot moves chose, in order, each in move format with seat (and never do bot; a take may leave out melds); compared as moves |
meldable |
{ "<seat>": [bool] }: each listed seat’s meldable cards, one per card of its hand, in hand order |
discardable |
{ "<seat>": [bool] }: each listed seat’s discardable cards, one per card of its hand, in hand order |
specialHand |
The name of the declared special hand, or null when none was declared |
score, gameScores, nextMinimums, gameOver and winners need the hand to be over: when it is
not, each of them that is listed fails the scenario with <key>: the hand is not over.
Seat and side keys (in hands, handSizes, redThrees, blackThrees, bonusCards, meldable, discardable, melds, score, gameScores
and nextMinimums) are canonical decimal strings ("0", "5"; not "01" or "+1") of seats or
sides that exist. seed and stream are integers from 0 to 9007199254740991; anything else fails
the scenario.
Numbers. In every spec file (decks, rule sets, scenarios, parity) a number is a JSON integer: no
fraction or exponent (4.0 and 4e0 fail), never quoted ("4" fails), and a true or false
is never a number. seed and stream range over 0 to 9007199254740991 (a savedGames case’s are
strings, as in a save: Parity), a pcg32 case’s bound
over 1 to 4294967295 and its outputs over 0 to 4294967295; every other number, a move’s seat
included, is a signed 32-bit integer (−2147483648 to 2147483647). A file that breaks this fails.
Repeated keys. A JSON object that repeats a key reads as if only the key’s last occurrence were
there, in every text a core’s production code reads: a rule set
(invalid/rulesets/duplicate-key-last-wins.json), a saved game
(invalid/saves/duplicate-key-last-wins.json) and a CLI request’s input
(protocol/cli.md). A reader that keeps the first occurrence, or refuses
the object, fails those files. No other spec file (decks, games, scenarios, parity) repeats a key, so
their test runners need not agree on one.
Expected values were derived from this document with a reference implementation (a
script that is not part of the repo); every scenario was replayed through it. The scoring rules follow
Pagat’s Classic Canasta (scoring, going out, the end of
the stock, the game target), and every score in scenarios/scoring/ was also counted by hand.
The meldable and errorContext values, and the sortHand, groupMelds and takeSelection parity
cases (issue #29), were derived from For screens with a script outside the repo, and
each new scenario’s moves were replayed through the Rust engine; the meldable hands were also
checked by hand. No external reference vector applies to them.
The saved-game files (checkpoint 7, issue #54: parity/saved-games.json, saves/ and
invalid/saves/) were made with a throwaway program over the Rust engine (rust/canasta-rules as of
this checkpoint, whose step-by-step games reproduce the logHash of parity/bot-games-*.json) and
a writer and loader written from Saved games. It checked that every state of each
savedGames game, saved and loaded, is the same state, and that each resumed game plays the same
steps; a second throwaway script, a loader written separately from this document, checked that every
saves/ file loads and every invalid/saves/ file fails with exactly its expected message. The
seed-18446744073709551615 savedGames case (issue #82) was made with a throwaway test over the Rust
engine, and the Swift and Kotlin cores reproduce its stepsHash and saved. No external reference
vector applies.
Parity
Each *.json file in parity/ is { "kind": "...", "cases": [...] }. Every core runs every case
and must match it exactly. A file of an unknown kind fails, and so does a case with a key its kind
does not list, or a seed, stream or bound outside the ranges in Numbers.
| Kind | Each case |
|---|---|
pcg32 |
name, seed, stream, and either next (the first outputs of next()) or bound with nextBounded (the first outputs of nextBounded(bound)), each from a fresh new(seed, stream) |
shuffle |
name, optionally deck (a deck id; missing means french, so the French cases name none), decks (how many copies), seed, stream, cards: decks copies of the deck’s canonical order, one after another, shuffled with new(seed, stream), top first. Every code of cards is read with the deck’s parser |
cards |
name, deck (a deck id), cards and notCards (lists of codes, either may be empty). Each code of cards must parse as a card of the deck and format back to the same code; no code of notCards may parse as a card of the deck (Card codes) |
deal |
A scenario whose start is a seeded deal, with no moves, whose expect holds turn, pile, pileHidden, stock, and hands and redThrees for every seat |
sortHand |
name, cards, order (dealt, rank or suit), sorted: sortHand(cards, order) (Hand order) |
groupMelds |
name, ruleSet, optionally overrides (merged into the rule set as in a scenario), optionally sideMelds (the side’s melds, each a list of card codes; missing: none), cards, melds: groupMelds(rules, sideMelds, cards) (Selections) |
takeSelection |
name, ruleSet, optionally overrides and sideMelds (as in groupMelds), optionally pileTop (missing: the pile is empty), cards, take: { "method", "cards", "melds" }, all three required, takeSelection(rules, sideMelds, pileTop, cards) (Selections) |
fnv1a64 |
name, text, hash: the FNV-1a 64 of the text’s UTF-8 bytes, 16 lowercase hex digits. The first three are the published vectors |
botGames |
name, ruleSet, players, seed, stream, levels (one easy or normal per seat), hands, moves (all hands), winners, gameScores (the final game score of each side), logHash, and optionally log (the log lines). The core plays the bot game and compares every listed field exactly; with log, a mismatch names the first line that differs |
savedGames |
name, ruleSet, players, seed and stream (canonical decimal strings, "0" to "18446744073709551615", as in a save; anything else fails with seed: out of range or stream: out of range), levels (one easy or normal per seat), saveAfter, steps, stepsHash, winners, gameScores, saved (a saved game object). saveAfter and steps are integers from 0 to 2147483647; a negative one fails, before any play, with saveAfter: out of range or steps: out of range. The core plays the game step by step, saves it after saveAfter steps, loads that save and plays on; see below |
botWinRate |
name, games (the path, under spec/, of a botGames file), minNormalWins. In every case of that file one side’s seats are all normal and the other side’s all easy; a game is a Normal win when its winners is exactly [that side]. Fewer than minNormalWins wins fails with minNormalWins: <wins> of <games> is below <min>; the runner prints the win rate either way |
Moves and scoring are pinned by scenarios, including some that start from a seeded deal
(scenarios/turns/seeded-family-draw-discard.json, and the whole hands in
scenarios/scoring/seeded-full-hand-*.json); whole games are pinned by the bot games.
parity/bot-games-*.json hold 50 games per rule set (4 players, seed i, stream 0, Normal on side
i % 2) and parity/bot-game-sample.json one of them with its whole log. parity-long/ has the
same layout with 1,000 games per rule set: every runner reads parity-long/**/*.json too, but only
when the environment variable CANASTA_PARITY_LONG is 1 (CI runs it nightly and on demand).
Every core must find at least one parity/ file of each kind.
Decks in parity cases. In a shuffle or cards case, after the unknown-key and number checks:
a cards case with no deck fails with deck: missing; a deck that is not one of the strings
french, spanish-40 and spanish-48 fails with deck: not french, spanish-40 or spanish-48 (a
shuffle case with no deck is french, but "deck": null is a deck that is not one of the
strings, not a missing one, as in a rule set); a code of cards that the deck’s parser refuses fails
with cards[<i>]: "<code>" is not a <deck> card (<i> from 0, <deck> the id), and one that formats as
another code with cards[<i>]: "<code>" formats as "<other>"; a code of notCards that parses fails
with notCards[<i>]: "<code>" is a <deck> card. A runner reports every such failure of a case, in
that order, not only the first. A shuffle case with any such failure stops there; otherwise it
shuffles and compares its cards, code for code, with the shuffled pack.
The Spanish shuffle cases (issue #134) were derived with a throwaway script outside the repo that
implements PCG32, the shuffle and the canonical order above. The
same script first reproduced the published pcg32-demo vector, every case of parity/pcg32.json and
both French cases of parity/shuffle.json byte for byte. A second, separately written script
reproduced every parity/pcg32.json case, every case of both shuffle files, each decks/ file’s
order from its ranks, suits and jokers, and every parity/cards.json case. No published
reference vector exists for a Spanish deck. The cards cases list every code of each deck’s order
and non-codes chosen by hand.
Saved games, step by step. A savedGames case starts the game node like newGame with
ruleSet, players, dealer 0, seed, stream, controllers = levels, view all, and computer
seats left to the runner (runsComputers false). A step is one of: while the hand is not over,
the computer seat to act plays one action (the game node’s stepComputer, as in
Computer seats), logged as the line <seat> <action text> with the
action text of bots.md; once the hand is over and the game
is not, nextHand, logged as the line nextHand. The game ends when a hand is over and the game is.
stepsHash is the FNV-1a 64 of the lines, each followed by (as logHash). The runner, in
this order, failing at the first mismatch:
- Plays the whole game. Its step count,
stepsHash,winnersand finalgameScores(each side’s new game score after the last hand) must be the case’s (steps: <got>, expected <want>, and so on). saveAfterabove the step count fails withsaveAfter: beyond the game's <steps> steps.- The save of the game after
saveAftersteps, parsed, must equalsavedas a JSON value (the same keys, the same values, arrays in order): elsesaved: does not match. - Loads that text with every rule set in
rulesets/(runsComputersfalse); a failure fails withload: <message>. Saving the loaded game must give the same JSON value: elsesaved: does not round-trip. - Plays the loaded game on to its end. The first
saveAfterlines of step 1 followed by these lines (the resumed lines,<n>of them in all) must be exactly step 1’s lines. The runner compares them line by line as far as both go: the first line that differs fails withresumed: line <i> differs, counting from 0. If every compared line matches but the counts differ (the resumed game ends early or plays on longer), it fails withresumed: <n> steps, expected <steps>. Last, the save of the last state must equal the save of step 1’s last state (resumed: final save differs).
So every core proves, in its own game, that save → load → continue is the uninterrupted game, and
saved and stepsHash prove that all three agree. parity/saved-games.json saves in the first
hand, at the end of a hand before nextHand, in hand 3 with two sheet rows, with 6 players, right
after the deal (each save point but those two boundaries chosen where both forgetting the log and
re-making the sources would change the moves that follow, issue #54), and at seed and stream
18446744073709551615 late in hand 1, so that the resumed game deals hand 2 with stream + 1
wrapping to 0 (issue #82).
Invalid files
invalid/ holds files that break one rule of this document each, so every runner proves it rejects
them: invalid/rulesets/ (each must fail to decode as a rule set), invalid/scenarios/ (each must
fail as a scenario), invalid/parity/ (each must fail as a parity file), invalid/tutorials/ (each must fail to
load with the rule sets of rulesets/, with exactly the expected message) and invalid/saves/ (each
file’s text, as it is, must fail to load with the rule sets of rulesets/; the
expected text is the whole message, such as malformed: log[0].pileTop). Nothing else reads them.
invalid/app-status/ is checked by bin/test app-status, and invalid/ads/ (placement files) and
invalid/purchases/ (entitlement caches) by bin/test ads; their texts are those checkers’
messages, and the platforms only check that their parser returns nothing for each file
(spec/ads, spec/purchases).
invalid/expected.json maps each file’s path under invalid/ to a piece of text that every
runner’s failure message contains, so the three fail the same way; "" (only for rule sets) means
any decoding failure. A rule set that breaks the deck check has an exact entry
(deck: missing, deck: canasta is not played with spanish-40), since every core words those
failures itself. For invalid/saves/ it is the whole message, and every runner compares it
exactly (malformed: hand must not pass for malformed: handOrder). A file missing from expected.json, or an entry with no file, fails the test.
Family readings (confirmed in #8)
Issue #8 asked the family to confirm these readings of
the Family rules table; Eduardo confirmed all four on 18 Nov 2026. family.json and the scenarios
encode them.
- Black threes (rows 20, 21): 4 black threes are needed to meld them, only when going out
(
blackThrees.minToMeld: 4); each is worth 5 points. - The cut (rows 23, 26): 4 face-down cards go into the pile under the first upcard; a wild or red three upcard stays and another card is turned on top. Whoever takes the pile also takes the 4 hidden cards (into the hand; a red three among them is laid out and not replaced).
- 6-player target (row 25): 7,500, the official target for 3 teams of 2.
- Wild-card canastas (row 13): a meld of only wilds must be laid as a complete canasta of 7
(
wildCanastas.mustBeLaidComplete: true;falsewould let it start from 3 cards and grow). It is exempt from row 11’s 3-wild limit, counts as a canasta for going out, and takes more wilds once laid; an exact-mix bonus then applies only while the counts match exactly (8 wilds score the default 2,000). A side holds at most one wild meld.
scenarios/scoring/family-real-hand.json is a placeholder: an invented but realistic Family hand.
Replacing it with a hand from a real family game, scored on paper, is the phase 1 gate.
Behaviour tests
behaviour/ tests what a person can see and do, on every platform, with no simulator or device.
Each platform builds a CLI that speaks the CLI protocol; the same TypeScript tests
run unchanged against all three, on bun test.
cd spec/behaviourCANASTA_CLI=../../rust/target/debug/canasta-cli bun test # one platformbun run test:swift # or test:kotlin, test:rust: build that CLI first (protocol/cli.md)bun run test:wasm # the Wasm build in-process: run bin/build-wasm firstbun run test # all four, one after anotherCANASTA_CLInames the CLI binary, absolute or relative tospec/behaviour. The SDK starts it as<binary> --spec <repo>/spec, one process per test, inside the network guard.sdk/cli.tsis the SDK:sessionstarts a CLI and closes it (it must exit with status 0);precondition(node, check)pollslsuntil the focused node isnodeandcheckholds;do(action, input, node, check)runs an action that must succeed, then waits the same way;refused(action, input, kind, code)runs one that must fail with exactly that error. Polls arelsrequests, at mostPOLLSof them, never sleeps; a check fails by returning false or throwing (a failedexpect).sdk/guard.tsis the network guard andsdk/probe.tsthe connection it must refuse (to 192.0.2.1, a TEST-NET-1 address that RFC 5737 reserves for documentation, so it never reaches anyone).CANASTA_TARGET=wasm(test:wasm) runs the same tests against the Wasm build of the Rust core (rust/canasta-wasm, loaded bysdk/wasm.ts) instead of a CLI process: the SDK feeds each line it would write to stdin toSession.handleand queues the response as if printed, and closing frees the session (a trap fails it, like a nonzero exit). Two checks are about the process, so they differ: instead of “the CLI runs inside the network guard”, the Wasm run checks that the module imports nothing but wasm-bindgen’s glue (no WASI, no host functions that could reach a network); “the guard refuses a connection” is skipped there (it starts no process to guard), and the run reports1 skip.- Every
*.test.tsfile underbehaviour/tests/is a test file. A test must pass on all three CLIs and on Wasm; never skip one per platform (the guard test above is the one exception: no process, no guard). Tests find actions by name and read seats and hands from the state. - The seeds and hands the tests play (
tests/expected.ts) were derived from this document with the same reference implementation as the scenarios; up to checkpoint 3 it also ran the whole suite against a reference CLI of the protocol. The checkpoint 4 tests’ moves, refusals and next-hand deal were replayed through the reference engine, not a reference CLI.tests/deal.test.tsreusesparity/deal.jsonas it is, and works out each dealt card’shandPointsandmeldablemark from the rule set (after a deal no side holds a meld, so only the hand’s own counts matter). tests/play.test.tsplays deal → draw → lay an opening meld → discard, plus a scripted round of all four seats.tests/hand.test.tsplays a whole hand: it replaysscenarios/scoring/seeded-full-hand-family.jsonas it is (its moves, then its expected score as the score sheet), deals the next hand, and walks the “may I go out?” flow.tests/view.test.tschecks the viewing seat, hot-seat hiding,sortHandand each shown card’s points and meldable mark (protocol/cli.md “Viewing”); its hands were derived with the same reference script as themeldablescenarios.tests/tutorial.test.tsplaystutorials/canasta-first-hand.jsonfromnewTutorialto the score: at every step it checks the game node’stutorialkey against the file and the position againsttests/expected.ts(firstHandSteps,firstHandScore), then plays the step’sexpect. It also pins the refusals: the rules’ own first (wrongTurnStage,handNotOver), thennotTutorialStepfor a legal move that is not the step’s, and a step’s meld accepted with its cards in another order.