Authoring a game: the shape of the code
package mygame
import (
"errors"
"github.com/PipGrylls/CIG2"
)
const Name = "my-game"
type Game struct{} // no fields: shared by every table
var _ cig2.Game = (*Game)(nil)
var _ cig2.ActionHinter = (*Game)(nil)
func init() { cig2.RegisterGame(Name, &Game{}) }
type state struct {
Scores map[cig2.PlayerID]int
}
func (g *Game) Setup(s *cig2.Session, players []cig2.PlayerID, config any) error {
deck := s.NewDeck("deck", cig2.Hidden())
s.Root().AddChild(deck)
// … add cards with s.NewCard(&Card{…}), deck.Shuffle(s.Rand()) …
s.SetState(&state{Scores: map[cig2.PlayerID]int{}})
s.SetTurn(cig2.NewTurnTracker(players))
return nil
}
func (g *Game) HandleAction(s *cig2.Session, p cig2.PlayerID, a cig2.Action) error {
st := cig2.MustStateOf[*state](s)
switch a.Name {
case "play":
// 1. Validate everything — return errors here only.
if !s.Turn().IsCurrent(p) {
return errors.New("not your turn")
}
// 2. Then mutate. No error returns after the first change.
st.Scores[p]++
s.Turn().Advance()
return nil
}
return errors.New("unknown action")
}
func (g *Game) CheckEnd(s *cig2.Session) (bool, cig2.Result) {
// Notice every way the game can end.
return false, cig2.Result{}
}
func (g *Game) LegalActions(s *cig2.Session, viewer cig2.PlayerID) []cig2.ActionHint {
// The same predicate HandleAction validates with.
if s.Turn().IsCurrent(viewer) {
return []cig2.ActionHint{{Name: "play"}}
}
return []cig2.ActionHint{}
}Tools you will want
| You need | Use |
|---|---|
| per-table data | s.SetState, cig2.MustStateOf[*T] |
| per-seat secrets shown only to that seat | s.SetPlayerState + GameState(s, viewer) |
| whose turn | cig2.NewTurnTracker, s.Turn() |
| phases and rounds | cig2.NewPhaseMachine, OnEnter, NeedsInput |
| “after any change, check X” rules | s.SetSettle |
| a timeout or a delayed action | s.Schedule, s.Rearm (timer-only actions check a.FromTimer()) |
| ask one seat to choose | s.Ask(cig2.Question{…}) |
| collect one submission per seat | cig2.Collector |
| a zone by ID with its type | cig2.MustFindZoneAs[*cig2.Hand](s, id) |
| a card by UUID | s.FindCard(uuid) |
| config with defaults and validation | cig2.DecodeConfig[Config](config) |
| static card tables | content.MustLoad[T](fsys, path) |
| a standard 52-card deck | deck52 |
| a server | host.Run(ctx, host.Config{…}) |
cig context cheatsheet has every signature, and cig context patterns covers what not to write.