feat(game): official first-move tile draw + admin step-by-step replay
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 17s
CI / ui (pull_request) Has been skipped
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m19s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 17s
CI / ui (pull_request) Has been skipped
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m19s
Decide who moves first by the official rule: each seated player draws one tile, the one closest to "A" leads (a blank beats every letter), ties re-drawing until a single leader remains. Each draw uses honest per-draw crypto/rand entropy (not the deterministic bag seed), so the recorded draw — not a seed — is the only account of the outcome. The leader takes seat 0, so the engine and journal replay are unchanged. The draw is recorded with the game (game_setup_draws, migration 00013) for future tournaments, designed as a discrete "player N draws a tile" step. Friend/AI games draw at creation. Auto-match draws when the game opens, against a synthetic uuid.Nil opponent whose draw rows (NULL account_id) are back-filled to the real opponent on join — so the opener's seat is fixed up front and the existing open-game pre-move is preserved with no reseating. Admin /_gm/games/:id gains the recorded draw list and a simple step-by-step board replay (game.ReplayTimeline + a vanilla-JS stepper): a board with A-O/1-15 headers and highlighted premium squares, placed letters with their tile value as a subscript, rack panels around the board (seat 0 top, 1 bottom, 2 left, 3 right) with the current player highlighted, and a per-move log with the tiles drawn and the bag remainder. Docs: ARCHITECTURE §6/§9, FUNCTIONAL (+_ru), PRERELEASE (FM row), design spec.
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/engine"
|
||||
)
|
||||
|
||||
// ReplayStep is one step of an admin game replay: the move that produced it (nil for the
|
||||
// initial dealt state, step 0) and the resulting position — every seat's rack, the running
|
||||
// scores, whose turn it is and the bag remainder. Step k's board is the union of every
|
||||
// play's placements through step k, which the renderer accumulates onto an empty grid
|
||||
// (docs/ARCHITECTURE.md §9.1 visual replay).
|
||||
type ReplayStep struct {
|
||||
// Move is the journalled move that produced this state, or nil for the initial deal.
|
||||
Move *HistoryMove
|
||||
// Drawn lists the tiles the mover drew from the bag after this move ("?" for a blank);
|
||||
// empty for the initial deal, a pass or a resignation.
|
||||
Drawn []string
|
||||
// Racks holds every seat's rack at this step, indexed by seat ("?" for a blank).
|
||||
Racks [][]string
|
||||
// Scores holds every seat's running score, indexed by seat.
|
||||
Scores []int
|
||||
// ToMove is the seat to move at this step.
|
||||
ToMove int
|
||||
// BagLen is the number of tiles left in the bag at this step.
|
||||
BagLen int
|
||||
}
|
||||
|
||||
// ReplayTimelineView is the admin replay of a game: the persisted game plus the ordered
|
||||
// replay steps (the initial deal followed by one step per journalled move).
|
||||
type ReplayTimelineView struct {
|
||||
Game Game
|
||||
Steps []ReplayStep
|
||||
}
|
||||
|
||||
// ReplayTimeline rebuilds a game from its pinned seed and journal and returns the ordered
|
||||
// replay steps for the admin console: the initial deal (step 0) then one step per
|
||||
// journalled move, each carrying the resulting racks, scores, turn cursor, bag size and the
|
||||
// tiles the mover drew. The deterministic bag makes the reconstruction exact. It needs no
|
||||
// dictionary beyond the engine the seed deals, and — like the live replay — stops early if a
|
||||
// committed move became illegal under tightened rules rather than failing.
|
||||
func (svc *Service) ReplayTimeline(ctx context.Context, gameID uuid.UUID) (ReplayTimelineView, error) {
|
||||
pre, err := svc.store.GetGame(ctx, gameID)
|
||||
if err != nil {
|
||||
return ReplayTimelineView{}, err
|
||||
}
|
||||
seed, err := svc.store.GameSeed(ctx, gameID)
|
||||
if err != nil {
|
||||
return ReplayTimelineView{}, err
|
||||
}
|
||||
g, err := engine.New(svc.registry, engine.Options{
|
||||
Variant: pre.Variant,
|
||||
Version: pre.DictVersion,
|
||||
Players: pre.Players,
|
||||
Seed: seed,
|
||||
DropoutTiles: pre.DropoutTiles,
|
||||
MultipleWordsPerTurn: pre.MultipleWordsPerTurn,
|
||||
})
|
||||
if err != nil {
|
||||
return ReplayTimelineView{}, err
|
||||
}
|
||||
moves, err := svc.store.GetJournal(ctx, gameID)
|
||||
if err != nil {
|
||||
return ReplayTimelineView{}, err
|
||||
}
|
||||
steps := make([]ReplayStep, 0, len(moves)+1)
|
||||
steps = append(steps, snapshotStep(g, nil, nil))
|
||||
for i := range moves {
|
||||
mv := moves[i]
|
||||
before := g.Hand(mv.Seat)
|
||||
if err := replayMove(g, mv); err != nil {
|
||||
if errors.Is(err, engine.ErrIllegalPlay) {
|
||||
g.Abort()
|
||||
break
|
||||
}
|
||||
return ReplayTimelineView{}, fmt.Errorf("game: replay-timeline %s move %d: %w", gameID, mv.Seq, err)
|
||||
}
|
||||
moveCopy := mv
|
||||
steps = append(steps, snapshotStep(g, &moveCopy, drawnTiles(before, g.Hand(mv.Seat), usedTiles(mv))))
|
||||
}
|
||||
return ReplayTimelineView{Game: pre, Steps: steps}, nil
|
||||
}
|
||||
|
||||
// snapshotStep captures the position after applying move (nil for the initial deal): every
|
||||
// seat's rack and score, the turn cursor and the bag size, with the supplied drawn tiles.
|
||||
func snapshotStep(g *engine.Game, move *HistoryMove, drawn []string) ReplayStep {
|
||||
n := g.Players()
|
||||
racks := make([][]string, n)
|
||||
scores := make([]int, n)
|
||||
for i := 0; i < n; i++ {
|
||||
racks[i] = g.Hand(i)
|
||||
scores[i] = g.Score(i)
|
||||
}
|
||||
return ReplayStep{Move: move, Drawn: drawn, Racks: racks, Scores: scores, ToMove: g.ToMove(), BagLen: g.BagLen()}
|
||||
}
|
||||
|
||||
// usedTiles returns the rack tiles a move consumed ("?" for a blank): the placed tiles of a
|
||||
// play or the swapped tiles of an exchange; a pass or resignation consumes none.
|
||||
func usedTiles(mv HistoryMove) []string {
|
||||
switch mv.Action {
|
||||
case "play":
|
||||
used := make([]string, len(mv.Tiles))
|
||||
for i, t := range mv.Tiles {
|
||||
if t.Blank {
|
||||
used[i] = "?" // a placed blank leaves the rack as the blank marker
|
||||
} else {
|
||||
used[i] = t.Letter
|
||||
}
|
||||
}
|
||||
return used
|
||||
case "exchange":
|
||||
return mv.Exchanged
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// drawnTiles returns the tiles the mover drew from the bag: the post-move rack (after) minus
|
||||
// the tiles kept (before minus used). It compares the racks as multisets, so duplicate
|
||||
// letters are counted correctly.
|
||||
func drawnTiles(before, after, used []string) []string {
|
||||
kept := make(map[string]int, len(before))
|
||||
for _, t := range before {
|
||||
kept[t]++
|
||||
}
|
||||
for _, t := range used {
|
||||
if kept[t] > 0 {
|
||||
kept[t]--
|
||||
}
|
||||
}
|
||||
var drawn []string
|
||||
for _, t := range after {
|
||||
if kept[t] > 0 {
|
||||
kept[t]--
|
||||
continue
|
||||
}
|
||||
drawn = append(drawn, t)
|
||||
}
|
||||
return drawn
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"scrabble/backend/internal/engine"
|
||||
)
|
||||
|
||||
func TestUsedTiles(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mv HistoryMove
|
||||
want []string
|
||||
}{
|
||||
{"pass", HistoryMove{Action: "pass"}, nil},
|
||||
{"resign", HistoryMove{Action: "resign"}, nil},
|
||||
{"play with blank", HistoryMove{Action: "play", Tiles: []engine.TileRecord{{Letter: "a"}, {Letter: "b", Blank: true}}}, []string{"a", "?"}},
|
||||
{"exchange", HistoryMove{Action: "exchange", Exchanged: []string{"a", "?"}}, []string{"a", "?"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := usedTiles(tt.mv); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("usedTiles = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDrawnTiles(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
before, used []string
|
||||
after []string
|
||||
want []string
|
||||
}{
|
||||
{"play refill", []string{"a", "b", "c", "d"}, []string{"a", "b"}, []string{"c", "d", "e", "f"}, []string{"e", "f"}},
|
||||
{"blank played", []string{"?", "a"}, []string{"?"}, []string{"a", "x"}, []string{"x"}},
|
||||
{"pass keeps rack", []string{"a", "b"}, nil, []string{"a", "b"}, nil},
|
||||
{"duplicate letters", []string{"e", "e", "e"}, []string{"e"}, []string{"e", "e", "q"}, []string{"q"}},
|
||||
{"empty bag no refill", []string{"a", "b"}, []string{"a"}, []string{"b"}, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := drawnTiles(tt.before, tt.after, tt.used); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("drawnTiles = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/engine"
|
||||
)
|
||||
|
||||
// maxSeedingRounds caps the first-move draw's tie re-draws. With a real bag a tie
|
||||
// breaks with positive probability each round, so this is reached only by a
|
||||
// degenerate (e.g. test) entropy source that ties forever; the cap turns that into
|
||||
// an error instead of an infinite loop.
|
||||
const maxSeedingRounds = 1000
|
||||
|
||||
// SetupDraw is one recorded tile draw of the first-move seeding — one row of
|
||||
// game_setup_draws (docs/ARCHITECTURE.md §6, §9): the round, the draw order within
|
||||
// it, the seated account that drew, and the decoded tile with its rank. It is
|
||||
// dictionary-independent: the letter, the blank flag and the numeric rank describe
|
||||
// the draw without any alphabet table.
|
||||
type SetupDraw struct {
|
||||
Round int
|
||||
PickNo int
|
||||
Account uuid.UUID
|
||||
Letter string
|
||||
Blank bool
|
||||
Rank int
|
||||
}
|
||||
|
||||
// seedingResult is the outcome of the first-move seeding: the winning account, the
|
||||
// seated accounts rotated so the winner leads (seat 0), and the full draw log to
|
||||
// persist.
|
||||
type seedingResult struct {
|
||||
winner uuid.UUID
|
||||
order []uuid.UUID
|
||||
draws []SetupDraw
|
||||
}
|
||||
|
||||
// drawIntn returns a uniformly random integer in [0, n) for n > 0. It is the
|
||||
// entropy seam of the first-move seeding: production uses crypto/rand (cryptoIntn),
|
||||
// so every draw is honestly random with no single seed; tests inject a
|
||||
// deterministic source.
|
||||
type drawIntn func(n int) (int, error)
|
||||
|
||||
// cryptoIntn draws a uniform integer in [0, n) from crypto/rand — the honest,
|
||||
// seedless entropy the first-move draw requires.
|
||||
func cryptoIntn(n int) (int, error) {
|
||||
v, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("game: first-move draw entropy: %w", err)
|
||||
}
|
||||
return int(v.Int64()), nil
|
||||
}
|
||||
|
||||
// seedFirstMove runs the official first-move draw over accounts for variant v,
|
||||
// drawing tiles with the entropy source intn. Each round every contender draws one
|
||||
// tile (without replacement) from a fresh full bag; the tile closest to "A" wins, a
|
||||
// blank beating every letter; contenders tied for the best tile re-draw in the next
|
||||
// round until a single leader remains. It returns the leader, the rotation that
|
||||
// seats the leader first (preserving the others' seating order), and every draw for
|
||||
// the record. It performs no I/O beyond calling intn.
|
||||
func seedFirstMove(v engine.Variant, accounts []uuid.UUID, intn drawIntn) (seedingResult, error) {
|
||||
if len(accounts) < 2 {
|
||||
return seedingResult{}, fmt.Errorf("game: first-move seeding needs at least 2 accounts, got %d", len(accounts))
|
||||
}
|
||||
full, err := engine.SetupBag(v)
|
||||
if err != nil {
|
||||
return seedingResult{}, err
|
||||
}
|
||||
contenders := append([]uuid.UUID(nil), accounts...)
|
||||
var draws []SetupDraw
|
||||
for round := 1; ; round++ {
|
||||
if round > maxSeedingRounds {
|
||||
return seedingResult{}, fmt.Errorf("game: first-move seeding unresolved after %d rounds", maxSeedingRounds)
|
||||
}
|
||||
bag := append([]engine.SetupTile(nil), full...)
|
||||
picks := make([]engine.SetupTile, len(contenders))
|
||||
for i, acc := range contenders {
|
||||
tile, rest, err := drawSetupTile(bag, intn)
|
||||
if err != nil {
|
||||
return seedingResult{}, err
|
||||
}
|
||||
bag = rest
|
||||
picks[i] = tile
|
||||
draws = append(draws, SetupDraw{
|
||||
Round: round, PickNo: i, Account: acc,
|
||||
Letter: tile.Letter, Blank: tile.Blank, Rank: tile.Rank,
|
||||
})
|
||||
}
|
||||
winners := bestContenders(contenders, picks)
|
||||
if len(winners) == 1 {
|
||||
return seedingResult{winner: winners[0], order: rotateToFirst(accounts, winners[0]), draws: draws}, nil
|
||||
}
|
||||
contenders = winners
|
||||
}
|
||||
}
|
||||
|
||||
// drawSetupTile removes one uniformly random tile from bag using the entropy source
|
||||
// intn and returns it with the shrunk bag (a fresh slice, leaving bag untouched).
|
||||
// It is the per-tile draw primitive — the seam a future manual "player N draws a
|
||||
// tile" tournament API will drive, one call per external request.
|
||||
func drawSetupTile(bag []engine.SetupTile, intn drawIntn) (engine.SetupTile, []engine.SetupTile, error) {
|
||||
if len(bag) == 0 {
|
||||
return engine.SetupTile{}, nil, fmt.Errorf("game: first-move draw from an empty bag")
|
||||
}
|
||||
i, err := intn(len(bag))
|
||||
if err != nil {
|
||||
return engine.SetupTile{}, nil, err
|
||||
}
|
||||
if i < 0 || i >= len(bag) {
|
||||
return engine.SetupTile{}, nil, fmt.Errorf("game: first-move draw index %d out of range %d", i, len(bag))
|
||||
}
|
||||
tile := bag[i]
|
||||
rest := make([]engine.SetupTile, 0, len(bag)-1)
|
||||
rest = append(rest, bag[:i]...)
|
||||
rest = append(rest, bag[i+1:]...)
|
||||
return tile, rest, nil
|
||||
}
|
||||
|
||||
// bestContenders returns the contenders whose drawn tile has the lowest (best)
|
||||
// rank — the sole winner if one, else the tied set that re-draws. picks is aligned
|
||||
// with contenders by index.
|
||||
func bestContenders(contenders []uuid.UUID, picks []engine.SetupTile) []uuid.UUID {
|
||||
best := picks[0].Rank
|
||||
for _, p := range picks[1:] {
|
||||
if p.Rank < best {
|
||||
best = p.Rank
|
||||
}
|
||||
}
|
||||
var winners []uuid.UUID
|
||||
for i, p := range picks {
|
||||
if p.Rank == best {
|
||||
winners = append(winners, contenders[i])
|
||||
}
|
||||
}
|
||||
return winners
|
||||
}
|
||||
|
||||
// rotateToFirst returns accounts rotated cyclically so winner sits first (seat 0),
|
||||
// preserving the seating order of the rest (docs/ARCHITECTURE.md §6). winner must be
|
||||
// present in accounts.
|
||||
func rotateToFirst(accounts []uuid.UUID, winner uuid.UUID) []uuid.UUID {
|
||||
i := 0
|
||||
for ; i < len(accounts); i++ {
|
||||
if accounts[i] == winner {
|
||||
break
|
||||
}
|
||||
}
|
||||
out := make([]uuid.UUID, 0, len(accounts))
|
||||
out = append(out, accounts[i:]...)
|
||||
out = append(out, accounts[:i]...)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/engine"
|
||||
)
|
||||
|
||||
// scriptIntn returns a drawIntn that yields the scripted indices in order, failing
|
||||
// the test if the script is exhausted or an index is out of range. It lets a test
|
||||
// drive the first-move draw deterministically (English SetupBag order: 9 'a' at
|
||||
// 0..8, then 'b' …, blanks last).
|
||||
func scriptIntn(t *testing.T, seq ...int) drawIntn {
|
||||
t.Helper()
|
||||
i := 0
|
||||
return func(n int) (int, error) {
|
||||
if i >= len(seq) {
|
||||
t.Fatalf("intn script exhausted (asked for [0,%d))", n)
|
||||
}
|
||||
v := seq[i]
|
||||
i++
|
||||
if v < 0 || v >= n {
|
||||
t.Fatalf("intn script value %d out of range [0,%d)", v, n)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedFirstMoveDirectWinner(t *testing.T) {
|
||||
a, b := uuid.New(), uuid.New()
|
||||
// a draws bag[0]='a' (rank 0); b draws bag[8]='b' (rank 1) → a wins, no tie.
|
||||
res, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b}, scriptIntn(t, 0, 8))
|
||||
if err != nil {
|
||||
t.Fatalf("seedFirstMove: %v", err)
|
||||
}
|
||||
if res.winner != a {
|
||||
t.Fatalf("winner = %v, want %v", res.winner, a)
|
||||
}
|
||||
if got := res.order; len(got) != 2 || got[0] != a || got[1] != b {
|
||||
t.Fatalf("order = %v, want [a b]", got)
|
||||
}
|
||||
if len(res.draws) != 2 {
|
||||
t.Fatalf("draws = %d, want 2", len(res.draws))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedFirstMoveBlankSupersedes(t *testing.T) {
|
||||
a, b := uuid.New(), uuid.New()
|
||||
// a draws 'a' (rank 0); after the draw the two blanks sit at 97,98 — b draws
|
||||
// bag[97], a blank, which beats every letter.
|
||||
res, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b}, scriptIntn(t, 0, 97))
|
||||
if err != nil {
|
||||
t.Fatalf("seedFirstMove: %v", err)
|
||||
}
|
||||
if res.winner != b {
|
||||
t.Fatalf("winner = %v, want %v (blank supersedes)", res.winner, b)
|
||||
}
|
||||
last := res.draws[len(res.draws)-1]
|
||||
if !last.Blank || last.Rank != engine.BlankRank || last.Letter != "?" {
|
||||
t.Fatalf("winning draw = %+v, want a blank (rank %d, '?')", last, engine.BlankRank)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedFirstMoveTieRedraw(t *testing.T) {
|
||||
a, b, c := uuid.New(), uuid.New(), uuid.New()
|
||||
// Round 1: a→bag[0]='a'(0), b→bag[0]='a'(0), c→bag[7]='b'(1) → a,b tie best.
|
||||
// Round 2 (a,b only): a→bag[0]='a'(0), b→bag[8]='b'(1) → a wins.
|
||||
res, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b, c}, scriptIntn(t, 0, 0, 7, 0, 8))
|
||||
if err != nil {
|
||||
t.Fatalf("seedFirstMove: %v", err)
|
||||
}
|
||||
if res.winner != a {
|
||||
t.Fatalf("winner = %v, want %v", res.winner, a)
|
||||
}
|
||||
if len(res.draws) != 5 {
|
||||
t.Fatalf("draws = %d, want 5 (3 in round 1, 2 in round 2)", len(res.draws))
|
||||
}
|
||||
if res.draws[2].Round != 1 || res.draws[3].Round != 2 {
|
||||
t.Fatalf("round boundaries wrong: %+v", res.draws)
|
||||
}
|
||||
// The full table keeps every account's seating order, winner first.
|
||||
if got := res.order; got[0] != a || got[1] != b || got[2] != c {
|
||||
t.Fatalf("order = %v, want [a b c]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedFirstMoveTooFewAccounts(t *testing.T) {
|
||||
if _, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{uuid.New()}, scriptIntn(t)); err == nil {
|
||||
t.Fatal("want error for a single account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedFirstMovePerpetualTieCapped(t *testing.T) {
|
||||
a, b := uuid.New(), uuid.New()
|
||||
// Always drawing bag[0] gives both players an 'a' every round — a tie that never
|
||||
// resolves; the round cap must turn it into an error, not an infinite loop.
|
||||
alwaysZero := drawIntn(func(int) (int, error) { return 0, nil })
|
||||
if _, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b}, alwaysZero); err == nil {
|
||||
t.Fatal("want error when ties never resolve")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRotateToFirst(t *testing.T) {
|
||||
a, b, c, d := uuid.New(), uuid.New(), uuid.New(), uuid.New()
|
||||
tests := []struct {
|
||||
name string
|
||||
accounts []uuid.UUID
|
||||
winner uuid.UUID
|
||||
want []uuid.UUID
|
||||
}{
|
||||
{"two winner second", []uuid.UUID{a, b}, b, []uuid.UUID{b, a}},
|
||||
{"three winner first", []uuid.UUID{a, b, c}, a, []uuid.UUID{a, b, c}},
|
||||
{"four winner third", []uuid.UUID{a, b, c, d}, c, []uuid.UUID{c, d, a, b}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := rotateToFirst(tt.accounts, tt.winner)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Fatalf("len = %d, want %d", len(got), len(tt.want))
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Fatalf("rotate = %v, want %v", got, tt.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,12 @@ type Service struct {
|
||||
version string
|
||||
clock func() time.Time
|
||||
rng func() int64
|
||||
pub notify.Publisher
|
||||
// firstMoveEntropy returns the entropy source for one game's first-move draw
|
||||
// (docs/ARCHITECTURE.md §6). The default is crypto/rand — an honest, seedless draw;
|
||||
// tests override it via SetFirstMoveEntropy for a deterministic turn order. It is a
|
||||
// factory so a stateful test source restarts cleanly per game.
|
||||
firstMoveEntropy func() drawIntn
|
||||
pub notify.Publisher
|
||||
// aiTrigger, when set, is called after an honest-AI game is created or advanced and
|
||||
// is still on a robot's potential turn, so the robot replies at once instead of
|
||||
// waiting for the next driver scan. It is fire-and-forget (the robot package wires
|
||||
@@ -59,17 +64,18 @@ type Service struct {
|
||||
func NewService(store *Store, accounts *account.Store, registry *engine.Registry, cfg Config, log *zap.Logger) *Service {
|
||||
clock := func() time.Time { return time.Now().UTC() }
|
||||
return &Service{
|
||||
store: store,
|
||||
accounts: accounts,
|
||||
registry: registry,
|
||||
cache: newGameCache(cfg.CacheTTL, clock),
|
||||
locks: newKeyedMutex(),
|
||||
version: cfg.DictVersion,
|
||||
clock: clock,
|
||||
rng: randomSeed,
|
||||
pub: notify.Nop{},
|
||||
metrics: defaultGameMetrics(),
|
||||
log: log,
|
||||
store: store,
|
||||
accounts: accounts,
|
||||
registry: registry,
|
||||
cache: newGameCache(cfg.CacheTTL, clock),
|
||||
locks: newKeyedMutex(),
|
||||
version: cfg.DictVersion,
|
||||
clock: clock,
|
||||
rng: randomSeed,
|
||||
firstMoveEntropy: func() drawIntn { return cryptoIntn },
|
||||
pub: notify.Nop{},
|
||||
metrics: defaultGameMetrics(),
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +107,18 @@ func (svc *Service) SetNudgeClearer(fn func(ctx context.Context, gameID, account
|
||||
svc.clearNudges = fn
|
||||
}
|
||||
|
||||
// SetFirstMoveEntropy overrides the entropy source for the first-move draw
|
||||
// (docs/ARCHITECTURE.md §6). It must be called during wiring or test setup before any
|
||||
// game is created; the production default is crypto/rand and is never overridden.
|
||||
// factory returns a fresh draw function per game, so a stateful deterministic test
|
||||
// source restarts cleanly for each game. It exists for deterministic tests.
|
||||
func (svc *Service) SetFirstMoveEntropy(factory func() func(n int) (int, error)) {
|
||||
if factory == nil {
|
||||
return
|
||||
}
|
||||
svc.firstMoveEntropy = func() drawIntn { return drawIntn(factory()) }
|
||||
}
|
||||
|
||||
// triggerAI fires the honest-AI fast-move hook for an active vs_ai game (best-effort,
|
||||
// fire-and-forget). It is a no-op for non-AI games, finished games and when no hook is
|
||||
// installed, so callers can invoke it unconditionally after a create or commit.
|
||||
@@ -191,15 +209,32 @@ func (svc *Service) Create(ctx context.Context, params CreateParams) (Game, erro
|
||||
}
|
||||
}
|
||||
seen := make(map[uuid.UUID]bool, len(params.Seats))
|
||||
seats := make([]seatInsert, len(params.Seats))
|
||||
for i, id := range params.Seats {
|
||||
for _, id := range params.Seats {
|
||||
if seen[id] {
|
||||
return Game{}, fmt.Errorf("%w: account %s seated twice", ErrInvalidConfig, id)
|
||||
}
|
||||
seen[id] = true
|
||||
// Snapshot each seat's display name at creation. For a vs-AI game this stamps the
|
||||
// robot's seeded account name (unchanged behaviour); a disguised auto-match robot
|
||||
// instead gets a fresh per-game name when the reaper attaches it (AttachRobot).
|
||||
}
|
||||
|
||||
// Decide who moves first by the official draw (docs/ARCHITECTURE.md §6): each seated
|
||||
// account draws a tile, the one closest to "A" leads (a blank supersedes all letters),
|
||||
// ties re-drawing until a single leader remains. Each draw uses fresh entropy, not the
|
||||
// game seed, so the recorded draws — persisted with the game — are the only account of
|
||||
// the outcome. The winner takes seat 0; the rest keep their order.
|
||||
seeding, err := seedFirstMove(params.Variant, params.Seats, svc.firstMoveEntropy())
|
||||
if err != nil {
|
||||
if errors.Is(err, engine.ErrUnknownVariant) {
|
||||
return Game{}, fmt.Errorf("%w: %v", ErrInvalidConfig, err)
|
||||
}
|
||||
return Game{}, err
|
||||
}
|
||||
|
||||
// Build the seats in the drawn turn order, snapshotting each seat's display name. For a
|
||||
// vs-AI game this stamps the robot's seeded account name (unchanged behaviour); a
|
||||
// disguised auto-match robot instead gets a fresh per-game name when the reaper attaches
|
||||
// it (AttachRobot).
|
||||
seats := make([]seatInsert, len(seeding.order))
|
||||
for i, id := range seeding.order {
|
||||
acc, err := svc.accounts.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, account.ErrNotFound) {
|
||||
@@ -249,7 +284,7 @@ func (svc *Service) Create(ctx context.Context, params CreateParams) (Game, erro
|
||||
multipleWordsPerTurn: params.MultipleWordsPerTurn,
|
||||
vsAI: params.VsAI,
|
||||
}
|
||||
if err := svc.store.CreateGame(ctx, ins, seats); err != nil {
|
||||
if err := svc.store.CreateGame(ctx, ins, seats, seeding.draws); err != nil {
|
||||
return Game{}, err
|
||||
}
|
||||
svc.cache.put(id, g, params.Variant.String())
|
||||
@@ -312,14 +347,27 @@ func (svc *Service) OpenOrJoin(ctx context.Context, accountID uuid.UUID, params
|
||||
status: StatusOpen,
|
||||
openDeadline: &deadline,
|
||||
}
|
||||
// Seat the caller at seat 0 or seat 1 (seat 0 always moves first), snapshotting their
|
||||
// display name; the other seat is left empty (a zero seatInsert) for the opponent.
|
||||
caller := seatInsert{accountID: accountID, displayName: acc.DisplayName}
|
||||
seats := []seatInsert{caller, {}}
|
||||
if seed&1 == 1 {
|
||||
seats = []seatInsert{{}, caller}
|
||||
// Decide the first move now by the official draw, with the not-yet-arrived opponent as a
|
||||
// synthetic placeholder (uuid.Nil): the draw fixes who sits at seat 0 — and so moves
|
||||
// first — before either player acts (docs/ARCHITECTURE.md §6). The caller takes their
|
||||
// drawn seat; the opponent seat is left empty. The opponent's draw rows are recorded with
|
||||
// a NULL account and back-filled when a real opponent joins. Each draw uses fresh entropy,
|
||||
// not the game seed. seats/draws are used only when a fresh game is opened.
|
||||
seeding, err := seedFirstMove(params.Variant, []uuid.UUID{accountID, uuid.Nil}, svc.firstMoveEntropy())
|
||||
if err != nil {
|
||||
if errors.Is(err, engine.ErrUnknownVariant) {
|
||||
return Game{}, false, fmt.Errorf("%w: %v", ErrInvalidConfig, err)
|
||||
}
|
||||
return Game{}, false, err
|
||||
}
|
||||
gameID, joined, created, err := svc.store.OpenOrJoin(ctx, accountID, acc.DisplayName, ins, seats, exclude)
|
||||
caller := seatInsert{accountID: accountID, displayName: acc.DisplayName}
|
||||
seats := make([]seatInsert, len(seeding.order))
|
||||
for seat, who := range seeding.order {
|
||||
if who == accountID {
|
||||
seats[seat] = caller // the empty opponent seat stays a zero seatInsert
|
||||
}
|
||||
}
|
||||
gameID, joined, created, err := svc.store.OpenOrJoin(ctx, accountID, acc.DisplayName, ins, seats, exclude, seeding.draws)
|
||||
if err != nil {
|
||||
return Game{}, false, err
|
||||
}
|
||||
@@ -547,8 +595,9 @@ func (svc *Service) transition(ctx context.Context, gameID, accountID uuid.UUID,
|
||||
return MoveResult{}, ErrNotAPlayer
|
||||
}
|
||||
// A move is allowed while the game is active or still open (the starter may move on
|
||||
// their turn before an opponent joins); only a finished game rejects it. The turn
|
||||
// check below keeps the starter off the still-empty opponent seat.
|
||||
// their turn before an opponent joins; the first-move draw ran when the game opened, so
|
||||
// the seats are already fixed); only a finished game rejects it. The turn check below
|
||||
// keeps the starter off the still-empty opponent seat.
|
||||
if pre.Status == StatusFinished {
|
||||
return MoveResult{}, ErrFinished
|
||||
}
|
||||
@@ -1287,6 +1336,14 @@ func (svc *Service) History(ctx context.Context, gameID uuid.UUID) (HistoryView,
|
||||
return HistoryView{Game: g, Moves: moves}, nil
|
||||
}
|
||||
|
||||
// SetupDraws returns a game's recorded first-move draws (docs/ARCHITECTURE.md §6), ordered by
|
||||
// round then pick. It backs the admin console's first-move section. An auto-match opponent's
|
||||
// draws carry uuid.Nil until a real opponent joins and back-fills them; an empty slice means
|
||||
// the game predates the draw record.
|
||||
func (svc *Service) SetupDraws(ctx context.Context, gameID uuid.UUID) ([]SetupDraw, error) {
|
||||
return svc.store.SetupDraws(ctx, gameID)
|
||||
}
|
||||
|
||||
// ExportGCG renders a game as GCG text from the journal alone (no dictionary). It
|
||||
// is allowed only on a finished game: exporting an in-progress game would leak the
|
||||
// full move journal mid-play, so an active game yields ErrGameActive.
|
||||
|
||||
@@ -127,11 +127,14 @@ type seatInsert struct {
|
||||
displayName string
|
||||
}
|
||||
|
||||
// CreateGame inserts the games row and one game_players row per seat (seat 0
|
||||
// first) inside a single transaction.
|
||||
func (s *Store) CreateGame(ctx context.Context, ins gameInsert, seats []seatInsert) error {
|
||||
// CreateGame inserts the games row, one game_players row per seat (seat 0 first) and
|
||||
// the first-move seeding draws inside a single transaction.
|
||||
func (s *Store) CreateGame(ctx context.Context, ins gameInsert, seats []seatInsert, draws []SetupDraw) error {
|
||||
return withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||
return insertGameTx(ctx, tx, ins, seats)
|
||||
if err := insertGameTx(ctx, tx, ins, seats); err != nil {
|
||||
return err
|
||||
}
|
||||
return insertSetupDrawsTx(ctx, tx, ins.id, draws)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,6 +176,30 @@ func insertGameTx(ctx context.Context, tx *sql.Tx, ins gameInsert, seats []seatI
|
||||
return nil
|
||||
}
|
||||
|
||||
// insertSetupDrawsTx appends the first-move seeding draws for game gameID on tx —
|
||||
// the dictionary-independent record of how the first player was chosen
|
||||
// (docs/ARCHITECTURE.md §6). The games row must already exist on tx (the foreign
|
||||
// key), so it runs after insertGameTx. An empty draws slice is a no-op.
|
||||
func insertSetupDrawsTx(ctx context.Context, tx *sql.Tx, gameID uuid.UUID, draws []SetupDraw) error {
|
||||
for _, d := range draws {
|
||||
// A uuid.Nil account marks the synthetic opponent of an auto-match draw, persisted as
|
||||
// a NULL account_id and back-filled when a real opponent joins.
|
||||
var acc any = d.Account
|
||||
if d.Account == uuid.Nil {
|
||||
acc = postgres.NULL
|
||||
}
|
||||
di := table.GameSetupDraws.INSERT(
|
||||
table.GameSetupDraws.GameID, table.GameSetupDraws.Round, table.GameSetupDraws.PickNo,
|
||||
table.GameSetupDraws.AccountID, table.GameSetupDraws.Letter, table.GameSetupDraws.IsBlank,
|
||||
table.GameSetupDraws.DrawRank,
|
||||
).VALUES(gameID, d.Round, d.PickNo, acc, d.Letter, d.Blank, d.Rank)
|
||||
if _, err := di.ExecContext(ctx, tx); err != nil {
|
||||
return fmt.Errorf("insert setup draw round %d pick %d: %w", d.Round, d.PickNo, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// openMatchKey hashes an auto-match bucket (variant + per-turn word rule) into the
|
||||
// advisory-lock key that serialises concurrent enqueues for that bucket, so two
|
||||
// players never both open a game instead of pairing.
|
||||
@@ -199,8 +226,9 @@ func openMatchKey(variant string, multipleWords bool) int64 {
|
||||
// arrangement (the caller and uuid.Nil for the still-empty opponent, in the chosen
|
||||
// order) used only when a game is created; callerName is the caller's display-name
|
||||
// snapshot, stamped on their seat whether they open a fresh game or fill another
|
||||
// player's open one.
|
||||
func (s *Store) OpenOrJoin(ctx context.Context, accountID uuid.UUID, callerName string, ins gameInsert, seats []seatInsert, exclude []uuid.UUID) (gameID uuid.UUID, joined, created bool, err error) {
|
||||
// player's open one. seats and draws (the first-move draw recorded against the synthetic
|
||||
// opponent, docs/ARCHITECTURE.md §6) are used only when a game is created.
|
||||
func (s *Store) OpenOrJoin(ctx context.Context, accountID uuid.UUID, callerName string, ins gameInsert, seats []seatInsert, exclude []uuid.UUID, draws []SetupDraw) (gameID uuid.UUID, joined, created bool, err error) {
|
||||
err = withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||
if _, e := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`,
|
||||
openMatchKey(ins.variant, ins.multipleWordsPerTurn)); e != nil {
|
||||
@@ -222,7 +250,7 @@ func (s *Store) OpenOrJoin(ctx context.Context, accountID uuid.UUID, callerName
|
||||
LIMIT 1 FOR UPDATE SKIP LOCKED`,
|
||||
ins.variant, ins.multipleWordsPerTurn, accountID, uuidArrayLiteral(exclude)).Scan(&other); {
|
||||
case e == nil:
|
||||
if er := fillOpenSeat(ctx, tx, other, accountID, callerName); er != nil {
|
||||
if er := fillAndActivate(ctx, tx, other, accountID, callerName); er != nil {
|
||||
return er
|
||||
}
|
||||
gameID, joined = other, true
|
||||
@@ -230,10 +258,15 @@ func (s *Store) OpenOrJoin(ctx context.Context, accountID uuid.UUID, callerName
|
||||
case !errors.Is(e, sql.ErrNoRows):
|
||||
return fmt.Errorf("find open game: %w", e)
|
||||
}
|
||||
// 2. None waiting — open a fresh game seating the caller (the other seat empty).
|
||||
// 2. None waiting — open a fresh game seating the caller (the other seat empty) and
|
||||
// recording the first-move draw; the synthetic opponent's rows carry a NULL account
|
||||
// until a real opponent joins and back-fills them.
|
||||
if e := insertGameTx(ctx, tx, ins, seats); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := insertSetupDrawsTx(ctx, tx, ins.id, draws); e != nil {
|
||||
return e
|
||||
}
|
||||
gameID, created = ins.id, true
|
||||
return nil
|
||||
})
|
||||
@@ -258,7 +291,7 @@ func (s *Store) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID, disp
|
||||
if status != StatusOpen {
|
||||
return nil
|
||||
}
|
||||
if e := fillOpenSeat(ctx, tx, gameID, robotID, displayName); e != nil {
|
||||
if e := fillAndActivate(ctx, tx, gameID, robotID, displayName); e != nil {
|
||||
return e
|
||||
}
|
||||
attached = true
|
||||
@@ -267,15 +300,23 @@ func (s *Store) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID, disp
|
||||
return attached, err
|
||||
}
|
||||
|
||||
// fillOpenSeat seats accountID in an open game's empty opponent seat — stamping
|
||||
// displayName as the seat's display-name snapshot — and flips the game to active with a
|
||||
// fresh turn clock. The caller holds the game row.
|
||||
func fillOpenSeat(ctx context.Context, tx *sql.Tx, gameID, accountID uuid.UUID, displayName string) error {
|
||||
// fillAndActivate seats accountID in an open game's empty opponent seat — stamping
|
||||
// displayName as the seat's snapshot — back-fills the first-move draw rows the open game
|
||||
// recorded for the then-unknown opponent (docs/ARCHITECTURE.md §6), and flips the game to
|
||||
// active with a fresh turn clock. The seat the joiner takes was already fixed by the draw at
|
||||
// open time, so the journal (any opening move the starter made while waiting) is never
|
||||
// disturbed. The caller holds the game row.
|
||||
func fillAndActivate(ctx context.Context, tx *sql.Tx, gameID, accountID uuid.UUID, displayName string) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE backend.game_players SET account_id = $2, display_name = $3 WHERE game_id = $1 AND account_id IS NULL`,
|
||||
gameID, accountID, displayName); err != nil {
|
||||
return fmt.Errorf("fill opponent seat: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE backend.game_setup_draws SET account_id = $2 WHERE game_id = $1 AND account_id IS NULL`,
|
||||
gameID, accountID); err != nil {
|
||||
return fmt.Errorf("back-fill opponent draws: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE backend.games SET status = 'active', open_deadline_at = NULL, turn_started_at = now(), updated_at = now()
|
||||
WHERE game_id = $1`, gameID); err != nil {
|
||||
@@ -587,6 +628,37 @@ func (s *Store) GetJournal(ctx context.Context, id uuid.UUID) ([]HistoryMove, er
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SetupDraws loads the ordered first-move seeding draws for a game (round then pick
|
||||
// order), or an empty slice for a game created before the draw was recorded. It
|
||||
// backs the admin console's first-move section.
|
||||
func (s *Store) SetupDraws(ctx context.Context, id uuid.UUID) ([]SetupDraw, error) {
|
||||
stmt := postgres.SELECT(table.GameSetupDraws.AllColumns).
|
||||
FROM(table.GameSetupDraws).
|
||||
WHERE(table.GameSetupDraws.GameID.EQ(postgres.UUID(id))).
|
||||
ORDER_BY(table.GameSetupDraws.Round.ASC(), table.GameSetupDraws.PickNo.ASC())
|
||||
var rows []model.GameSetupDraws
|
||||
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||
return nil, fmt.Errorf("game: get setup draws %s: %w", id, err)
|
||||
}
|
||||
out := make([]SetupDraw, len(rows))
|
||||
for i, r := range rows {
|
||||
// A NULL account is the synthetic opponent of an auto-match draw not yet back-filled.
|
||||
acc := uuid.Nil
|
||||
if r.AccountID != nil {
|
||||
acc = *r.AccountID
|
||||
}
|
||||
out[i] = SetupDraw{
|
||||
Round: int(r.Round),
|
||||
PickNo: int(r.PickNo),
|
||||
Account: acc,
|
||||
Letter: r.Letter,
|
||||
Blank: r.IsBlank,
|
||||
Rank: int(r.DrawRank),
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CommitMove appends the move and applies the post-move game state — the turn
|
||||
// cursor and per-seat scores, plus the finish stamp and statistics when the move
|
||||
// ended the game — in one transaction.
|
||||
|
||||
Reference in New Issue
Block a user