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

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:
Ilia Denisov
2026-06-20 08:47:18 +02:00
parent 76d4610e6f
commit caefc8f579
27 changed files with 1661 additions and 59 deletions
+1
View File
@@ -36,6 +36,7 @@ the edge before prod. Each phase maps back to the owner's raw pre-release TODO l
| GL | Simultaneous quick-game cap (10): grey "New Game" + a lobby notice at the cap; backend gate on quick enqueue + invitation creation (409 `game_limit_reached`), accepting invitations exempt; `at_game_limit` rides `games.list` | owner ad-hoc | **done** |
| CR | In-game chat read receipts: per-message `unread_seats` bitmask (migration `00008`); a per-viewer unread **dot** in the lobby + game header (a nudge counts and clears when its recipient moves); reading = opening the move history (the 💬 fade-blinks twice) or the chat, acked (`chat.read`) only when unread; `chat_read_duration` + `chat_unread_messages` metrics + tracing + the **Scrabble — Messages** Grafana dashboard (follow-up PR); a message to a disguised robot opponent is born read; admin unread-only filter / read column / per-seat read card | owner ad-hoc | **done** |
| BX | Asymmetric per-user block + in-game controls: a block now silently suppresses everything **from** the blocked user (chat, nudge, friend requests, invitations are kept but never delivered/surfaced, born-read) while they notice nothing, **without** deleting the friendship (unblock restores it); auto-match excludes a block-related pair (either direction); in-game opponent card gains a ✖️ **block** control (mirroring 🤝, red "Block?" confirm, mutual-hide, struck name + hidden chat composer when blocked); optimistic apply + `user_blocked`/`user_unblocked` event confirm + rollback; admin user card gains **blocks / blocked-by / friends** cross-linked lists. Blocking a disguised-robot opponent is recorded per-game in a separate **`robot_blocks`** table (migration `00011`), keyed on game+seat with the seen name — never the shared robot account — so the matchmaker keeps giving robots; it shows in the blocked list and re-marks the in-game card | owner ad-hoc | **done** |
| FM | First-move tile draw (official rules): each seated player draws a tile, the one closest to "A" leads (a blank beats every letter), ties re-drawing until a single leader; **honest per-draw `crypto/rand` entropy**, not the bag seed, so the **record** (`game_setup_draws`, migration `00013`) — not a seed — is the only account of the outcome, kept for future **tournaments** (designed as a discrete per-tile "player N draws" step). Friend/AI draws at create; **auto-match draws at *open*** against a synthetic `uuid.Nil` opponent whose draw rows are back-filled on join, so the opener's seat is fixed up front and the existing open-game pre-move is preserved (no reseating, no play-gating). Admin `/_gm/games/:id` gains the recorded draw list + a simple **step-by-step board replay** (`ReplayTimeline`). | owner ad-hoc | **done** |
| → | Stage 18 — prod contour deploy | — | see [`PLAN.md`](PLAN.md) |
## Key findings (these reshaped the raw list — read before starting a phase)
@@ -137,3 +137,59 @@ code { background: var(--bg); padding: 0.05rem 0.3rem; border-radius: 4px; }
an image attachment is previewed inline, bounded so it cannot dominate the page. */
.msgbody { white-space: pre-wrap; word-break: break-word; background: var(--bg); padding: 0.6rem 0.8rem; border-radius: 6px; margin: 0.6rem 0; }
.attach { max-width: 100%; max-height: 480px; height: auto; border: 1px solid var(--line); border-radius: 6px; }
/* Game replay (admin): a script-stepped board with rack panels around it, a move log and the
first-move draw. A placed tile shows its value as a subscript; a 0 value (a blank) shows none. */
.replay-stage {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
grid-template-areas: ". top ." "left board right" ". bottom .";
gap: 0.5rem;
align-items: center;
justify-items: center;
margin-bottom: 0.6rem;
}
.rack-top { grid-area: top; }
.rack-bottom { grid-area: bottom; }
.rack-left { grid-area: left; }
.rack-right { grid-area: right; }
.replay-board { grid-area: board; overflow: auto; }
.board-grid {
display: grid;
grid-template-columns: 1.4rem repeat(15, 1.7rem);
grid-auto-rows: 1.7rem;
gap: 1px;
background: var(--line);
border: 1px solid var(--line);
width: max-content;
}
.board-grid .bh { display: flex; align-items: center; justify-content: center; font-size: 0.6rem; color: var(--ink-dim); background: var(--panel); }
.board-grid .cell { position: relative; display: flex; align-items: center; justify-content: center; background: var(--panel-hi); }
.cell .prem { font-size: 0.55rem; color: var(--ink); opacity: 0.8; }
.cell.tw { background: #7a2230; }
.cell.dw { background: #a8506a; }
.cell.tl { background: #235a7a; }
.cell.dl { background: #3f87a8; }
.cell.centre .prem { font-size: 0.95rem; color: var(--warn); opacity: 1; }
.tile {
display: inline-flex; align-items: baseline; justify-content: center;
min-width: 1.35rem; height: 1.35rem; padding: 0 0.12rem;
background: #e8d9a0; color: #1b1408; border-radius: 3px;
font-weight: 700; font-size: 0.8rem; line-height: 1.35rem;
}
.tile sub { font-size: 0.5rem; font-weight: 600; line-height: 1; align-self: flex-end; margin-left: 1px; }
.tile.blank { background: #cdbfe0; }
.cell.filled { background: var(--panel-hi); }
.cell.filled .tile { width: 100%; height: 100%; border-radius: 2px; }
.rack-slot { padding: 0.25rem; border-radius: 6px; }
.rack-slot.active { outline: 2px solid var(--accent); background: var(--panel-hi); }
.rack-name { font-size: 0.72rem; color: var(--ink-dim); margin-bottom: 0.2rem; text-align: center; }
.rack-tiles { display: flex; gap: 2px; flex-wrap: wrap; justify-content: center; }
.rack-left .rack-tiles, .rack-right .rack-tiles { flex-direction: column; }
.replay-controls { display: flex; align-items: center; gap: 0.8rem; justify-content: center; margin: 0.6rem 0; }
.replay-controls button { background: var(--panel-hi); color: var(--ink); border: 1px solid var(--line); font-weight: 600; }
.replay-controls button:disabled { opacity: 0.4; cursor: default; }
.replay-pos { color: var(--ink-dim); font-variant-numeric: tabular-nums; }
.replay-log { margin: 0.4rem 0 0; padding-left: 1.4rem; max-height: 14rem; overflow: auto; font-size: 0.85rem; }
.replay-log li { color: var(--ink-dim); padding: 0.1rem 0; }
.replay-log li.cur { color: var(--ink); font-weight: 600; }
@@ -27,5 +27,87 @@
</table>
{{if .HasRobot}}<p><small>Play-to-win is decided once per game from the bag seed; robots play to win in ~{{.RobotTargetPct}}% of games.</small></p>{{end}}
</section>
{{if .SetupDraws}}
<section class="panel"><h2>First-move draw</h2>
<p class="note">Each player draws a tile; the one closest to &ldquo;A&rdquo; moves first (a blank beats every letter), ties re-drawing until a single leader remains.{{if .FirstMover}} <b>{{.FirstMover}}</b> leads.{{end}}</p>
<table class="list">
<thead><tr><th>Round</th><th>Player</th><th>Tile</th><th>Rank</th></tr></thead>
<tbody>
{{range .SetupDraws}}
<tr><td>{{.Round}}</td><td>{{if .AccountID}}<a href="/_gm/users/{{.AccountID}}">{{.Name}}</a>{{else}}{{.Name}}{{end}}</td><td>{{.Letter}}{{if .Blank}} <small>(blank)</small>{{end}}</td><td>{{.Rank}}</td></tr>
{{end}}
</tbody>
</table>
</section>
{{end}}
{{if .HasReplay}}
<section class="panel"><h2>Replay</h2>
<div class="replay-stage">
<div class="rack-slot rack-top" data-seat="0"></div>
<div class="rack-slot rack-left" data-seat="2"></div>
<div class="replay-board" id="replay-board"></div>
<div class="rack-slot rack-right" data-seat="3"></div>
<div class="rack-slot rack-bottom" data-seat="1"></div>
</div>
<div class="replay-controls">
<button type="button" id="replay-prev">&#9664; prev</button>
<span class="replay-pos" id="replay-pos"></span>
<button type="button" id="replay-next">next &#9654;</button>
</div>
<ol class="replay-log" id="replay-log"></ol>
<script>
const REPLAY = {{.ReplayJSON}};
(function(){
if(!REPLAY||!REPLAY.steps){return;}
const N=15, COLS="ABCDEFGHIJKLMNO", PREM={tw:"3W",dw:"2W",tl:"3L",dl:"2L"};
const boardEl=document.getElementById("replay-board"), logEl=document.getElementById("replay-log");
const posEl=document.getElementById("replay-pos"), prevBtn=document.getElementById("replay-prev"), nextBtn=document.getElementById("replay-next");
let step=0;
function esc(s){const d=document.createElement("div");d.textContent=s==null?"":s;return d.innerHTML;}
function tileHTML(t){const sub=(t.v&&t.v>0)?"<sub>"+t.v+"<\/sub>":"";return "<span class=\"tile"+(t.b?" blank":"")+"\">"+esc(t.l)+sub+"<\/span>";}
function placedAt(k){const m={};for(let s=1;s<=k;s++){const mv=REPLAY.steps[s]&&REPLAY.steps[s].move;if(mv&&mv.placements){for(const p of mv.placements){m[p.r+","+p.c]=p;}}}return m;}
function renderBoard(){
const placed=placedAt(step);let h="<div class=\"board-grid\"><div class=\"bh corner\"><\/div>";
for(let c=0;c<N;c++){h+="<div class=\"bh\">"+COLS[c]+"<\/div>";}
for(let r=0;r<N;r++){h+="<div class=\"bh\">"+(r+1)+"<\/div>";
for(let c=0;c<N;c++){const p=placed[r+","+c];
if(p){h+="<div class=\"cell filled\">"+tileHTML(p)+"<\/div>";continue;}
const prem=REPLAY.premium[r][c], centre=(r===REPLAY.centre[0]&&c===REPLAY.centre[1]);
const label=centre?"&#9733;":(prem?PREM[prem]:"");
h+="<div class=\"cell "+(prem||"")+(centre?" centre":"")+"\">"+(label?"<span class=\"prem\">"+label+"<\/span>":"")+"<\/div>";}}
h+="<\/div>";boardEl.innerHTML=h;
}
function renderRacks(){
const st=REPLAY.steps[step];
document.querySelectorAll(".rack-slot").forEach(function(slot){
const seat=parseInt(slot.dataset.seat,10), info=REPLAY.seats.find(function(s){return s.seat===seat;}), rack=st.racks[seat];
if(!info||!rack){slot.style.display="none";slot.innerHTML="";return;}
slot.style.display="";slot.classList.toggle("active",st.toMove===seat);
const nm=info.accountId?"<a href=\"/_gm/users/"+info.accountId+"\">"+esc(info.name)+"<\/a>":esc(info.name||("seat "+seat));
slot.innerHTML="<div class=\"rack-name\">"+nm+" &middot; "+(st.scores[seat]||0)+"<\/div><div class=\"rack-tiles\">"+rack.map(tileHTML).join("")+"<\/div>";
});
}
function renderLog(){
let h="";
for(let s=1;s<=step;s++){const st=REPLAY.steps[s], m=st.move;if(!m){continue;}
const who=((REPLAY.seats.find(function(x){return x.seat===m.seat;})||{}).name)||("seat "+m.seat);
let desc;
if(m.action==="play"){desc="played "+((m.words&&m.words.length)?m.words.join(", "):"")+" for "+m.score;}
else if(m.action==="exchange"){desc="exchanged "+((m.exchanged&&m.exchanged.length)||0)+" tiles";}
else if(m.action==="pass"){desc="passed";}
else{desc=m.action;}
const drew=(st.drawn&&st.drawn.length)?" &middot; drew "+st.drawn.map(function(t){return t.l;}).join(""):"";
h+="<li class=\""+(s===step?"cur":"")+"\">"+esc(who)+" "+esc(desc)+drew+" &middot; bag "+st.bagLen+"<\/li>";}
logEl.innerHTML=h||"<li class=\"note\">opening position<\/li>";
}
function render(){renderBoard();renderRacks();renderLog();posEl.textContent=step+" / "+(REPLAY.steps.length-1);prevBtn.disabled=step<=0;nextBtn.disabled=step>=REPLAY.steps.length-1;}
prevBtn.onclick=function(){if(step>0){step--;render();}};
nextBtn.onclick=function(){if(step<REPLAY.steps.length-1){step++;render();}};
document.addEventListener("keydown",function(e){if(e.key==="ArrowLeft"){prevBtn.click();}else if(e.key==="ArrowRight"){nextBtn.click();}});
render();
})();
</script>
</section>
{{end}}
{{end}}
{{- end}}
+21
View File
@@ -268,6 +268,27 @@ type GameDetailView struct {
// RobotTargetPct is the configured global play-to-win rate, in percent.
HasRobot bool
RobotTargetPct int
// ReplayJSON is the game-replay payload (board, seats, per-step racks/scores/bag) the
// game_detail page feeds to its vanilla-JS stepper; HasReplay gates the replay section.
ReplayJSON template.JS
HasReplay bool
// SetupDraws is the first-move draw — one row per tile drawn (docs/ARCHITECTURE.md §6) —
// and FirstMover is the resolved name of the seat-0 player the draw elected.
SetupDraws []SetupDrawRow
FirstMover string
}
// SetupDrawRow is one tile drawn in the first-move seeding (docs/ARCHITECTURE.md §6): the
// round, the player (Name/AccountID, or "(opponent)" with an empty AccountID for an
// auto-match synthetic draw not yet back-filled), the drawn letter (upper-cased; "?" for a
// blank) and its draw rank.
type SetupDrawRow struct {
Round int
Name string
AccountID string
Letter string
Blank bool
Rank int
}
// SeatRow is one seat of a game. For a robot seat (IsRobot) RobotIntent is the game's
+52
View File
@@ -0,0 +1,52 @@
package engine
import "fmt"
// SetupTile is one tile of a variant's full bag, decoded for the first-move draw
// (docs/ARCHITECTURE.md §6): its concrete letter (or the blank marker), a blank
// flag, and its draw rank. Lower rank wins the draw — a blank ranks above every
// letter, and letters rank by alphabet index, so the tile closest to the start of
// the alphabet ("A") wins. It is dictionary-independent, built from the variant's
// solver ruleset alone.
type SetupTile struct {
// Letter is the concrete character (the case the solver ruleset emits), or
// the blank marker "?" for a blank.
Letter string
// Blank reports whether the tile is a blank.
Blank bool
// Rank orders the draw: BlankRank for a blank (best), else the letter's
// alphabet index (0 = closest to "A").
Rank int
}
// BlankRank is the first-move draw rank of a blank: below every letter index, so a
// blank always beats a lettered tile, matching the official rule that a blank
// supersedes all letters.
const BlankRank = -1
// SetupBag returns variant's full tile bag — every lettered tile expanded by its
// count, plus one entry per blank — decoded for the first-move seeding draw. The
// order is deterministic (alphabet order, blanks last); callers shuffle it with
// their own entropy. It needs no dictionary, so it is built from the variant's
// ruleset alone and reports ErrUnknownVariant for an unrecognised variant.
func SetupBag(v Variant) ([]SetupTile, error) {
rs, ok := v.ruleset()
if !ok {
return nil, fmt.Errorf("%w: %d", ErrUnknownVariant, v)
}
bag := make([]SetupTile, 0, 128)
for i, n := range rs.Counts {
ch, err := rs.Alphabet.Character(byte(i))
if err != nil {
// An offered variant's alphabet never yields a bad index; skip defensively.
continue
}
for range n {
bag = append(bag, SetupTile{Letter: ch, Rank: i})
}
}
for range rs.Blanks {
bag = append(bag, SetupTile{Letter: blankLetter, Blank: true, Rank: BlankRank})
}
return bag, nil
}
+47
View File
@@ -0,0 +1,47 @@
package engine
import (
"errors"
"testing"
)
func TestSetupBagEnglish(t *testing.T) {
bag, err := SetupBag(VariantEnglish)
if err != nil {
t.Fatalf("SetupBag: %v", err)
}
// English Scrabble: 98 lettered tiles + 2 blanks = 100.
if len(bag) != 100 {
t.Fatalf("bag size = %d, want 100", len(bag))
}
blanks, aCount := 0, 0
for _, tl := range bag {
switch {
case tl.Blank:
blanks++
if tl.Rank != BlankRank {
t.Errorf("blank rank = %d, want %d", tl.Rank, BlankRank)
}
if tl.Letter != blankLetter {
t.Errorf("blank letter = %q, want %q", tl.Letter, blankLetter)
}
case tl.Letter == "a":
aCount++
if tl.Rank != 0 {
t.Errorf("'a' rank = %d, want 0 (closest to A)", tl.Rank)
}
}
}
if blanks != 2 {
t.Errorf("blanks = %d, want 2", blanks)
}
if aCount != 9 {
t.Errorf("'a' count = %d, want 9", aCount)
}
}
func TestSetupBagUnknownVariant(t *testing.T) {
if _, err := SetupBag(Variant(99)); !errors.Is(err, ErrUnknownVariant) {
t.Fatalf("err = %v, want ErrUnknownVariant", err)
}
}
+144
View File
@@ -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)
}
})
}
}
+156
View File
@@ -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
}
+130
View File
@@ -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)
}
}
})
}
}
+72 -15
View File
@@ -38,6 +38,11 @@ type Service struct {
version string
clock func() time.Time
rng func() int64
// 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
@@ -67,6 +72,7 @@ func NewService(store *Store, accounts *account.Store, registry *engine.Registry
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)
}
gameID, joined, created, err := svc.store.OpenOrJoin(ctx, accountID, acc.DisplayName, ins, seats, exclude)
return Game{}, false, err
}
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.
+85 -13
View File
@@ -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.
+6
View File
@@ -206,6 +206,12 @@ func TestConsoleGameDetailRobotSchedule(t *testing.T) {
if !strings.Contains(body, "~40%") {
t.Error("robot play-to-win target caption missing")
}
if !strings.Contains(body, "First-move draw") {
t.Error("first-move draw section missing from the game detail")
}
if !strings.Contains(body, `id="replay-board"`) {
t.Error("replay board container missing from the game detail")
}
}
// TestConsoleThrottledViewAndFlagClear drives the rate-limit surface end to
@@ -134,11 +134,13 @@ func TestDictionaryUpdateFlow(t *testing.T) {
// newGameServiceOn builds a game service over the shared pool but a caller-supplied
// dictionary directory, version and registry, for the isolated dictionary tests.
func newGameServiceOn(dir, version string, reg *engine.Registry) *game.Service {
return game.NewService(
svc := game.NewService(
game.NewStore(testDB), account.NewStore(testDB), reg,
game.Config{DictDir: dir, DictVersion: version, TimeoutSweepInterval: time.Minute, CacheTTL: time.Hour},
zap.NewNop(),
)
svc.SetFirstMoveEntropy(seatZeroFirstMove)
return svc
}
// seedDawgs copies the committed DAWG of every variant from src into dst (flat).
@@ -0,0 +1,154 @@
//go:build integration
package inttest
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"scrabble/backend/internal/engine"
"scrabble/backend/internal/game"
)
// The first-move-draw suite covers the official seeding (docs/ARCHITECTURE.md §6): the draw is
// recorded with the game, decides seat 0 (the first mover), and — in auto-match — runs against
// a synthetic opponent at open time whose draw rows are back-filled when a real opponent joins.
// TestCreateRecordsFirstMoveDraws checks a directly-seated game records the draw against the
// real seated accounts and seats the drawn leader (the suite's deterministic draw elects the
// first-listed account) at seat 0.
func TestCreateRecordsFirstMoveDraws(t *testing.T) {
ctx := context.Background()
svc := newGameService()
a := provisionAccount(t)
b := provisionAccount(t)
g, err := svc.Create(ctx, game.CreateParams{Variant: engine.VariantEnglish, Seats: []uuid.UUID{a, b}, TurnTimeout: 24 * time.Hour, Seed: 1})
if err != nil {
t.Fatalf("create: %v", err)
}
if g.Seats[0].AccountID != a || g.Seats[1].AccountID != b {
t.Fatalf("seats = [%s %s], want [a b]", g.Seats[0].AccountID, g.Seats[1].AccountID)
}
draws, err := svc.SetupDraws(ctx, g.ID)
if err != nil {
t.Fatalf("setup draws: %v", err)
}
// seatZeroFirstMove resolves in one round: the first contender (a) draws a blank and wins.
if len(draws) != 2 {
t.Fatalf("draws = %d, want 2 (one round, two players)", len(draws))
}
if draws[0].Account != a || !draws[0].Blank {
t.Fatalf("draw[0] = %+v, want a having drawn a blank", draws[0])
}
if draws[1].Account != b {
t.Fatalf("draw[1] account = %s, want b", draws[1].Account)
}
}
// TestAutoMatchDrawBackfilledOnJoin checks an open auto-match game records the draw at open
// time against the synthetic opponent (a NULL account) and back-fills those rows to the real
// opponent when they join.
func TestAutoMatchDrawBackfilledOnJoin(t *testing.T) {
ctx := context.Background()
clearOpenGames(t)
svc := newGameService()
starter := provisionAccount(t)
g := openGame(t, svc, starter, evenOpeningSeed(t))
draws, err := svc.SetupDraws(ctx, g.ID)
if err != nil {
t.Fatalf("setup draws: %v", err)
}
if len(draws) != 2 {
t.Fatalf("open draws = %d, want 2", len(draws))
}
var nullSeen, starterSeen bool
for _, d := range draws {
switch d.Account {
case uuid.Nil:
nullSeen = true
case starter:
starterSeen = true
}
}
if !nullSeen || !starterSeen {
t.Fatalf("open draws = %+v, want the starter and a NULL synthetic opponent", draws)
}
joiner := provisionAccount(t)
if _, joined, err := svc.OpenOrJoin(ctx, joiner, openParams(0), time.Now().Add(time.Minute), nil); err != nil || !joined {
t.Fatalf("join = (joined %v, err %v), want joined", joined, err)
}
after, err := svc.SetupDraws(ctx, g.ID)
if err != nil {
t.Fatalf("setup draws after join: %v", err)
}
for _, d := range after {
if d.Account == uuid.Nil {
t.Fatalf("draw still NULL after join: %+v", d)
}
if d.Account != starter && d.Account != joiner {
t.Fatalf("draw account %s is neither player", d.Account)
}
}
}
// TestReplayTimeline checks the admin replay timeline reconstructs the dealt racks and one
// played move: the step count, the drawn tiles, the bag remainder, the running score and the
// turn cursor.
func TestReplayTimeline(t *testing.T) {
ctx := context.Background()
svc := newGameService()
a := provisionAccount(t)
b := provisionAccount(t)
seed := evenOpeningSeed(t)
g, err := svc.Create(ctx, game.CreateParams{Variant: engine.VariantEnglish, Seats: []uuid.UUID{a, b}, TurnTimeout: 24 * time.Hour, Seed: seed})
if err != nil {
t.Fatalf("create: %v", err)
}
hint, ok := newMirror(t, seed, 2).HintView()
if !ok || len(hint.Tiles) == 0 {
t.Fatal("no opening move for the seed")
}
if _, err := svc.SubmitPlay(ctx, g.ID, a, hint.Tiles); err != nil {
t.Fatalf("play: %v", err)
}
tl, err := svc.ReplayTimeline(ctx, g.ID)
if err != nil {
t.Fatalf("replay timeline: %v", err)
}
if len(tl.Steps) != 2 {
t.Fatalf("steps = %d, want 2 (deal + one move)", len(tl.Steps))
}
deal := tl.Steps[0]
if deal.Move != nil {
t.Fatalf("step 0 must be the deal, got move %+v", deal.Move)
}
rackSize := len(deal.Racks[0])
if rackSize == 0 || len(deal.Racks) != 2 || len(deal.Racks[1]) != rackSize {
t.Fatalf("deal racks = %v, want two equal full racks", deal.Racks)
}
move := tl.Steps[1]
if move.Move == nil || move.Move.Action != "play" {
t.Fatalf("step 1 move = %+v, want a play", move.Move)
}
if len(move.Drawn) != len(hint.Tiles) {
t.Fatalf("drawn = %v, want %d refilled tiles", move.Drawn, len(hint.Tiles))
}
if move.BagLen != deal.BagLen-len(hint.Tiles) {
t.Fatalf("bag after play = %d, want %d", move.BagLen, deal.BagLen-len(hint.Tiles))
}
if len(move.Racks[0]) != rackSize {
t.Fatalf("mover rack after refill = %d, want %d", len(move.Racks[0]), rackSize)
}
if move.Scores[0] <= 0 {
t.Fatalf("seat 0 score after play = %d, want > 0", move.Scores[0])
}
if move.ToMove != 1 {
t.Fatalf("to_move after seat 0 play = %d, want 1", move.ToMove)
}
}
+36 -2
View File
@@ -26,9 +26,10 @@ import (
// assembly, and the stats reader. Helpers used by a single test file stay in
// that file; everything reused across files lives here.
// newGameService builds a game service over the shared pool and registry.
// newGameService builds a game service over the shared pool and registry, with a
// deterministic first-move draw so the suite keeps a stable turn order.
func newGameService() *game.Service {
return game.NewService(
svc := game.NewService(
game.NewStore(testDB),
account.NewStore(testDB),
testRegistry,
@@ -40,6 +41,39 @@ func newGameService() *game.Service {
},
zap.NewNop(),
)
svc.SetFirstMoveEntropy(seatZeroFirstMove)
return svc
}
// seatZeroFirstMove is a first-move-draw entropy factory that always elects the first
// listed account as the leader, keeping the integration suite's turn order stable
// despite the real draw's randomness: the first contender draws a blank — the best
// possible tile — and wins outright, the rest draw the first remaining tile. It is a
// factory so each game restarts the one-shot "blank" pick.
func seatZeroFirstMove() func(n int) (int, error) {
first := true
return func(n int) (int, error) {
if first {
first = false
return n - 1, nil // a blank sits last in the bag → best rank
}
return 0, nil
}
}
// seatOneFirstMove is a first-move-draw entropy factory that elects the second contender (in
// auto-match, the synthetic opponent) as the leader, so the caller is seated at seat 1: the
// first contender draws the first remaining tile and the second draws a blank, winning.
func seatOneFirstMove() func(n int) (int, error) {
pick := 0
return func(n int) (int, error) {
i := 0
if pick == 1 {
i = n - 1 // the second contender draws a blank → best rank
}
pick++
return i, nil
}
}
// newSocialService builds a social service over the shared pool, reading game
+14 -11
View File
@@ -18,8 +18,9 @@ import (
// The open-game suite covers an auto-match game that a player enters immediately and
// waits inside (status 'open', the opponent seat empty) until a human or a robot joins.
// evenOpeningSeed returns an even seed (so OpenOrJoin seats the starter at seat 0, which
// moves first) whose fresh two-player English opening rack has a legal move.
// evenOpeningSeed returns a seed whose fresh two-player English opening rack (seat 0) has a
// legal move, for tests that drive or attempt an opening play. It scans even seeds; seat
// order no longer depends on the seed — the first-move draw decides it (docs/ARCHITECTURE.md §6).
func evenOpeningSeed(t *testing.T) int64 {
t.Helper()
for seed := int64(2); seed <= 400; seed += 2 {
@@ -59,9 +60,9 @@ func openGame(t *testing.T, svc *game.Service, starter uuid.UUID, seed int64) ga
return g
}
// TestOpenGameStarterMovesThenWaits checks the starter (seat 0) may move on their turn
// while the game is open, after which it is the empty opponent seat's turn and the
// starter just waits.
// TestOpenGameStarterMovesThenWaits checks the starter may move on their turn while the game
// is open (the first-move draw, run when the game opened, put them at seat 0), after which it
// is the empty opponent seat's turn and the starter just waits.
func TestOpenGameStarterMovesThenWaits(t *testing.T) {
ctx := context.Background()
clearOpenGames(t)
@@ -89,28 +90,30 @@ func TestOpenGameStarterMovesThenWaits(t *testing.T) {
}
}
// TestOpenGameStarterWaitsWhenOpponentMovesFirst checks that when the starter is seated
// at seat 1 (odd seed), the still-empty seat 0 is to move, so the starter cannot act.
// TestOpenGameStarterWaitsWhenOpponentMovesFirst checks that when the first-move draw seats
// the starter at seat 1 (the synthetic opponent won the open draw), the still-empty seat 0 is
// to move, so the starter cannot act until an opponent fills it.
func TestOpenGameStarterWaitsWhenOpponentMovesFirst(t *testing.T) {
ctx := context.Background()
clearOpenGames(t)
svc := newGameService()
svc.SetFirstMoveEntropy(seatOneFirstMove) // the synthetic opponent wins → the caller sits at seat 1
starter := provisionAccount(t)
g, _, err := svc.OpenOrJoin(ctx, starter, openParams(1), time.Now().Add(time.Minute), nil)
if err != nil {
t.Fatalf("open: %v", err)
}
if g.ToMove != 0 || g.Seats[0].AccountID != uuid.Nil {
t.Fatalf("odd-seed open game: to_move %d seat0 %s, want the empty seat 0 to move", g.ToMove, g.Seats[0].AccountID)
t.Fatalf("opponent-won open draw: to_move %d seat0 %s, want the empty seat 0 to move", g.ToMove, g.Seats[0].AccountID)
}
if _, err := svc.Pass(ctx, g.ID, starter); !errors.Is(err, game.ErrNotYourTurn) {
t.Fatalf("starter acting on the empty seat's turn = %v, want ErrNotYourTurn", err)
}
}
// TestOpenGameJoinAfterStarterMoved checks a second human joins an open game even after
// the starter has already made their first move, landing on the board mid-opening and
// able to act on their turn.
// TestOpenGameJoinAfterStarterMoved checks a second human joins an open game even after the
// starter has already made their first move: the seats were fixed by the draw at open, so the
// joiner takes the empty seat without disturbing the journal, and can act on their turn.
func TestOpenGameJoinAfterStarterMoved(t *testing.T) {
ctx := context.Background()
clearOpenGames(t)
@@ -0,0 +1,24 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type GameSetupDraws struct {
GameID uuid.UUID `sql:"primary_key"`
Round int16 `sql:"primary_key"`
PickNo int16 `sql:"primary_key"`
AccountID *uuid.UUID
Letter string
IsBlank bool
DrawRank int16
CreatedAt time.Time
}
@@ -0,0 +1,99 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var GameSetupDraws = newGameSetupDrawsTable("backend", "game_setup_draws", "")
type gameSetupDrawsTable struct {
postgres.Table
// Columns
GameID postgres.ColumnString
Round postgres.ColumnInteger
PickNo postgres.ColumnInteger
AccountID postgres.ColumnString
Letter postgres.ColumnString
IsBlank postgres.ColumnBool
DrawRank postgres.ColumnInteger
CreatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type GameSetupDrawsTable struct {
gameSetupDrawsTable
EXCLUDED gameSetupDrawsTable
}
// AS creates new GameSetupDrawsTable with assigned alias
func (a GameSetupDrawsTable) AS(alias string) *GameSetupDrawsTable {
return newGameSetupDrawsTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new GameSetupDrawsTable with assigned schema name
func (a GameSetupDrawsTable) FromSchema(schemaName string) *GameSetupDrawsTable {
return newGameSetupDrawsTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new GameSetupDrawsTable with assigned table prefix
func (a GameSetupDrawsTable) WithPrefix(prefix string) *GameSetupDrawsTable {
return newGameSetupDrawsTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new GameSetupDrawsTable with assigned table suffix
func (a GameSetupDrawsTable) WithSuffix(suffix string) *GameSetupDrawsTable {
return newGameSetupDrawsTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newGameSetupDrawsTable(schemaName, tableName, alias string) *GameSetupDrawsTable {
return &GameSetupDrawsTable{
gameSetupDrawsTable: newGameSetupDrawsTableImpl(schemaName, tableName, alias),
EXCLUDED: newGameSetupDrawsTableImpl("", "excluded", ""),
}
}
func newGameSetupDrawsTableImpl(schemaName, tableName, alias string) gameSetupDrawsTable {
var (
GameIDColumn = postgres.StringColumn("game_id")
RoundColumn = postgres.IntegerColumn("round")
PickNoColumn = postgres.IntegerColumn("pick_no")
AccountIDColumn = postgres.StringColumn("account_id")
LetterColumn = postgres.StringColumn("letter")
IsBlankColumn = postgres.BoolColumn("is_blank")
DrawRankColumn = postgres.IntegerColumn("draw_rank")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
allColumns = postgres.ColumnList{GameIDColumn, RoundColumn, PickNoColumn, AccountIDColumn, LetterColumn, IsBlankColumn, DrawRankColumn, CreatedAtColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, LetterColumn, IsBlankColumn, DrawRankColumn, CreatedAtColumn}
defaultColumns = postgres.ColumnList{IsBlankColumn, CreatedAtColumn}
)
return gameSetupDrawsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
GameID: GameIDColumn,
Round: RoundColumn,
PickNo: PickNoColumn,
AccountID: AccountIDColumn,
Letter: LetterColumn,
IsBlank: IsBlankColumn,
DrawRank: DrawRankColumn,
CreatedAt: CreatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -31,6 +31,7 @@ func UseSchema(schema string) {
GameInvitations = GameInvitations.FromSchema(schema)
GameMoves = GameMoves.FromSchema(schema)
GamePlayers = GamePlayers.FromSchema(schema)
GameSetupDraws = GameSetupDraws.FromSchema(schema)
Games = Games.FromSchema(schema)
Identities = Identities.FromSchema(schema)
Sessions = Sessions.FromSchema(schema)
@@ -0,0 +1,31 @@
-- +goose Up
-- The first-move draw (docs/ARCHITECTURE.md §6): before a game starts, each seated
-- player draws one tile from the bag and the tile closest to "A" decides who moves
-- first (a blank supersedes all letters); players tied for the best tile re-draw
-- until a single leader remains. Each draw uses fresh entropy (not the game's
-- deterministic bag seed), so this record — not a seed — is the only account of how
-- the order was chosen. It is kept for tournaments, where the draw becomes a manual
-- per-tile call. The record is dictionary-independent: the decoded letter, the blank
-- flag and the numeric draw rank describe each draw without any alphabet table. The
-- winner is reflected as seat 0 in game_players, so no order column is duplicated
-- here. In auto-match the opponent is unknown at draw time (the draw runs against a
-- synthetic placeholder when the game opens), so their draw rows carry a NULL account_id,
-- back-filled when a real opponent joins. Hidden from players for now; surfaced only in the
-- admin console.
SET search_path = backend, pg_catalog;
CREATE TABLE game_setup_draws (
game_id uuid NOT NULL REFERENCES games (game_id) ON DELETE CASCADE,
round smallint NOT NULL,
pick_no smallint NOT NULL,
account_id uuid REFERENCES accounts (account_id) ON DELETE CASCADE,
letter text NOT NULL,
is_blank boolean NOT NULL DEFAULT false,
draw_rank smallint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (game_id, round, pick_no)
);
-- +goose Down
SET search_path = backend, pg_catalog;
DROP TABLE game_setup_draws;
@@ -523,6 +523,34 @@ func (s *Server) consoleGameDetail(c *gin.Context) {
}
}
}
// First-move draw (docs/ARCHITECTURE.md §6) and the step-by-step replay timeline. Both are
// best-effort: a game that predates the draw or cannot be replayed still renders its
// summary and seats.
names := make(map[string]string, len(view.Seats))
for _, st := range view.Seats {
names[st.AccountID] = st.DisplayName
}
if draws, derr := s.games.SetupDraws(ctx, g.ID); derr == nil {
for _, d := range draws {
row := adminconsole.SetupDrawRow{Round: d.Round, Letter: strings.ToUpper(d.Letter), Blank: d.Blank, Rank: d.Rank}
if d.Account == uuid.Nil {
row.Name = "(opponent)"
} else {
row.Name = names[d.Account.String()]
row.AccountID = d.Account.String()
}
view.SetupDraws = append(view.SetupDraws, row)
}
}
if len(view.Seats) > 0 {
view.FirstMover = view.Seats[0].DisplayName
}
if tl, terr := s.games.ReplayTimeline(ctx, g.ID); terr == nil {
if rj, jerr := buildReplayJSON(g.Variant, tl, view.Seats); jerr == nil {
view.ReplayJSON = rj
view.HasReplay = len(tl.Steps) > 0
}
}
s.renderConsole(c, "game_detail", "games", "Game", view)
}
@@ -0,0 +1,168 @@
package server
import (
"encoding/json"
"html/template"
"strings"
"scrabble/backend/internal/adminconsole"
"scrabble/backend/internal/engine"
"scrabble/backend/internal/game"
)
// The admin game-replay payload embedded in the game_detail page for its vanilla-JS stepper:
// the premium board layout, the seats and one step per replay frame (the dealt racks, then
// one per move) carrying the resulting racks, scores, turn cursor and bag size. Letters are
// upper-cased for display and carry their tile value (0 renders without a subscript).
type replayTileJSON struct {
L string `json:"l"`
V int `json:"v"`
B bool `json:"b,omitempty"`
}
type replayPlaceJSON struct {
R int `json:"r"`
C int `json:"c"`
L string `json:"l"`
V int `json:"v"`
B bool `json:"b,omitempty"`
}
type replayMoveJSON struct {
Seat int `json:"seat"`
Action string `json:"action"`
Words []string `json:"words,omitempty"`
Score int `json:"score"`
Placements []replayPlaceJSON `json:"placements,omitempty"`
Exchanged []replayTileJSON `json:"exchanged,omitempty"`
}
type replayStepJSON struct {
Move *replayMoveJSON `json:"move"`
Drawn []replayTileJSON `json:"drawn,omitempty"`
Racks [][]replayTileJSON `json:"racks"`
Scores []int `json:"scores"`
ToMove int `json:"toMove"`
BagLen int `json:"bagLen"`
}
type replaySeatJSON struct {
Seat int `json:"seat"`
Name string `json:"name"`
AccountID string `json:"accountId"`
}
type replayDataJSON struct {
Centre [2]int `json:"centre"`
Premium [][]string `json:"premium"`
Seats []replaySeatJSON `json:"seats"`
Steps []replayStepJSON `json:"steps"`
}
// buildReplayJSON renders a game's replay timeline as the JSON the stepper consumes, resolving
// each tile's value from the variant's alphabet. The result is safe to embed in a <script>:
// encoding/json escapes <, > and & to \u00xx, so a user-chosen seat name cannot break out.
func buildReplayJSON(variant engine.Variant, tl game.ReplayTimelineView, seats []adminconsole.SeatRow) (template.JS, error) {
values := map[string]int{}
if table, err := engine.AlphabetTable(variant); err == nil {
for _, e := range table {
values[e.Letter] = e.Value
}
}
tile := func(letter string, blank bool) replayTileJSON {
v := 0
if !blank {
v = values[strings.ToLower(letter)]
}
return replayTileJSON{L: strings.ToUpper(letter), V: v, B: blank}
}
tiles := func(letters []string) []replayTileJSON {
out := make([]replayTileJSON, len(letters))
for i, l := range letters {
out[i] = tile(l, l == "?")
}
return out
}
data := replayDataJSON{Centre: [2]int{7, 7}, Premium: premiumGrid(variant)}
for _, s := range seats {
data.Seats = append(data.Seats, replaySeatJSON{Seat: s.Seat, Name: s.DisplayName, AccountID: s.AccountID})
}
for _, st := range tl.Steps {
js := replayStepJSON{
Racks: make([][]replayTileJSON, len(st.Racks)),
Scores: st.Scores,
ToMove: st.ToMove,
BagLen: st.BagLen,
Drawn: tiles(st.Drawn),
}
for i, r := range st.Racks {
js.Racks[i] = tiles(r)
}
if st.Move != nil {
m := &replayMoveJSON{Seat: st.Move.Seat, Action: st.Move.Action, Words: st.Move.Words, Score: st.Move.Score}
for _, p := range st.Move.Tiles {
t := tile(p.Letter, p.Blank)
m.Placements = append(m.Placements, replayPlaceJSON{R: p.Row, C: p.Col, L: t.L, V: t.V, B: t.B})
}
m.Exchanged = tiles(st.Move.Exchanged)
js.Move = m
}
data.Steps = append(data.Steps, js)
}
b, err := json.Marshal(data)
if err != nil {
return "", err
}
return template.JS(b), nil
}
// premiumRows is the standard Scrabble premium-square layout: T triple-word, D double-word,
// t triple-letter, d double-letter, * the centre double-word, '.' a plain square.
var premiumRows = []string{
"T..d...T...d..T",
".D...t...t...D.",
"..D...d.d...D..",
"d..D...d...D..d",
"....D.....D....",
".t...t...t...t.",
"..d...d.d...d..",
"T..d...*...d..T",
"..d...d.d...d..",
".t...t...t...t.",
"....D.....D....",
"d..D...d...D..d",
"..D...d.d...D..",
".D...t...t...D.",
"T..d...T...d..T",
}
// premiumGrid returns the 15×15 premium-square codes ("tw"/"dw"/"tl"/"dl"/"") for variant.
// Erudite carries no double-word premium on the centre square (only the start star).
func premiumGrid(variant engine.Variant) [][]string {
code := func(ch byte) string {
switch ch {
case 'T':
return "tw"
case 'D', '*':
return "dw"
case 't':
return "tl"
case 'd':
return "dl"
}
return ""
}
grid := make([][]string, len(premiumRows))
for r, row := range premiumRows {
grid[r] = make([]string, len(row))
for c := 0; c < len(row); c++ {
grid[r][c] = code(row[c])
}
}
if variant == engine.VariantErudit {
grid[7][7] = ""
}
return grid
}
+22 -2
View File
@@ -327,6 +327,21 @@ Key points:
timed out while asleep. A game whose journal can no longer be replayed — a
committed move made illegal by a later rule change — is instead closed as a
**draw** (`aborted`) on the next open, never left unopenable (§9.1).
- **First move (who goes first)**: decided by the official draw — each seated player
draws one tile and the tile closest to "A" leads (a **blank supersedes all letters**);
players tied for the best tile re-draw until a single leader remains. Each draw uses
**fresh entropy** (`crypto/rand`), **not** the deterministic bag `seed`, so the draw is
genuinely random and its **record** — not a seed — is the only account of the outcome. The
leader takes **seat 0** (which moves first), the rest keeping their seating order, so the
engine and journal replay are unchanged (seat 0 always leads). A directly-seated game
(friend/AI) draws at creation. **Auto-match** draws when the game **opens**, with the
not-yet-arrived opponent as a synthetic placeholder (`uuid.Nil`, whose draw rows are
back-filled to the real opponent on join), so the opener's seat is fixed up front and they
may make their opening move while waiting with no later reseating. The draw is **recorded**
with the game (`game_setup_draws`, §9) and surfaced only in the admin console's
step-by-step game replay — **not shown to players** today; it is kept for future
tournaments, where it becomes a manual, per-tile external call. It is modelled as a discrete
"player N draws a tile" step so that API is a thin driver over the same component.
- **Players**: auto-match is always 2 players; friend games are 24 players.
`backend` owns turn order and the bag for any player count. A resignation or
timeout in a two-player game ends it with the other player winning. In a game
@@ -615,7 +630,8 @@ in either direction (the enqueue excludes the caller's `BlockedWith` set);
the `kind` admitting `robot`),
`sessions` (revoke-only opaque-token hashes), the game tables
`games` (carrying the `dropout_tiles` disposition column), `game_players`,
`game_moves` (the move journal), `complaints`, `account_stats` and
`game_moves` (the move journal), `game_setup_draws` (the first-move draw record, §6),
`complaints`, `account_stats` and
`account_best_move`, and the
social/lobby tables `friendships` (the request/accept graph, its status admitting
`declined`), `blocks`
@@ -630,7 +646,11 @@ in either direction (the enqueue excludes the caller's `BlockedWith` set);
Auto-match has no separate store: a game **awaiting an opponent** is an ordinary
`games` row with status `open` and a single seated `game_players` row (the empty
opponent seat is a null `account_id`, filled when a human or robot joins), plus an
`open_deadline_at` stamp the reaper scans for robot substitution.
`open_deadline_at` stamp the reaper scans for robot substitution. The **first-move draw**
(§6) is recorded in `game_setup_draws` when the game opens; the synthetic opponent's rows
carry a NULL `account_id` until a real opponent joins and back-fills them. The record is
dictionary-independent — a decoded letter, a blank flag and the numeric draw rank — like
the journal (§9.1), so it never depends on a dictionary or the solver's encoding.
- **Active games are event-sourced.** A game is a `games` row (pinned
`variant`/`dict_version`, bag `seed`, the per-game settings, and a denormalised
turn cursor) plus an append-only, decoded move journal (`game_moves`); the live
+3 -2
View File
@@ -271,8 +271,9 @@ at its end (the game could not be continued), and the same note rides the GCG ex
Operators reach a server-rendered admin console at `${DOMAIN}/_gm` — the backend
renders it; the gateway gates it with HTTP Basic Auth on its public listener and
proxies it verbatim. The console lists and inspects **users** (profile, statistics,
identities, their games) and **games** (summary + seats), works the **word-complaint
review queue** — resolving each as reject / accept-add / accept-remove — and exposes
identities, their games) and **games** summary, seats, the recorded **first-move tile
draw** (who drew what, deciding who leads), and a simple **step-by-step board replay** of the
whole game — works the **word-complaint review queue** — resolving each as reject / accept-add / accept-remove — and exposes
the **dictionary**: the active version new games pin, the resident versions per
variant, an online **dictionary update** (upload the `scrabble-dawg-vX.Y.Z.tar.gz`
release archive, preview the words added and removed per variant against the active
+3 -1
View File
@@ -277,7 +277,9 @@ UTC), суточного окна отсутствия (away; сетка по 10
Оператор открывает серверную админ-консоль по адресу `${DOMAIN}/_gm` — её рендерит
backend; gateway закрывает её HTTP Basic Auth на публичном порту и проксирует
один-в-один. В консоли можно смотреть **пользователей** (профиль, статистика,
identity, их игры) и **игры** (сводка + места), разбирать **очередь жалоб на слова**
identity, их игры) и **игры** сводка, места, записанная **жеребьёвка первого хода** (кто что
вытащил и кто ходит первым) и простой **пошаговый реплей доски** всей партии, — разбирать
**очередь жалоб на слова**
закрывая каждую как reject / accept-add / accept-remove — и управлять **словарём**:
активная версия, на которую опираются новые партии, резидентные версии по вариантам,
онлайн-**обновление словаря** (загрузить релизный архив `scrabble-dawg-vX.Y.Z.tar.gz`,
@@ -0,0 +1,161 @@
# First-move tile-draw seeding + admin game replay — design
- Date: 2026-06-19
- Branch: `feature/first-move-draw`
- Status: approved (owner sign-off 2026-06-19)
## Goal
Two linked pieces.
1. **First-move selection by the official rule.** Each seated player draws one tile
from the bag; the tile alphabetically closest to "A" wins, a blank superseding all
letters. Players tied for the best tile re-draw until a single leader remains. Each
draw uses fresh entropy — **not** the game's deterministic seed. The whole draw
process is persisted with the game (not shown to players yet; needed later for
tournaments, where the draw becomes a manual, per-tile external "player N draws a
tile" call). A game must not start until the draw has produced a leader. The future
API is not designed here, but the code exposes the draw as a discrete step.
2. **Admin replay on `/_gm/games/:id`.** A simple board that steps move-by-move:
column (AO) and row (115) headers, highlighted premium squares, placed letters
drawn upper-case with the tile value as a subscript (0 → no number), rack panels
around the board (seat 0 top, 1 bottom, 2 left, 3 right) labelled by player name
with a profile link and the current player's rack highlighted, prev/next stepping,
and a per-move log line with the move, the tiles drawn from the bag, and the bag
remainder. The first-move draw is shown as a flat list of actions, not stepped on
the board.
## Decisions (owner interview, 2026-06-19)
- **Comparison key:** alphabetical (alphabet index; closest to "A" wins; blank
supersedes). Not tile point value.
- **The draw decides only the first player;** the rest keep their seating order (the
circle is rotated so the winner leads).
- **Persistence:** a dedicated table `game_setup_draws` (one row per draw),
tournament / manual-API ready.
- **Lifecycle:** a code seam only (a seeding component with a per-draw method); no
persisted `seeding` status yet (the auto path runs it synchronously at the active
transition).
## Design
### Seeding (`internal/game/seating.go`)
- A component shaped as a finite state machine, ready for a future per-tile external
call. Entropy is a parameter (interface / `io.Reader`); production uses
`crypto/rand`, tests inject a deterministic source so the ranking / tie / rotation
logic is unit-testable.
- **A round:** honestly shuffle the variant's full tile multiset (`rules.Counts` +
blanks) with fresh entropy and draw one tile **without replacement** for each
participant. This realises "shuffle before each draw, not a single seed".
- **Rank:** blank = best (`-1`); letter = alphabet index (`0` = closest to "A").
Lower rank moves earlier.
- **Tie:** participants sharing the best rank re-draw in the next round (others drop
out) until a single leader remains.
- **Result:** the winner plus the full draw log.
### Turn order — seat rotation
The draw affects the game only through who occupies **seat 0** (seat 0 moves first;
the engine/replay invariant is unchanged). Rotate the seated-account circle so the
winner sits at seat 0, preserving the cyclic order of the rest. This generalises the
current `seed&1` swap (2 players) and replaces both `seed&1` (auto-match) and
"`Seats[0]` first" (friend/AI). It applies to every new game.
The engine deals racks by seat **index** and is account-agnostic, and journal replay
starts at seat 0, so **no engine or replay change is needed** — only the seat→account
mapping in `game_players`.
### Persistence — `game_setup_draws` (migration `00013`)
```sql
CREATE TABLE backend.game_setup_draws (
game_id uuid NOT NULL REFERENCES backend.games (game_id) ON DELETE CASCADE,
round smallint NOT NULL,
pick_no smallint NOT NULL,
account_id uuid NOT NULL REFERENCES backend.accounts (account_id),
letter text NOT NULL,
is_blank boolean NOT NULL DEFAULT false,
rank smallint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (game_id, round, pick_no)
);
```
Self-contained and dictionary-independent (decoded letter + blank flag + numeric
rank), like the §9.1 journal. The first mover is visible as seat 0 in `game_players`,
so there is no redundant column. Additive — existing games have no rows (no backfill).
The future tournament API appends one row per draw call.
### Wiring — the active transition
- **Create (friend/AI):** run the seeding over `params.Seats`, persist the draw rows,
rotate the account list so the winner is index 0, then proceed unchanged
(`engine.New` takes only the seat count). All within the create transaction.
- **Auto-match:** the second player is unknown until the seat is filled, so the
seeding runs at `fillOpenSeat` (human join) and `AttachRobot` (robot) inside the
fill transaction. The seat assignment is written from the draw outcome (seat 0 =
winner) rather than only filling the empty seat; the open-time `seed&1` pre-seating
is dropped.
The auto path calls the seeding component synchronously in a loop. No persisted
`seeding` status; the seam in code is what a future manual API drives.
### Admin replay
- **Data:** a new service method `ReplayTimeline(gameID)` reuses the existing
`replay()` (engine rebuilt from seed + journal) and snapshots after each move: every
seat's rack (`Hand(i)`), score (`Score(i)`), the seat to move (`ToMove()`), the bag
remainder (`BagLen()`), plus per move the action, placements, words, and the tiles
drawn from the bag (multiset diff: `hand_after (hand_before used)`; `hand_before`
from the journal). Step 0 is the dealt racks. The board at step k is the placements
of plays 1..k applied onto an empty grid (no dictionary — §9.1 visual replay).
- **UI:** server-rendered Go `html/template` plus a small page-scoped vanilla-JS
stepper over the timeline embedded as JSON (no per-step round-trip). The board
renders headers, highlighted premium squares (a standard fixed 15×15 layout
duplicated as a Go constant — `premiums.ts` is itself such a constant; the admin is
not coupled to solver internals), upper-case letters with the value subscript (0 → no
number) in tile-styled cells. Rack panels: seat 0 top, 1 bottom, 2 left, 3 right;
name + profile link; the current player's rack highlighted. A log accumulates by move
(play / pass / exchange + drawn tiles + bag remainder), the current step highlighted.
The seeding is a separate flat list ("Round N: player X — E(rank), … → Y leads
first"), with profile links.
## Tests
- **Seeding:** ranking (blank beats letters; closer to "A" wins), tie chains, rotation
for 2/3/4 seats, record determinism under an injected entropy source.
- **ReplayTimeline:** drawn tiles / bag remainder / racks / scores on a known short
game.
- **Store / integration:** write+read `game_setup_draws`; seat 0 = winner for both
Create and auto-match.
## Out of scope
The tournament draw API itself (only the seam). No change to the game bag's
determinism or replay. No reuse / rewrite of the Svelte board in the admin. The board
design is deliberately minimal.
## Docs to bake back (same PR)
`docs/ARCHITECTURE.md` (§6 seeding procedure, §9 table, §9.1-style record invariant),
`docs/FUNCTIONAL.md` (+ `_ru`) first-move-selection story, backend / admin READMEs, Go
Doc comments, `PRERELEASE.md` note.
## Update (2026-06-20) — final auto-match design
During implementation the owner replaced the auto-match approach. The original plan above ran
the draw at **fill** time (when the opponent joins) and **reseated** the winner to seat 0. That
conflicts with the existing open-game feature where the opener may play their opening move
while waiting: reseating after a move would corrupt the journal's seat↔move mapping.
The final design runs the draw when the game **opens**, with the not-yet-arrived opponent as a
synthetic placeholder (`uuid.Nil`). The draw fixes the opener's seat up front; the opponent
joins into the already-decided empty seat with **no reseating**, so the open-game pre-move is
preserved and the journal is never disturbed. The opponent's draw rows are persisted with a
NULL `account_id` (so `game_setup_draws.account_id` is **nullable**) and **back-filled** to the
real opponent (or robot) on join. The directly-seated (friend/AI) path is unchanged from the
plan (draw at create, real accounts, no synthetic). Consequently there is **no play-gating and
no rack-hiding** while a game is open. See `docs/ARCHITECTURE.md` §6 / §9 for the authoritative
description.