Getting started: implementing Snap

This walks through building Snap as a second CIG2 game, using only the framework as it exists today (.claude/SPEC.md, and everything under the repo root). Nothing here requires touching framework code — that’s the promise games/highcardduel already proves, and this guide leans on it as the worked reference throughout.

Step 0 is a complete, real, tiny example — build and run it before touching Snap at all. Every step after that describes Snap’s own decisions and code in prose; it does not write Snap’s implementation for you.

0. The smallest thing that compiles and runs

Before wrestling with Snap’s actual rules, build something trivial end to end, so the mechanical parts — Game, a zone, a card, an action, a snapshot — are already familiar by the time they show up wrapped in real game design. This section is a complete, working Game. Nothing about it is Snap-specific; forget it once the shape has sunk in.

Create games/_warmup/game.go. The leading underscore is load-bearing: Go tooling (go build ./..., go test ./...) silently skips any directory starting with _ or ., so this scratch package never has to be cleaned up or excluded from anything — delete the whole directory whenever you’re done with it.

package warmup

import (
	"fmt"

	"github.com/PipGrylls/CIG2"
)

// Coin is the only payload this warm-up needs: one field, one meaning.
type Coin struct {
	Face string `json:"face"` // "heads" or "tails"
}

func (*Coin) PayloadTag() string { return "coin" }

// Game is the smallest legal cig2.Game: one Public zone, one card, one
// action that mutates it, one end condition.
type Game struct{}

var _ cig2.Game = (*Game)(nil)

type state struct {
	flipped bool
}

func (g *Game) Setup(s *cig2.Session, players []cig2.PlayerID, _ any) error {
	s.SetState(&state{})
	table := s.NewDisplay("table", cig2.Public())
	s.Root().AddChild(table)
	table.Add(s.NewCard(&Coin{Face: "heads"}))
	return nil
}

func (g *Game) HandleAction(s *cig2.Session, player cig2.PlayerID, action cig2.Action) error {
	if action.Name != "flip" {
		return fmt.Errorf("warmup: unknown action %q", action.Name)
	}
	card := cig2.MustFindZoneAs[*cig2.Display](s, "table").Cards()[0]
	coin := card.Payload.(*Coin)
	if s.Rand().IntN(2) == 0 {
		coin.Face = "heads"
	} else {
		coin.Face = "tails"
	}
	cig2.MustStateOf[*state](s).flipped = true
	return nil
}

func (g *Game) CheckEnd(s *cig2.Session) (bool, cig2.Result) {
	return cig2.MustStateOf[*state](s).flipped, cig2.Result{Reason: "flipped"}
}

// Name is this game's registered name. It doubles as the namespace every
// payload and zone tag registers under, so your tags can never collide with
// another game's — see Step 3.
const Name = "warmup"

func init() {
	cig2.RegisterPayload(Name, "coin", func() cig2.CardPayload { return &Coin{} })
	cig2.RegisterGame(Name, &Game{})
}

That’s a real Game: it builds a zone tree in Setup, mutates a card’s payload in place in response to an action, and ends itself in CheckEnd. Nothing hidden, no turns, no second player even required to hold state — deliberately, so the only new ideas are the four framework touchpoints themselves.

Now prove it runs, without writing a server or a browser page — a session driven directly over real channels, the same pattern (at trivial scale) every game’s integration test uses later:

package warmup

import (
	"testing"
	"time"

	"github.com/PipGrylls/CIG2"
)

func TestWarmup(t *testing.T) {
	s := cig2.NewSession("t1", &Game{}, []cig2.PlayerID{"p1"})
	conn := cig2.NewChanConn(4)
	if err := s.Attach("p1", conn); err != nil {
		t.Fatal(err)
	}
	if err := s.Start(); err != nil {
		t.Fatal(err)
	}
	defer s.Stop()

	<-conn.Messages() // the opening snapshot; ignored here

	s.Submit("p1", []byte(`{"action":"flip"}`))

	select {
	case raw := <-conn.Messages():
		// Decoding needs the game's name: payload tags are namespaced per
		// game, so the decoder has to know whose "coin" this is. A bare
		// json.Unmarshal deliberately fails here with a message saying so.
		snap, err := cig2.UnmarshalSnapshot(raw, Name)
		if err != nil {
			t.Fatal(err)
		}
		t.Logf("snapshot after flip: %s", raw)
		if !snap.Over {
			t.Fatal("expected the round to be over after one flip")
		}
	case <-time.After(time.Second):
		t.Fatal("timed out waiting for a snapshot")
	}
}

Run: go test ./games/_warmup/ -run TestWarmup -v

Expected: it passes, and -v prints the raw snapshot JSON — a real ZoneView for "table", holding one CardView whose payload.face is "heads" or "tails", exactly as filtered by Filter for a real player. That JSON is the same shape everything from here on produces; Snap just has more zones and more decisions behind them.

Delete games/_warmup/ (or keep it around as a scratch reference — either is fine, it was never wired into anything) and move on.

1. Decide the ruleset before writing anything

Snap has more real variation than High Card Duel, and the framework can’t make these calls for you — pin them down first, the same way the project’s own brainstorming process insists on resolving ambiguity before code:

  • Player count. Classic Snap scales to a group; start with 2 to keep the first version small, the same choice High Card Duel made.
  • Turn structure. Real Snap is played in real time with no turns — anyone can play or snap whenever. That’s a legitimate design, but it removes the natural fit with TurnTracker. The simpler on-ramp: turn-based play (one player plays a card on their turn), with “snap” available to any player at any time regardless of whose turn it is. Decide which you’re building — the rest of this guide assumes turn-based play with an out-of-turn snap.
  • What “snap” checks. Two consecutive top cards matching by rank is the classic rule. Decide now whether suit ever matters, whether a false snap (called with no match) penalizes the caller, and what happens if two players snap in the same instant (the session’s actor model already serializes this for you — whoever’s action the session processes first wins; decide if that’s the rule you want or if you need an explicit tie-break).
  • Win condition. Common choices: the game ends when one player holds every card, or when a player runs out of cards to play. Pick one; CheckEnd needs an unambiguous answer.

Write these decisions down somewhere durable (a short design note, even a comment block) before you touch any of the steps below — every step after this assumes you’ve already made them.

2. Create the package

games/snap/
  cards.go
  game.go
  game_test.go
  integration_test.go

This mirrors games/highcardduel/ exactly. package snap, imports github.com/PipGrylls/CIG2. Nothing under games/ is imported by the framework — the only relationship is the other direction (RegisterGame in init(), covered in Step 7), which is what makes “adding a game never touches framework code” true.

3. Define the card payload

CardPayload is a one-method interface (PayloadTag() string), and the framework never looks inside it — the whole payload is what gets dropped when a card must be opaque. Look at games/highcardduel/cards.go’s PlayingCard/StandardDeck() for the shape: a small struct with exported, JSON-tagged fields, a PayloadTag() method, and a RegisterPayload call in init().

Don’t import highcardduel.PlayingCard to reuse it, even though Snap needs an identical 52-card deck. Define your own type in games/snap, registered under its own tag (e.g. "snap_card", not "playing_card"). Games are meant to be independent, self-contained plugins — cross-game imports create exactly the coupling the “adding a game never touches framework code” rule exists to prevent. Yes, this means duplicating a 52-card deck definition; that duplication is precisely what the project’s already-planned (but not yet built) DX/distribution layer exists to remove later, by making a standard deck a shared, versioned Go module instead of something copy-pasted per game. Don’t try to solve that yourself here.

This is not a hypothetical warning — it’s a real bug this exact guide predicted and a real draft of Snap then hit anyway: an early cards.go for Snap registered its payload under RegisterPayload("playing_card", ...) — the same tag highcardduel already owns.

That specific collision only exists because games/highcardduel and games/snap currently live in the same repo, as neighbors, easy to blank-import together — this repo is CIG2’s own development monorepo, holding the framework plus its example games for convenience, not the shape a real game ships in. A genuinely separate game — its own repo, its own module, importing only github.com/PipGrylls/CIG2 — would never see this particular pairing; there’s no highcardduel in its dependency tree to collide with.

The underlying constraint is still real for a real deployment, for a different reason: payloadRegistry is one table per Go process, not per repo. It’s shared by whatever set of packages a given binary happens to blank-import — which is exactly one game today (your own demo), but would be more than one the moment anybody builds a server hosting several independently-authored CIG2 games at once (a lobby, an arcade — a legitimate use of the framework, not a monorepo artifact). Two unrelated authors independently reaching for the obvious tag name "playing_card" is exactly the kind of coincidence that only surfaces once someone combines their games, with no warning beforehand. Pick a tag distinctive to your game now, and it’s a non-issue whenever that happens.

4. Design the zone tree

Every zone in CIG2 has a visibility mode, and this is where Snap’s actual gameplay logic starts. Map it out before writing Setup:

  • Root — a Group, Public(), created automatically by NewSession. You add children to it via s.Root().AddChild(...).
  • Per-player draw pile — a Deck (s.NewDeck), cig2.Hidden(). This is the single most important visibility choice in the whole game: Hidden means nobody, including the owning player, can see their own pile’s order. That’s exactly the fog of war Snap depends on — a player who could peek ahead in their own pile would trivially always win.
  • The shared discard/snap pile — a Pile (s.NewPile), cig2.Public(). Every card played onto it is visible to everyone, which is what lets every player judge whether to snap.
  • Optional per-player area — a Group wrapping each player’s pile, the same way High Card Duel groups a hand inside an “area” zone. Purely organizational; use it if you want a place to nest UI-relevant zones later.

No new zone type is needed — Deck, Pile, Group already exist and already carry their compile-time interface assertions (var _ DeckZone = (*Deck)(nil), etc., in deck.go/pile.go/group.go). If some later variant of Snap genuinely needs a new zone shape, zone.go and group.go are the templates to copy: embed cardZone, write a ZoneTag() and LoadZone, register it with RegisterZone, and add the compile-time assertion right next to the type — that assertion is not optional boilerplate, it’s the direct fix for the exact bug (Deck.AddCard silently drifting from DeckZone) that motivated this whole project.

5. The critical gotcha: don’t copy High Card Duel’s Reveal() call

This is the one place a straight copy of the reference game will quietly break Snap, and it’s worth understanding why before you write HandleAction.

High Card Duel calls card.Reveal() because its cards need to become visible while still sitting in an OwnerOnly zone — reveal is exactly the mechanism for “show this despite the zone’s own rule,” and it’s sticky by design: once revealed, a card stays revealed forever, in every zone it later passes through (see .claude/SPEC.md §3 and filter.go’s filterCard, where c.Revealed() is checked before the zone’s mode, and overrides even Hidden).

Snap’s discard pile is already Public — every card on it is visible to everyone with no Reveal() call needed at all, because Public mode shows real identity unconditionally. So don’t call Reveal() when a card is played onto the discard pile. If you do, here’s the leak it causes: when a player later wins a snap and that same card moves into their own Hidden personal deck, its sticky Revealed flag would keep showing its identity to every opponent, permanently — silently defeating the entire fog of war the Hidden deck exists to provide, and letting opponents count cards. Reveal is one-way by design (card.go, Reveal() — “there is deliberately no method that un-reveals a card”), so once that mistake is made there is no fixing it from inside a single round; it can only be avoided by not making the call.

The rule to carry forward: call Reveal() only for a card whose identity must survive re-entering a stricter zone than the one it’s currently visible from. If a card’s visibility is fully explained by the zone it’s sitting in, don’t touch Revealed at all.

5.1 The mirror mistake — and why it’s the more dangerous one

Everything above warns against calling Reveal() when you don’t need it. The opposite mistake is just as easy, and it fails far more quietly.

“Don’t call Reveal() unless you have to” leads naturally to: this card is already face-up where it is, so moving it doesn’t need a Reveal(). That reasoning is correct only when the destination is Public. Move that same card into a Hidden zone and it doesn’t just become opaque — it disappears from the wire entirely. Filter’s ModeHidden case (filter.go) drops a non-Revealed card from ZoneView.Cards completely, emitting only a count. A card you just legally played face-up is now indistinguishable from the zone’s genuinely face-down cards: still correct in the domain model, still counted, but unrenderable and gone from every future snapshot.

Nothing catches this. Not go build, not go vet, not domain-model unit tests — the card is where you put it, so any test asserting on zones and counts passes. It only surfaces if you assert on filtered wire output for a card that changes zones after being played face-up. This is not hypothetical: a real game built on CIG2 (Klondike, moving a card from the Public waste onto a Hidden tableau column) shipped exactly this bug, and only the integration test caught it.

So the complete rule has two halves:

Moving a card does not carry its visibility with it — only the sticky Revealed flag travels. A card that was visible at its source because that zone was Public needs a fresh Reveal() if it must stay visible in a stricter destination.

Concretely, for the three destination modes:

Moving a face-up card into…Need Reveal()?
PublicNo — the zone shows everything unconditionally
OwnerOnlyYes, if non-owners must still see it
HiddenYes — otherwise it vanishes from the wire completely

6. Actions

Two actions, both flat {"action": "...", "data": {...}} envelopes handled in one HandleAction switch, exactly like High Card Duel’s single-case switch on "reveal":

  • "play" — the acting player draws from their own Deck (Draw(), which errors on an empty deck via the exported ErrEmptyDeck) and moves it onto the shared pile (s.Move(card, pile)). If you chose turn-based play, validate whose turn it is first (s.Turn().IsCurrent(player)) and advance afterward (s.Turn().Advance()) — TurnTracker is provided by the framework specifically so you don’t hand-roll this (game.go, NewTurnTracker/IsCurrent/Advance).
  • "snap" — any player, any time. Read the pile’s current cards (pile.Cards() returns a copy; the two most recent are the last two elements, since Pile.Add appends and Top() returns the last one). Compare ranks. On a match, move every card in the pile onto the calling player’s deck (s.Move in a loop) — this is the reverse of Step 5’s concern, so the same rule applies: don’t call Reveal() on the way in. On a non-match, return an error (or apply whatever penalty you decided in Step 1) — HandleAction returning an error rejects the action and reports it to that player only, per game.go’s documented contract; the board is untouched for everyone else.

Store per-round state (whose turn it is doesn’t need this — TurnTracker lives on the session already — but anything else you need, like a penalty counter) via s.SetState/s.State(), never as a field on your Game struct. Game is registered once and shared by every concurrent session (game.go’s doc comment on the Game interface says this explicitly) — a field on the struct would leak state between unrelated tables.

7. Setup, CheckEnd, registration

Setup(s *Session, players []PlayerID, config any) error builds the tree from Step 4, deals the shuffled deck evenly between the two per-player Deck zones (Shuffle(s.Rand()) before or after the split — s.Rand() is test-seedable via cig2.WithRand, which is how game_test.go-style tests get deterministic deals), and calls s.SetTurn(cig2.NewTurnTracker(players)) if you’re doing turn-based play.

CheckEnd(s *Session) (bool, Result) checks your Step 1 win condition against whatever you stored via SetState, and returns cig2.Result{Winners: ..., Reason: "..."} — same shape High Card Duel uses.

Register in init():

func init() {
    cig2.RegisterGame("snap", &Game{})
}

That’s the entire integration point. Nothing in the framework — nothing under the repo root, nothing in registry/ — needs to change for Snap to exist. The only thing that needs to know Snap exists is whatever main package blank-imports it (see Step 9).

8. Test it the way this project insists on

Per .claude/SPEC.md §9 and CLAUDE.md’s ground rules, two layers, both required — a game whose only proof is unit tests is exactly the situation that let the predecessor project’s dealing bug ship silently:

  • Unit tests (game_test.go) for the rules: Setup deals the right counts to the right zones with the right visibility; "play" rejects the wrong player’s turn; "snap" accepts a real match and rejects a non-match; CheckEnd fires on your chosen win condition. Model these on games/highcardduel/game_test.go.
  • One real end-to-end integration test (integration_test.go) that spins up an actual *cig2.Session with real ChanConns over real channels, plays a full round through real Submit calls, and asserts on the raw bytes each player received — not decoded structs. The warm-up’s TestWarmup in Step 0 is this same pattern at the smallest possible scale; copy the fuller recorder/waitForSnapshot pattern from games/highcardduel/integration_test.go for the real thing. It exists specifically because decoded-struct assertions have a blind spot (a custom UnmarshalJSON can silently discard a leaked field before any assertion sees it — this project shipped that exact bug once and only caught it via mutation testing). At minimum, assert that a card sitting in a player’s Hidden deck never appears with identity on the wire before it’s played, and — this is Snap’s version of the Step 5 gotcha — that a card reclaimed into a personal deck after a snap stops carrying identity on the wire from that point on. If you skip that second assertion, a Reveal() mistake from Step 5 will pass every other test in the suite and ship anyway.

9. Make it playable

Copy cmd/cig2-demo into cmd/snap-demo — a host.Config plus host.Run, under 70 lines, with the page in an embedded static/index.html. Only the game name, seats and the page change. That touches no framework code. Wherever you do it:

  • Blank-import games/snap so its init() runs: _ "github.com/PipGrylls/CIG2/games/snap".
  • host.Server.Mount already serves the browser toolkit (web.FS) at /cig2/, alongside /events, /action and /reset.
  • Write the page against <cig2-table>/<cig2-board> — start with <cig2-board> for zero-config rendering, and read web/AGENTS.md before writing anything by hand. It documents the full styling vocabulary, the three layers for drawing a card (CSS attributes → <template> → a registered render function), and the one authoring rule worth repeating here because it applies directly to Snap: pick one style per table — don’t mix a <cig2-board> with hand-placed <cig2-zone> elements for the same zone ID, or they’ll silently fight over the same card element.
  • Register a render function for your payload tag (registerCard('snap_card', ...)) and wire data-cig2-action="play" and data-cig2-action="snap" onto two buttons. The toolkit forwards exactly what you declare and never validates an action itself — illegal moves come back as a cig2-error event from the server’s rejection, the same way High Card Duel’s demo handles it.

10. Before calling it done

Run the same gates this project holds every change to:

go build ./... && go vet ./... && gofmt -l .
go test ./...
go test -race ./...

Then actually play a full round through a real browser — two windows, two seats — and confirm, by reading the raw-snapshot panel (or your own equivalent), that: your own deck never shows card order or identity, your opponent’s deck is the same, the discard pile shows real identities to everyone, and — the check that matters most for Snap specifically — a card you’ve reclaimed via a snap goes back to being invisible to your opponent. That last one is the integration test’s job too, but seeing it with your own eyes is what this project’s post-mortem calls “the specific layer of testing that was missing” the first time around.