diff --git a/backend/internal/account/stats.go b/backend/internal/account/stats.go
index 707361f..4df748c 100644
--- a/backend/internal/account/stats.go
+++ b/backend/internal/account/stats.go
@@ -2,6 +2,7 @@ package account
import (
"context"
+ "encoding/json"
"errors"
"fmt"
@@ -13,16 +14,39 @@ import (
"scrabble/backend/internal/postgres/jet/backend/table"
)
+// BestMoveTile is one letter cell of a best-move word: its concrete letter (the
+// designated letter for a blank), its tile point value (0 for a blank) and whether it
+// is a blank. It is the persisted/served shape: the game domain marshals a slice of
+// these into account_best_move.tiles, and the statistics screen renders them as game
+// tiles without consulting the variant's alphabet.
+type BestMoveTile struct {
+ Letter string `json:"letter"`
+ Value int `json:"value"`
+ Blank bool `json:"blank"`
+}
+
+// BestMove is an account's highest-scoring single play within one game variant: the
+// move's total score (every word it formed plus the all-tiles bonus, matching
+// MaxWordPoints) and its main word as an ordered slice of tiles.
+type BestMove struct {
+ Variant string
+ Score int
+ Tiles []BestMoveTile
+}
+
// Stats is a durable account's lifetime record, written by the game domain on each
// finish and read for the player's statistics screen. MaxGamePoints is the best
// single game's total; MaxWordPoints is the best single move's score (which already
-// includes every word it formed plus the all-tiles bonus).
+// includes every word it formed plus the all-tiles bonus). BestMoves holds the same
+// best move broken down per variant, with the word itself — empty for an account with
+// no recorded play yet, and never carrying a variant the account has not played.
type Stats struct {
Wins int
Losses int
Draws int
MaxGamePoints int
MaxWordPoints int
+ BestMoves []BestMove
}
// GetStats returns the lifetime statistics for id. An account with no account_stats
@@ -40,11 +64,46 @@ func (s *Store) GetStats(ctx context.Context, id uuid.UUID) (Stats, error) {
}
return Stats{}, fmt.Errorf("account: get stats %s: %w", id, err)
}
+ best, err := s.bestMoves(ctx, id)
+ if err != nil {
+ return Stats{}, err
+ }
return Stats{
Wins: int(row.Wins),
Losses: int(row.Losses),
Draws: int(row.Draws),
MaxGamePoints: int(row.MaxGamePoints),
MaxWordPoints: int(row.MaxWordPoints),
+ BestMoves: best,
}, nil
}
+
+// bestMoves reads an account's per-variant best moves, ordered by variant for a stable
+// response. Each row's tiles JSON is decoded into the served BestMoveTile slice. An
+// account with no recorded play yields an empty (nil) slice rather than an error.
+func (s *Store) bestMoves(ctx context.Context, id uuid.UUID) ([]BestMove, error) {
+ stmt := postgres.SELECT(
+ table.AccountBestMove.Variant,
+ table.AccountBestMove.Score,
+ table.AccountBestMove.Tiles,
+ ).
+ FROM(table.AccountBestMove).
+ WHERE(table.AccountBestMove.AccountID.EQ(postgres.UUID(id))).
+ ORDER_BY(table.AccountBestMove.Variant.ASC())
+ var rows []model.AccountBestMove
+ if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
+ if errors.Is(err, qrm.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("account: best moves %s: %w", id, err)
+ }
+ out := make([]BestMove, 0, len(rows))
+ for _, r := range rows {
+ var tiles []BestMoveTile
+ if err := json.Unmarshal([]byte(r.Tiles), &tiles); err != nil {
+ return nil, fmt.Errorf("account: decode best-move tiles %s/%s: %w", id, r.Variant, err)
+ }
+ out = append(out, BestMove{Variant: r.Variant, Score: int(r.Score), Tiles: tiles})
+ }
+ return out, nil
+}
diff --git a/backend/internal/game/service.go b/backend/internal/game/service.go
index b2c0e89..359cf35 100644
--- a/backend/internal/game/service.go
+++ b/backend/internal/game/service.go
@@ -1419,19 +1419,41 @@ func replayMove(g *engine.Game, mv HistoryMove) error {
}
// buildStats derives each seat's statistics contribution from a finished game:
-// win/loss/draw from the (resignation-aware) winner, the final score, and the
-// best single-move score from the log.
+// win/loss/draw from the (resignation-aware) winner, the final score, and the best
+// single play from the log — its score and, for the per-variant breakdown, its main
+// word as rendering tiles. Blank flags are taken from every blank ever placed (so a
+// blank laid by an earlier move and embedded in the best word is honoured), which is
+// equivalent to reading the final board since a placed tile never moves.
func buildStats(g *engine.Game, seats []Seat) []statDelta {
res := g.Result()
- best := make(map[int]int)
+ bestRec := make(map[int]engine.MoveRecord)
+ blanks := make(map[[2]int]bool)
for _, rec := range g.Log() {
- if rec.Action == engine.ActionPlay && rec.Score > best[rec.Player] {
- best[rec.Player] = rec.Score
+ if rec.Action != engine.ActionPlay {
+ continue
+ }
+ for _, t := range rec.Tiles {
+ if t.Blank {
+ blanks[[2]int{t.Row, t.Col}] = true
+ }
+ }
+ if cur, ok := bestRec[rec.Player]; !ok || rec.Score > cur.Score {
+ bestRec[rec.Player] = rec
}
}
+ variant := g.Variant().String()
+ values := letterValues(g.Variant())
out := make([]statDelta, 0, len(seats))
for _, s := range seats {
- d := statDelta{accountID: s.AccountID, gamePoints: g.Score(s.Seat), wordPoints: best[s.Seat]}
+ d := statDelta{accountID: s.AccountID, gamePoints: g.Score(s.Seat)}
+ if rec, ok := bestRec[s.Seat]; ok {
+ d.wordPoints = rec.Score
+ if rec.Score > 0 {
+ d.bestVariant = variant
+ d.bestScore = rec.Score
+ d.bestTiles = mainWordTiles(rec, blanks, values)
+ }
+ }
switch {
case res.Winner < 0:
d.draws = 1
@@ -1445,6 +1467,49 @@ func buildStats(g *engine.Game, seats []Seat) []statDelta {
return out
}
+// letterValues builds a lower-cased letter -> tile value lookup for a variant from the
+// engine's alphabet table, so a best-move word can be rendered with per-tile values on a
+// screen (statistics) that has not cached the variant's alphabet. It is empty for an
+// unrecognised variant, leaving every value zero.
+func letterValues(v engine.Variant) map[string]int {
+ table, err := engine.AlphabetTable(v)
+ if err != nil {
+ return nil
+ }
+ m := make(map[string]int, len(table))
+ for _, e := range table {
+ m[strings.ToLower(e.Letter)] = e.Value
+ }
+ return m
+}
+
+// mainWordTiles decodes a play's main word into rendering tiles: each letter with its
+// tile value (0 for a blank) and blank flag. blanks is the set of board coordinates a
+// blank was ever placed on; values maps a lower-cased letter to its tile value. It walks
+// the word from its first-letter coordinate along the play's orientation.
+func mainWordTiles(rec engine.MoveRecord, blanks map[[2]int]bool, values map[string]int) []account.BestMoveTile {
+ if len(rec.Words) == 0 {
+ return nil
+ }
+ dr, dc := 0, 1
+ if rec.Dir == engine.Vertical {
+ dr, dc = 1, 0
+ }
+ letters := []rune(rec.Words[0])
+ out := make([]account.BestMoveTile, len(letters))
+ for i, r := range letters {
+ row, col := rec.MainRow+i*dr, rec.MainCol+i*dc
+ blank := blanks[[2]int{row, col}]
+ letter := string(r)
+ value := 0
+ if !blank {
+ value = values[strings.ToLower(letter)]
+ }
+ out[i] = account.BestMoveTile{Letter: letter, Value: value, Blank: blank}
+ }
+ return out
+}
+
// nonGuestSeats filters out guest seats so the finish-time statistics are
// recomputed for durable non-guest accounts only — guests never accrue
// statistics (docs/ARCHITECTURE.md §9). It is called once per game, on finish.
diff --git a/backend/internal/game/stats_test.go b/backend/internal/game/stats_test.go
new file mode 100644
index 0000000..cff5a1a
--- /dev/null
+++ b/backend/internal/game/stats_test.go
@@ -0,0 +1,50 @@
+package game
+
+import (
+ "reflect"
+ "testing"
+
+ "scrabble/backend/internal/account"
+ "scrabble/backend/internal/engine"
+)
+
+// TestMainWordTilesHorizontalWithBlank checks that a horizontal main word is decoded into
+// tiles along its row, that the per-letter value is looked up from the value table, and that
+// a blank cell (here the middle 'a') is rendered with a zero value regardless of its letter
+// value — the blank flag is taken from the placed-blank set, not from this move's own tiles.
+func TestMainWordTilesHorizontalWithBlank(t *testing.T) {
+ rec := engine.MoveRecord{Dir: engine.Horizontal, MainRow: 7, MainCol: 5, Words: []string{"cat"}}
+ blanks := map[[2]int]bool{{7, 6}: true}
+ values := map[string]int{"c": 3, "a": 1, "t": 1}
+ got := mainWordTiles(rec, blanks, values)
+ want := []account.BestMoveTile{
+ {Letter: "c", Value: 3, Blank: false},
+ {Letter: "a", Value: 0, Blank: true},
+ {Letter: "t", Value: 1, Blank: false},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("mainWordTiles = %+v, want %+v", got, want)
+ }
+}
+
+// TestMainWordTilesVerticalCyrillic checks vertical walk and multi-byte (Cyrillic) letters:
+// the word must be split by rune, not byte, and laid down its column.
+func TestMainWordTilesVerticalCyrillic(t *testing.T) {
+ rec := engine.MoveRecord{Dir: engine.Vertical, MainRow: 3, MainCol: 8, Words: []string{"съёмка"}}
+ values := map[string]int{"с": 1, "ъ": 10, "ё": 4, "м": 2, "к": 2, "а": 1}
+ got := mainWordTiles(rec, map[[2]int]bool{}, values)
+ want := []account.BestMoveTile{
+ {Letter: "с", Value: 1}, {Letter: "ъ", Value: 10}, {Letter: "ё", Value: 4},
+ {Letter: "м", Value: 2}, {Letter: "к", Value: 2}, {Letter: "а", Value: 1},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("mainWordTiles = %+v, want %+v", got, want)
+ }
+}
+
+// TestMainWordTilesNoWord checks the defensive nil for a record carrying no words.
+func TestMainWordTilesNoWord(t *testing.T) {
+ if got := mainWordTiles(engine.MoveRecord{}, nil, nil); got != nil {
+ t.Errorf("mainWordTiles(no words) = %+v, want nil", got)
+ }
+}
diff --git a/backend/internal/game/store.go b/backend/internal/game/store.go
index f524de1..e720d27 100644
--- a/backend/internal/game/store.go
+++ b/backend/internal/game/store.go
@@ -3,6 +3,7 @@ package game
import (
"context"
"database/sql"
+ "encoding/json"
"errors"
"fmt"
"hash/fnv"
@@ -12,6 +13,7 @@ import (
"github.com/go-jet/jet/v2/qrm"
"github.com/google/uuid"
+ "scrabble/backend/internal/account"
"scrabble/backend/internal/engine"
"scrabble/backend/internal/postgres/jet/backend/model"
"scrabble/backend/internal/postgres/jet/backend/table"
@@ -53,13 +55,20 @@ type gameInsert struct {
}
// statDelta is one account's contribution to its statistics on a game finish.
+// bestVariant/bestScore/bestTiles describe the game's best play for this account when
+// it scored (bestVariant empty otherwise): the variant label, the play's total score and
+// its main word as rendering tiles. They feed the per-variant account_best_move upsert,
+// which keeps only the account's highest-scoring play per variant.
type statDelta struct {
- accountID uuid.UUID
- wins int
- losses int
- draws int
- gamePoints int
- wordPoints int
+ accountID uuid.UUID
+ wins int
+ losses int
+ draws int
+ gamePoints int
+ wordPoints int
+ bestVariant string
+ bestScore int
+ bestTiles []account.BestMoveTile
}
// commit is everything a single committed transition persists: the journal row,
@@ -633,6 +642,9 @@ func (s *Store) CommitMove(ctx context.Context, c commit) error {
if err := upsertStats(ctx, tx, d, c.now); err != nil {
return err
}
+ if err := upsertBestMove(ctx, tx, d, c.now); err != nil {
+ return err
+ }
}
}
return nil
@@ -662,6 +674,9 @@ func (s *Store) VoidGame(ctx context.Context, v voidCommit) error {
if err := upsertStats(ctx, tx, d, v.now); err != nil {
return err
}
+ if err := upsertBestMove(ctx, tx, d, v.now); err != nil {
+ return err
+ }
}
return nil
})
@@ -728,6 +743,37 @@ func upsertStats(ctx context.Context, tx *sql.Tx, d statDelta, now time.Time) er
return nil
}
+// upsertBestMove records the account's best play for a variant, keeping only the
+// highest-scoring one: a first play inserts, a later one replaces it only when it scored
+// strictly higher (the conditional DO UPDATE makes the upsert atomic under concurrent
+// finishes without a separate lock). It is a no-op when the finish carries no scoring play
+// for the account (a draw with no plays, or an exchange/pass-only game).
+func upsertBestMove(ctx context.Context, tx *sql.Tx, d statDelta, now time.Time) error {
+ if d.bestVariant == "" || len(d.bestTiles) == 0 {
+ return nil
+ }
+ tiles, err := json.Marshal(d.bestTiles)
+ if err != nil {
+ return fmt.Errorf("marshal best move %s/%s: %w", d.accountID, d.bestVariant, err)
+ }
+ stmt := table.AccountBestMove.
+ INSERT(
+ table.AccountBestMove.AccountID, table.AccountBestMove.Variant,
+ table.AccountBestMove.Score, table.AccountBestMove.Tiles, table.AccountBestMove.UpdatedAt,
+ ).
+ VALUES(d.accountID, d.bestVariant, d.bestScore, string(tiles), postgres.TimestampzT(now)).
+ ON_CONFLICT(table.AccountBestMove.AccountID, table.AccountBestMove.Variant).
+ DO_UPDATE(postgres.SET(
+ table.AccountBestMove.Score.SET(table.AccountBestMove.EXCLUDED.Score),
+ table.AccountBestMove.Tiles.SET(table.AccountBestMove.EXCLUDED.Tiles),
+ table.AccountBestMove.UpdatedAt.SET(table.AccountBestMove.EXCLUDED.UpdatedAt),
+ ).WHERE(table.AccountBestMove.EXCLUDED.Score.GT(table.AccountBestMove.Score)))
+ if _, err := stmt.ExecContext(ctx, tx); err != nil {
+ return fmt.Errorf("upsert best move %s/%s: %w", d.accountID, d.bestVariant, err)
+ }
+ return nil
+}
+
// SpendHintAllowance increments a seat's per-game hint counter by one.
func (s *Store) SpendHintAllowance(ctx context.Context, gameID uuid.UUID, seat int) error {
stmt := table.GamePlayers.
diff --git a/backend/internal/inttest/account_test.go b/backend/internal/inttest/account_test.go
index 86b1607..c7f1815 100644
--- a/backend/internal/inttest/account_test.go
+++ b/backend/internal/inttest/account_test.go
@@ -89,7 +89,8 @@ func TestGetStatsZeroForFreshAccount(t *testing.T) {
if err != nil {
t.Fatalf("get stats: %v", err)
}
- if (st != account.Stats{}) {
+ zero := st.Wins == 0 && st.Losses == 0 && st.Draws == 0 && st.MaxGamePoints == 0 && st.MaxWordPoints == 0
+ if !zero || len(st.BestMoves) != 0 {
t.Fatalf("fresh stats = %+v, want zero", st)
}
}
diff --git a/backend/internal/inttest/game_test.go b/backend/internal/inttest/game_test.go
index e409443..6b85c70 100644
--- a/backend/internal/inttest/game_test.go
+++ b/backend/internal/inttest/game_test.go
@@ -11,6 +11,7 @@ import (
"github.com/google/uuid"
+ "scrabble/backend/internal/account"
"scrabble/backend/internal/engine"
"scrabble/backend/internal/game"
)
@@ -120,8 +121,8 @@ func TestGameLifecycleAndStats(t *testing.T) {
t.Fatalf("final game not finished: %+v", last.Game)
}
- w0, l0, d0, mg0, _, ok0 := readStats(t, seats[0])
- w1, l1, d1, mg1, _, ok1 := readStats(t, seats[1])
+ w0, l0, d0, mg0, mw0, ok0 := readStats(t, seats[0])
+ w1, l1, d1, mg1, mw1, ok1 := readStats(t, seats[1])
if !ok0 || !ok1 {
t.Fatal("both players must have a stats row")
}
@@ -133,6 +134,44 @@ func TestGameLifecycleAndStats(t *testing.T) {
if !decisive && !draw {
t.Errorf("inconsistent W/L/D: p0(%d/%d/%d) p1(%d/%d/%d)", w0, l0, d0, w1, l1, d1)
}
+
+ // Each player who made a scoring play gets exactly one per-variant best move (only
+ // scrabble_en was played here); its score equals the aggregate max_word_points and it
+ // carries the decoded word as tiles.
+ accounts := account.NewStore(testDB)
+ for _, p := range []struct {
+ id uuid.UUID
+ maxWord int
+ }{{seats[0], mw0}, {seats[1], mw1}} {
+ if p.maxWord == 0 {
+ continue // a player who only passed has no best move
+ }
+ st, err := accounts.GetStats(ctx, p.id)
+ if err != nil {
+ t.Fatalf("get stats: %v", err)
+ }
+ if len(st.BestMoves) != 1 {
+ t.Fatalf("want one best move (only scrabble_en played), got %d: %+v", len(st.BestMoves), st.BestMoves)
+ }
+ bm := st.BestMoves[0]
+ if bm.Variant != engine.VariantEnglish.String() {
+ t.Errorf("best move variant = %q, want %q", bm.Variant, engine.VariantEnglish.String())
+ }
+ if bm.Score != p.maxWord {
+ t.Errorf("best move score %d != max_word_points %d", bm.Score, p.maxWord)
+ }
+ if len(bm.Tiles) == 0 {
+ t.Error("best move word is empty")
+ }
+ for _, tl := range bm.Tiles {
+ if tl.Letter == "" {
+ t.Error("best move tile has empty letter")
+ }
+ if tl.Blank && tl.Value != 0 {
+ t.Errorf("blank tile must score 0, got %d", tl.Value)
+ }
+ }
+ }
}
// TestReplayEquivalence plays a few moves through one service, then proves a
diff --git a/backend/internal/postgres/jet/backend/model/account_best_move.go b/backend/internal/postgres/jet/backend/model/account_best_move.go
new file mode 100644
index 0000000..6ec4fda
--- /dev/null
+++ b/backend/internal/postgres/jet/backend/model/account_best_move.go
@@ -0,0 +1,21 @@
+//
+// 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 AccountBestMove struct {
+ AccountID uuid.UUID `sql:"primary_key"`
+ Variant string `sql:"primary_key"`
+ Score int32
+ Tiles string
+ UpdatedAt time.Time
+}
diff --git a/backend/internal/postgres/jet/backend/table/account_best_move.go b/backend/internal/postgres/jet/backend/table/account_best_move.go
new file mode 100644
index 0000000..5901164
--- /dev/null
+++ b/backend/internal/postgres/jet/backend/table/account_best_move.go
@@ -0,0 +1,90 @@
+//
+// 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 AccountBestMove = newAccountBestMoveTable("backend", "account_best_move", "")
+
+type accountBestMoveTable struct {
+ postgres.Table
+
+ // Columns
+ AccountID postgres.ColumnString
+ Variant postgres.ColumnString
+ Score postgres.ColumnInteger
+ Tiles postgres.ColumnString
+ UpdatedAt postgres.ColumnTimestampz
+
+ AllColumns postgres.ColumnList
+ MutableColumns postgres.ColumnList
+ DefaultColumns postgres.ColumnList
+}
+
+type AccountBestMoveTable struct {
+ accountBestMoveTable
+
+ EXCLUDED accountBestMoveTable
+}
+
+// AS creates new AccountBestMoveTable with assigned alias
+func (a AccountBestMoveTable) AS(alias string) *AccountBestMoveTable {
+ return newAccountBestMoveTable(a.SchemaName(), a.TableName(), alias)
+}
+
+// Schema creates new AccountBestMoveTable with assigned schema name
+func (a AccountBestMoveTable) FromSchema(schemaName string) *AccountBestMoveTable {
+ return newAccountBestMoveTable(schemaName, a.TableName(), a.Alias())
+}
+
+// WithPrefix creates new AccountBestMoveTable with assigned table prefix
+func (a AccountBestMoveTable) WithPrefix(prefix string) *AccountBestMoveTable {
+ return newAccountBestMoveTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
+}
+
+// WithSuffix creates new AccountBestMoveTable with assigned table suffix
+func (a AccountBestMoveTable) WithSuffix(suffix string) *AccountBestMoveTable {
+ return newAccountBestMoveTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
+}
+
+func newAccountBestMoveTable(schemaName, tableName, alias string) *AccountBestMoveTable {
+ return &AccountBestMoveTable{
+ accountBestMoveTable: newAccountBestMoveTableImpl(schemaName, tableName, alias),
+ EXCLUDED: newAccountBestMoveTableImpl("", "excluded", ""),
+ }
+}
+
+func newAccountBestMoveTableImpl(schemaName, tableName, alias string) accountBestMoveTable {
+ var (
+ AccountIDColumn = postgres.StringColumn("account_id")
+ VariantColumn = postgres.StringColumn("variant")
+ ScoreColumn = postgres.IntegerColumn("score")
+ TilesColumn = postgres.StringColumn("tiles")
+ UpdatedAtColumn = postgres.TimestampzColumn("updated_at")
+ allColumns = postgres.ColumnList{AccountIDColumn, VariantColumn, ScoreColumn, TilesColumn, UpdatedAtColumn}
+ mutableColumns = postgres.ColumnList{ScoreColumn, TilesColumn, UpdatedAtColumn}
+ defaultColumns = postgres.ColumnList{UpdatedAtColumn}
+ )
+
+ return accountBestMoveTable{
+ Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
+
+ //Columns
+ AccountID: AccountIDColumn,
+ Variant: VariantColumn,
+ Score: ScoreColumn,
+ Tiles: TilesColumn,
+ UpdatedAt: UpdatedAtColumn,
+
+ AllColumns: allColumns,
+ MutableColumns: mutableColumns,
+ DefaultColumns: defaultColumns,
+ }
+}
diff --git a/backend/internal/postgres/migrations/00009_best_move.sql b/backend/internal/postgres/migrations/00009_best_move.sql
new file mode 100644
index 0000000..529a863
--- /dev/null
+++ b/backend/internal/postgres/migrations/00009_best_move.sql
@@ -0,0 +1,25 @@
+-- +goose Up
+-- Per-account, per-variant best single move: the highest-scoring play the account has
+-- ever made in each game variant. It exists so the statistics screen can show the word
+-- itself broken down by variant, not just the dimensionless aggregate
+-- account_stats.max_word_points. tiles is the move's main word as an ordered JSON array of
+-- {letter, value, blank} objects (value 0 and blank true for a wildcard), so the client
+-- renders it as game tiles without needing the variant's alphabet table. score is the
+-- play's total points (every word it formed plus the all-tiles bonus), matching
+-- max_word_points. A row is replaced only by a strictly higher-scoring play. It is written
+-- at game finish alongside account_stats; guest and honest-AI games never record statistics,
+-- so they never write here. See docs/ARCHITECTURE.md §9.
+SET search_path = backend, pg_catalog;
+
+CREATE TABLE account_best_move (
+ account_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
+ variant text NOT NULL,
+ score integer NOT NULL,
+ tiles jsonb NOT NULL,
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (account_id, variant)
+);
+
+-- +goose Down
+SET search_path = backend, pg_catalog;
+DROP TABLE IF EXISTS account_best_move;
diff --git a/backend/internal/server/handlers_account.go b/backend/internal/server/handlers_account.go
index 55ae838..817af04 100644
--- a/backend/internal/server/handlers_account.go
+++ b/backend/internal/server/handlers_account.go
@@ -29,13 +29,25 @@ type updateProfileRequest struct {
}
// statsDTO is a durable account's lifetime statistics (the derived games-played and
-// win-rate are computed client-side).
+// win-rate are computed client-side). BestMoves breaks the best move down per variant,
+// carrying the word itself; it is absent for an account with no recorded play and never
+// lists a variant the account has not played.
type statsDTO struct {
- Wins int `json:"wins"`
- Losses int `json:"losses"`
- Draws int `json:"draws"`
- MaxGamePoints int `json:"max_game_points"`
- MaxWordPoints int `json:"max_word_points"`
+ Wins int `json:"wins"`
+ Losses int `json:"losses"`
+ Draws int `json:"draws"`
+ MaxGamePoints int `json:"max_game_points"`
+ MaxWordPoints int `json:"max_word_points"`
+ BestMoves []bestMoveDTO `json:"best_moves,omitempty"`
+}
+
+// bestMoveDTO is one variant's best play: the variant label, the play's total score and
+// its main word as ordered tiles (letter, value, blank — value 0 for a blank), so the
+// client renders it as game tiles without the variant's alphabet table.
+type bestMoveDTO struct {
+ Variant string `json:"variant"`
+ Score int `json:"score"`
+ Word []account.BestMoveTile `json:"word"`
}
// parseAwayTime parses an "HH:MM" away-window bound.
@@ -140,11 +152,19 @@ func (s *Server) handleStats(c *gin.Context) {
s.abortErr(c, err)
return
}
+ var best []bestMoveDTO
+ if len(st.BestMoves) > 0 {
+ best = make([]bestMoveDTO, len(st.BestMoves))
+ for i, b := range st.BestMoves {
+ best[i] = bestMoveDTO{Variant: b.Variant, Score: b.Score, Word: b.Tiles}
+ }
+ }
c.JSON(http.StatusOK, statsDTO{
Wins: st.Wins,
Losses: st.Losses,
Draws: st.Draws,
MaxGamePoints: st.MaxGamePoints,
MaxWordPoints: st.MaxWordPoints,
+ BestMoves: best,
})
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 001b408..02e1c1e 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -568,7 +568,8 @@ disguised robot stays indistinguishable from a person.
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` and `account_stats`, and the
+ `game_moves` (the move journal), `complaints`, `account_stats` and
+ `account_best_move`, and the
social/lobby tables `friendships` (the request/accept graph, its status admitting
`declined`), `blocks`
(per-user blocks), `chat_messages` (per-game chat and nudges, carrying the per-message
@@ -597,7 +598,17 @@ disguised robot stays indistinguishable from a person.
seat): wins, losses, **draws**, max points in a game, and
max points for a single **move** (which already folds in every word the move
formed plus the all-tiles bonus). A tie increments draws only; a resignation or
- timeout is a loss for the acting player.
+ timeout is a loss for the acting player. A companion table **`account_best_move`**
+ (keyed by account **and variant**) keeps the highest-scoring single play **per
+ variant** with the word itself: its main word as an ordered JSON array of tiles
+ (letter, tile value, blank flag — value 0 for a blank), so the statistics screen
+ renders it as game tiles without the variant's alphabet table. Blank flags are
+ taken from every blank ever placed in the game (equivalent to reading the final
+ board, since a placed tile never moves). It is replaced only by a strictly
+ higher-scoring play, written in the same finish transaction, and skipped for
+ guest/honest-AI games exactly like `account_stats`. It is filled forward only —
+ plays finished before the table existed are not back-populated (the aggregate
+ `max_word_points` still covers them numerically).
### 9.1 History invariant (must hold forever)
diff --git a/docs/FUNCTIONAL.md b/docs/FUNCTIONAL.md
index e6bd4de..868503e 100644
--- a/docs/FUNCTIONAL.md
+++ b/docs/FUNCTIONAL.md
@@ -230,6 +230,9 @@ game is throwaway). The client shares the `.gcg` file where the platform support
it, otherwise downloads it. Statistics (durable accounts only):
wins, losses, draws, max points in a game, and max points for a single move (the
best play, which already includes every word it formed plus the all-tiles bonus).
+The best move is also broken down **per game variant**, showing the **word itself**
+drawn as game tiles (a wildcard shows its letter but no value) — one row per variant
+the player has played, omitting variants with no plays.
A game that can no longer be continued — because a rule changed and an earlier
move would now be illegal — is closed as a **draw** the moment someone opens it,
never left stuck on an error: the move history shows an impersonal organizer note
diff --git a/docs/FUNCTIONAL_ru.md b/docs/FUNCTIONAL_ru.md
index 025ffa9..0327e0c 100644
--- a/docs/FUNCTIONAL_ru.md
+++ b/docs/FUNCTIONAL_ru.md
@@ -234,6 +234,9 @@ UTC), суточного окна отсутствия (away; сетка по 10
иначе скачивает его. Статистика (только у постоянных аккаунтов):
победы, поражения, ничьи, макс. очков за партию и макс. очков за один ход (лучший
ход, уже включающий все образованные им слова и бонус за все фишки).
+Лучший ход также даётся **с разбивкой по вариантам игры** — **само слово**,
+нарисованное игровыми фишками (wildcard показывает свою букву без очков), по одной
+строке на каждый сыгранный вариант; варианты без ходов не выводятся.
Партия, которую больше нельзя продолжить — из-за изменения правил более ранний ход
стал бы недопустимым, — закрывается **ничьёй** в момент открытия её игроком, а не
остаётся висеть с ошибкой: в конце истории ходов показывается обезличенная заметка
diff --git a/docs/UI_DESIGN.md b/docs/UI_DESIGN.md
index 53b6976..9817245 100644
--- a/docs/UI_DESIGN.md
+++ b/docs/UI_DESIGN.md
@@ -280,8 +280,13 @@ enabled on the first, uncached load) and flip in place when an event refreshes t
everywhere (score card, lobby row, turn line), the add-friend 🤝 is never drawn, and the chat's
send field and 🛎️ nudge stay **disabled** while the 🔎 dictionary word-check keeps working.
- **Statistics** (`screens/Stats.svelte`, the lobby 📊 tab): a 2-column grid of stat
- cards (wins / losses / draws / games / win-rate / best game / best move) — pure
- numbers, no charts.
+ cards (wins / losses / draws / games / win-rate / best game) — pure numbers, no
+ charts — followed by a **full-width "best move" card** that breaks the best move
+ down per variant: one row per played variant (catalogue order, empty variants
+ omitted) with the variant name on the left, the **word drawn as game tiles**
+ (`components/WordTiles.svelte`, the board's placed-tile look at a small fixed size;
+ a wildcard shows its letter but no value) right-aligned to a shared edge, and the
+ score right-aligned in its own column.
- **Profile editing** (`screens/Profile.svelte`): an inline form — display name, a
**UTC-offset** timezone dropdown (defaulting to the browser's offset), the away
window as hour + 10-minute dropdowns (24-hour, ≤ 12 h), and block toggles — plus an
diff --git a/gateway/internal/backendclient/api_social.go b/gateway/internal/backendclient/api_social.go
index 3d989c4..7747fc2 100644
--- a/gateway/internal/backendclient/api_social.go
+++ b/gateway/internal/backendclient/api_social.go
@@ -47,13 +47,31 @@ type BlockListResp struct {
Blocked []AccountRefResp `json:"blocked"`
}
-// StatsResp is a durable account's lifetime statistics.
+// StatsResp is a durable account's lifetime statistics. BestMoves breaks the best move
+// down per variant, carrying the word itself; it is absent for an account with no recorded
+// play and lists only variants the account has played.
type StatsResp struct {
- Wins int `json:"wins"`
- Losses int `json:"losses"`
- Draws int `json:"draws"`
- MaxGamePoints int `json:"max_game_points"`
- MaxWordPoints int `json:"max_word_points"`
+ Wins int `json:"wins"`
+ Losses int `json:"losses"`
+ Draws int `json:"draws"`
+ MaxGamePoints int `json:"max_game_points"`
+ MaxWordPoints int `json:"max_word_points"`
+ BestMoves []BestMoveResp `json:"best_moves"`
+}
+
+// BestMoveResp is one variant's best play: the variant label, the play's total score and
+// its main word as ordered tiles (letter, value, blank — value 0 for a blank).
+type BestMoveResp struct {
+ Variant string `json:"variant"`
+ Score int `json:"score"`
+ Word []BestMoveTileResp `json:"word"`
+}
+
+// BestMoveTileResp is one letter cell of a best-move word.
+type BestMoveTileResp struct {
+ Letter string `json:"letter"`
+ Value int `json:"value"`
+ Blank bool `json:"blank"`
}
// InvitationInviteeResp is one invitee's seat and response with their name.
diff --git a/gateway/internal/transcode/encode_social.go b/gateway/internal/transcode/encode_social.go
index e9fadcc..1218fe4 100644
--- a/gateway/internal/transcode/encode_social.go
+++ b/gateway/internal/transcode/encode_social.go
@@ -91,15 +91,61 @@ func encodeRedeemResult(r backendclient.RedeemResultResp) []byte {
return b.FinishedBytes()
}
-// encodeStats builds a StatsView payload.
+// buildBestMoveTile builds a BestMoveTile table and returns its offset.
+func buildBestMoveTile(b *flatbuffers.Builder, t backendclient.BestMoveTileResp) flatbuffers.UOffsetT {
+ letter := b.CreateString(t.Letter)
+ fb.BestMoveTileStart(b)
+ fb.BestMoveTileAddLetter(b, letter)
+ fb.BestMoveTileAddValue(b, int32(t.Value))
+ fb.BestMoveTileAddBlank(b, t.Blank)
+ return fb.BestMoveTileEnd(b)
+}
+
+// buildBestMove builds a BestMoveView table — its word tile vector first, per the
+// bottom-up rule — and returns its offset.
+func buildBestMove(b *flatbuffers.Builder, m backendclient.BestMoveResp) flatbuffers.UOffsetT {
+ tiles := make([]flatbuffers.UOffsetT, len(m.Word))
+ for i, t := range m.Word {
+ tiles[i] = buildBestMoveTile(b, t)
+ }
+ fb.BestMoveViewStartWordVector(b, len(tiles))
+ for i := len(tiles) - 1; i >= 0; i-- {
+ b.PrependUOffsetT(tiles[i])
+ }
+ word := b.EndVector(len(tiles))
+ variant := b.CreateString(m.Variant)
+ fb.BestMoveViewStart(b)
+ fb.BestMoveViewAddVariant(b, variant)
+ fb.BestMoveViewAddScore(b, int32(m.Score))
+ fb.BestMoveViewAddWord(b, word)
+ return fb.BestMoveViewEnd(b)
+}
+
+// encodeStats builds a StatsView payload, embedding the per-variant best moves (each a
+// BestMoveView with its word tiles) when present.
func encodeStats(r backendclient.StatsResp) []byte {
- b := flatbuffers.NewBuilder(64)
+ b := flatbuffers.NewBuilder(256)
+ var bestMoves flatbuffers.UOffsetT
+ if len(r.BestMoves) > 0 {
+ offs := make([]flatbuffers.UOffsetT, len(r.BestMoves))
+ for i, m := range r.BestMoves {
+ offs[i] = buildBestMove(b, m)
+ }
+ fb.StatsViewStartBestMovesVector(b, len(offs))
+ for i := len(offs) - 1; i >= 0; i-- {
+ b.PrependUOffsetT(offs[i])
+ }
+ bestMoves = b.EndVector(len(offs))
+ }
fb.StatsViewStart(b)
fb.StatsViewAddWins(b, int32(r.Wins))
fb.StatsViewAddLosses(b, int32(r.Losses))
fb.StatsViewAddDraws(b, int32(r.Draws))
fb.StatsViewAddMaxGamePoints(b, int32(r.MaxGamePoints))
fb.StatsViewAddMaxWordPoints(b, int32(r.MaxWordPoints))
+ if len(r.BestMoves) > 0 {
+ fb.StatsViewAddBestMoves(b, bestMoves)
+ }
b.Finish(fb.StatsViewEnd(b))
return b.FinishedBytes()
}
diff --git a/gateway/internal/transcode/transcode_social_test.go b/gateway/internal/transcode/transcode_social_test.go
index a31e9ba..4f6fcab 100644
--- a/gateway/internal/transcode/transcode_social_test.go
+++ b/gateway/internal/transcode/transcode_social_test.go
@@ -194,7 +194,11 @@ func TestStatsRoundTrip(t *testing.T) {
if r.URL.Path != "/api/v1/user/stats" {
t.Errorf("unexpected path %q", r.URL.Path)
}
- _, _ = w.Write([]byte(`{"wins":5,"losses":3,"draws":1,"max_game_points":420,"max_word_points":90}`))
+ _, _ = w.Write([]byte(`{"wins":5,"losses":3,"draws":1,"max_game_points":420,"max_word_points":90,` +
+ `"best_moves":[{"variant":"scrabble_en","score":90,"word":[` +
+ `{"letter":"c","value":3,"blank":false},` +
+ `{"letter":"a","value":0,"blank":true},` +
+ `{"letter":"t","value":1,"blank":false}]}]}`))
})
defer cleanup()
@@ -208,6 +212,20 @@ func TestStatsRoundTrip(t *testing.T) {
if st.Wins() != 5 || st.Losses() != 3 || st.Draws() != 1 || st.MaxGamePoints() != 420 || st.MaxWordPoints() != 90 {
t.Fatalf("stats decoded wrong: %+v", st)
}
+ if st.BestMovesLength() != 1 {
+ t.Fatalf("best moves length = %d, want 1", st.BestMovesLength())
+ }
+ var bm fb.BestMoveView
+ st.BestMoves(&bm, 0)
+ if string(bm.Variant()) != "scrabble_en" || bm.Score() != 90 || bm.WordLength() != 3 {
+ t.Fatalf("best move decoded wrong: variant=%q score=%d wordLen=%d", bm.Variant(), bm.Score(), bm.WordLength())
+ }
+ // The middle tile is a blank: it carries its designated letter but scores 0.
+ var tile fb.BestMoveTile
+ bm.Word(&tile, 1)
+ if string(tile.Letter()) != "a" || tile.Value() != 0 || !tile.Blank() {
+ t.Fatalf("blank tile decoded wrong: letter=%q value=%d blank=%v", tile.Letter(), tile.Value(), tile.Blank())
+ }
}
func TestGcgRoundTrip(t *testing.T) {
diff --git a/pkg/fbs/scrabble.fbs b/pkg/fbs/scrabble.fbs
index bd9e440..c6b8cdf 100644
--- a/pkg/fbs/scrabble.fbs
+++ b/pkg/fbs/scrabble.fbs
@@ -458,14 +458,35 @@ table LinkResult {
session:Session;
}
+// BestMoveTile is one letter cell of a best-move word: its concrete letter (the designated
+// letter for a blank), its tile point value (0 for a blank) and whether it is a blank. It
+// lets the client render the word as game tiles without the variant's alphabet table.
+table BestMoveTile {
+ letter:string;
+ value:int;
+ blank:bool;
+}
+
+// BestMoveView is an account's highest-scoring single play within one game variant: the
+// variant label, the play's total score (matching max_word_points for that variant) and its
+// main word as ordered tiles.
+table BestMoveView {
+ variant:string;
+ score:int;
+ word:[BestMoveTile];
+}
+
// StatsView is a durable account's lifetime statistics (games-played and win-rate
-// are derived client-side).
+// are derived client-side). best_moves breaks the best move down per variant, carrying the
+// word itself; it is empty for an account with no recorded play and lists only variants the
+// account has played (added trailing — backward-compatible).
table StatsView {
wins:int;
losses:int;
draws:int;
max_game_points:int;
max_word_points:int;
+ best_moves:[BestMoveView];
}
// TargetRequest names a single counterpart account (friend request/cancel/unfriend,
diff --git a/pkg/fbs/scrabblefb/BestMoveTile.go b/pkg/fbs/scrabblefb/BestMoveTile.go
new file mode 100644
index 0000000..8cb943c
--- /dev/null
+++ b/pkg/fbs/scrabblefb/BestMoveTile.go
@@ -0,0 +1,90 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package scrabblefb
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type BestMoveTile struct {
+ _tab flatbuffers.Table
+}
+
+func GetRootAsBestMoveTile(buf []byte, offset flatbuffers.UOffsetT) *BestMoveTile {
+ n := flatbuffers.GetUOffsetT(buf[offset:])
+ x := &BestMoveTile{}
+ x.Init(buf, n+offset)
+ return x
+}
+
+func FinishBestMoveTileBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
+ builder.Finish(offset)
+}
+
+func GetSizePrefixedRootAsBestMoveTile(buf []byte, offset flatbuffers.UOffsetT) *BestMoveTile {
+ n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
+ x := &BestMoveTile{}
+ x.Init(buf, n+offset+flatbuffers.SizeUint32)
+ return x
+}
+
+func FinishSizePrefixedBestMoveTileBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
+ builder.FinishSizePrefixed(offset)
+}
+
+func (rcv *BestMoveTile) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *BestMoveTile) Table() flatbuffers.Table {
+ return rcv._tab
+}
+
+func (rcv *BestMoveTile) Letter() []byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
+ if o != 0 {
+ return rcv._tab.ByteVector(o + rcv._tab.Pos)
+ }
+ return nil
+}
+
+func (rcv *BestMoveTile) Value() int32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
+ if o != 0 {
+ return rcv._tab.GetInt32(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *BestMoveTile) MutateValue(n int32) bool {
+ return rcv._tab.MutateInt32Slot(6, n)
+}
+
+func (rcv *BestMoveTile) Blank() bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
+ if o != 0 {
+ return rcv._tab.GetBool(o + rcv._tab.Pos)
+ }
+ return false
+}
+
+func (rcv *BestMoveTile) MutateBlank(n bool) bool {
+ return rcv._tab.MutateBoolSlot(8, n)
+}
+
+func BestMoveTileStart(builder *flatbuffers.Builder) {
+ builder.StartObject(3)
+}
+func BestMoveTileAddLetter(builder *flatbuffers.Builder, letter flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(letter), 0)
+}
+func BestMoveTileAddValue(builder *flatbuffers.Builder, value int32) {
+ builder.PrependInt32Slot(1, value, 0)
+}
+func BestMoveTileAddBlank(builder *flatbuffers.Builder, blank bool) {
+ builder.PrependBoolSlot(2, blank, false)
+}
+func BestMoveTileEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ return builder.EndObject()
+}
diff --git a/pkg/fbs/scrabblefb/BestMoveView.go b/pkg/fbs/scrabblefb/BestMoveView.go
new file mode 100644
index 0000000..fa7b49c
--- /dev/null
+++ b/pkg/fbs/scrabblefb/BestMoveView.go
@@ -0,0 +1,101 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package scrabblefb
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type BestMoveView struct {
+ _tab flatbuffers.Table
+}
+
+func GetRootAsBestMoveView(buf []byte, offset flatbuffers.UOffsetT) *BestMoveView {
+ n := flatbuffers.GetUOffsetT(buf[offset:])
+ x := &BestMoveView{}
+ x.Init(buf, n+offset)
+ return x
+}
+
+func FinishBestMoveViewBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
+ builder.Finish(offset)
+}
+
+func GetSizePrefixedRootAsBestMoveView(buf []byte, offset flatbuffers.UOffsetT) *BestMoveView {
+ n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
+ x := &BestMoveView{}
+ x.Init(buf, n+offset+flatbuffers.SizeUint32)
+ return x
+}
+
+func FinishSizePrefixedBestMoveViewBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
+ builder.FinishSizePrefixed(offset)
+}
+
+func (rcv *BestMoveView) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *BestMoveView) Table() flatbuffers.Table {
+ return rcv._tab
+}
+
+func (rcv *BestMoveView) Variant() []byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
+ if o != 0 {
+ return rcv._tab.ByteVector(o + rcv._tab.Pos)
+ }
+ return nil
+}
+
+func (rcv *BestMoveView) Score() int32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
+ if o != 0 {
+ return rcv._tab.GetInt32(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *BestMoveView) MutateScore(n int32) bool {
+ return rcv._tab.MutateInt32Slot(6, n)
+}
+
+func (rcv *BestMoveView) Word(obj *BestMoveTile, j int) bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
+ if o != 0 {
+ x := rcv._tab.Vector(o)
+ x += flatbuffers.UOffsetT(j) * 4
+ x = rcv._tab.Indirect(x)
+ obj.Init(rcv._tab.Bytes, x)
+ return true
+ }
+ return false
+}
+
+func (rcv *BestMoveView) WordLength() int {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
+ if o != 0 {
+ return rcv._tab.VectorLen(o)
+ }
+ return 0
+}
+
+func BestMoveViewStart(builder *flatbuffers.Builder) {
+ builder.StartObject(3)
+}
+func BestMoveViewAddVariant(builder *flatbuffers.Builder, variant flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(variant), 0)
+}
+func BestMoveViewAddScore(builder *flatbuffers.Builder, score int32) {
+ builder.PrependInt32Slot(1, score, 0)
+}
+func BestMoveViewAddWord(builder *flatbuffers.Builder, word flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(2, flatbuffers.UOffsetT(word), 0)
+}
+func BestMoveViewStartWordVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
+ return builder.StartVector(4, numElems, 4)
+}
+func BestMoveViewEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ return builder.EndObject()
+}
diff --git a/pkg/fbs/scrabblefb/StatsView.go b/pkg/fbs/scrabblefb/StatsView.go
index 36748a4..67ba771 100644
--- a/pkg/fbs/scrabblefb/StatsView.go
+++ b/pkg/fbs/scrabblefb/StatsView.go
@@ -101,8 +101,28 @@ func (rcv *StatsView) MutateMaxWordPoints(n int32) bool {
return rcv._tab.MutateInt32Slot(12, n)
}
+func (rcv *StatsView) BestMoves(obj *BestMoveView, j int) bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
+ if o != 0 {
+ x := rcv._tab.Vector(o)
+ x += flatbuffers.UOffsetT(j) * 4
+ x = rcv._tab.Indirect(x)
+ obj.Init(rcv._tab.Bytes, x)
+ return true
+ }
+ return false
+}
+
+func (rcv *StatsView) BestMovesLength() int {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
+ if o != 0 {
+ return rcv._tab.VectorLen(o)
+ }
+ return 0
+}
+
func StatsViewStart(builder *flatbuffers.Builder) {
- builder.StartObject(5)
+ builder.StartObject(6)
}
func StatsViewAddWins(builder *flatbuffers.Builder, wins int32) {
builder.PrependInt32Slot(0, wins, 0)
@@ -119,6 +139,12 @@ func StatsViewAddMaxGamePoints(builder *flatbuffers.Builder, maxGamePoints int32
func StatsViewAddMaxWordPoints(builder *flatbuffers.Builder, maxWordPoints int32) {
builder.PrependInt32Slot(4, maxWordPoints, 0)
}
+func StatsViewAddBestMoves(builder *flatbuffers.Builder, bestMoves flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(5, flatbuffers.UOffsetT(bestMoves), 0)
+}
+func StatsViewStartBestMovesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
+ return builder.StartVector(4, numElems, 4)
+}
func StatsViewEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}
diff --git a/ui/e2e/social.spec.ts b/ui/e2e/social.spec.ts
index 64185ea..5509b56 100644
--- a/ui/e2e/social.spec.ts
+++ b/ui/e2e/social.spec.ts
@@ -53,11 +53,15 @@ test('invitations: the lobby shows an invitation and accepting clears it', async
await expect(page.getByText(/From Kaya/)).toBeHidden();
});
-test('stats screen shows the metrics', async ({ page }) => {
+test('stats screen shows the metrics and the per-variant best move', async ({ page }) => {
await loginLobby(page);
await page.getByRole('button', { name: /Stats/ }).click();
await expect(page.getByText('Win rate')).toBeVisible();
await expect(page.getByText('Best move')).toBeVisible();
+ // The best move breaks down per played variant, each row labelled by the variant and
+ // ending in the play's score (the word itself renders as game tiles).
+ await expect(page.getByText('Scrabble', { exact: true })).toBeVisible();
+ await expect(page.getByText('134')).toBeVisible();
});
test('settings hub: tabs switch in place and back returns to the lobby', async ({ page }) => {
diff --git a/ui/src/components/WordTiles.svelte b/ui/src/components/WordTiles.svelte
new file mode 100644
index 0000000..1a70ff4
--- /dev/null
+++ b/ui/src/components/WordTiles.svelte
@@ -0,0 +1,53 @@
+
+
+
+ {#each word as tile, i (i)}
+
+ {tile.letter.toUpperCase()}
+ {#if !tile.blank}{tile.value}{/if}
+
+ {/each}
+
+
+
diff --git a/ui/src/gen/fbs/scrabblefb.ts b/ui/src/gen/fbs/scrabblefb.ts
index 414ac35..25f0ac7 100644
--- a/ui/src/gen/fbs/scrabblefb.ts
+++ b/ui/src/gen/fbs/scrabblefb.ts
@@ -5,6 +5,8 @@ export { Ack } from './scrabblefb/ack.js';
export { AlphabetEntry } from './scrabblefb/alphabet-entry.js';
export { BannerCampaign } from './scrabblefb/banner-campaign.js';
export { BannerInfo } from './scrabblefb/banner-info.js';
+export { BestMoveTile } from './scrabblefb/best-move-tile.js';
+export { BestMoveView } from './scrabblefb/best-move-view.js';
export { BlockList } from './scrabblefb/block-list.js';
export { BlockStatus } from './scrabblefb/block-status.js';
export { ChatList } from './scrabblefb/chat-list.js';
diff --git a/ui/src/gen/fbs/scrabblefb/best-move-tile.ts b/ui/src/gen/fbs/scrabblefb/best-move-tile.ts
new file mode 100644
index 0000000..1e9b8f0
--- /dev/null
+++ b/ui/src/gen/fbs/scrabblefb/best-move-tile.ts
@@ -0,0 +1,68 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+export class BestMoveTile {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+ __init(i:number, bb:flatbuffers.ByteBuffer):BestMoveTile {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsBestMoveTile(bb:flatbuffers.ByteBuffer, obj?:BestMoveTile):BestMoveTile {
+ return (obj || new BestMoveTile()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsBestMoveTile(bb:flatbuffers.ByteBuffer, obj?:BestMoveTile):BestMoveTile {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new BestMoveTile()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+letter():string|null
+letter(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+letter(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+value():number {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+blank():boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
+}
+
+static startBestMoveTile(builder:flatbuffers.Builder) {
+ builder.startObject(3);
+}
+
+static addLetter(builder:flatbuffers.Builder, letterOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, letterOffset, 0);
+}
+
+static addValue(builder:flatbuffers.Builder, value:number) {
+ builder.addFieldInt32(1, value, 0);
+}
+
+static addBlank(builder:flatbuffers.Builder, blank:boolean) {
+ builder.addFieldInt8(2, +blank, +false);
+}
+
+static endBestMoveTile(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createBestMoveTile(builder:flatbuffers.Builder, letterOffset:flatbuffers.Offset, value:number, blank:boolean):flatbuffers.Offset {
+ BestMoveTile.startBestMoveTile(builder);
+ BestMoveTile.addLetter(builder, letterOffset);
+ BestMoveTile.addValue(builder, value);
+ BestMoveTile.addBlank(builder, blank);
+ return BestMoveTile.endBestMoveTile(builder);
+}
+}
diff --git a/ui/src/gen/fbs/scrabblefb/best-move-view.ts b/ui/src/gen/fbs/scrabblefb/best-move-view.ts
new file mode 100644
index 0000000..800a5db
--- /dev/null
+++ b/ui/src/gen/fbs/scrabblefb/best-move-view.ts
@@ -0,0 +1,88 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { BestMoveTile } from '../scrabblefb/best-move-tile.js';
+
+
+export class BestMoveView {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+ __init(i:number, bb:flatbuffers.ByteBuffer):BestMoveView {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsBestMoveView(bb:flatbuffers.ByteBuffer, obj?:BestMoveView):BestMoveView {
+ return (obj || new BestMoveView()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsBestMoveView(bb:flatbuffers.ByteBuffer, obj?:BestMoveView):BestMoveView {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new BestMoveView()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+variant():string|null
+variant(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+variant(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+score():number {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+word(index: number, obj?:BestMoveTile):BestMoveTile|null {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? (obj || new BestMoveTile()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
+}
+
+wordLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+static startBestMoveView(builder:flatbuffers.Builder) {
+ builder.startObject(3);
+}
+
+static addVariant(builder:flatbuffers.Builder, variantOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, variantOffset, 0);
+}
+
+static addScore(builder:flatbuffers.Builder, score:number) {
+ builder.addFieldInt32(1, score, 0);
+}
+
+static addWord(builder:flatbuffers.Builder, wordOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(2, wordOffset, 0);
+}
+
+static createWordVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startWordVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static endBestMoveView(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createBestMoveView(builder:flatbuffers.Builder, variantOffset:flatbuffers.Offset, score:number, wordOffset:flatbuffers.Offset):flatbuffers.Offset {
+ BestMoveView.startBestMoveView(builder);
+ BestMoveView.addVariant(builder, variantOffset);
+ BestMoveView.addScore(builder, score);
+ BestMoveView.addWord(builder, wordOffset);
+ return BestMoveView.endBestMoveView(builder);
+}
+}
diff --git a/ui/src/gen/fbs/scrabblefb/stats-view.ts b/ui/src/gen/fbs/scrabblefb/stats-view.ts
index dc49989..fd87e26 100644
--- a/ui/src/gen/fbs/scrabblefb/stats-view.ts
+++ b/ui/src/gen/fbs/scrabblefb/stats-view.ts
@@ -2,6 +2,9 @@
import * as flatbuffers from 'flatbuffers';
+import { BestMoveView } from '../scrabblefb/best-move-view.js';
+
+
export class StatsView {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
@@ -45,8 +48,18 @@ maxWordPoints():number {
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
}
+bestMoves(index: number, obj?:BestMoveView):BestMoveView|null {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? (obj || new BestMoveView()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
+}
+
+bestMovesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
static startStatsView(builder:flatbuffers.Builder) {
- builder.startObject(5);
+ builder.startObject(6);
}
static addWins(builder:flatbuffers.Builder, wins:number) {
@@ -69,18 +82,35 @@ static addMaxWordPoints(builder:flatbuffers.Builder, maxWordPoints:number) {
builder.addFieldInt32(4, maxWordPoints, 0);
}
+static addBestMoves(builder:flatbuffers.Builder, bestMovesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(5, bestMovesOffset, 0);
+}
+
+static createBestMovesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startBestMovesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
static endStatsView(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
return offset;
}
-static createStatsView(builder:flatbuffers.Builder, wins:number, losses:number, draws:number, maxGamePoints:number, maxWordPoints:number):flatbuffers.Offset {
+static createStatsView(builder:flatbuffers.Builder, wins:number, losses:number, draws:number, maxGamePoints:number, maxWordPoints:number, bestMovesOffset:flatbuffers.Offset):flatbuffers.Offset {
StatsView.startStatsView(builder);
StatsView.addWins(builder, wins);
StatsView.addLosses(builder, losses);
StatsView.addDraws(builder, draws);
StatsView.addMaxGamePoints(builder, maxGamePoints);
StatsView.addMaxWordPoints(builder, maxWordPoints);
+ StatsView.addBestMoves(builder, bestMovesOffset);
return StatsView.endStatsView(builder);
}
}
diff --git a/ui/src/lib/codec.test.ts b/ui/src/lib/codec.test.ts
index e05b7b9..dae78e9 100644
--- a/ui/src/lib/codec.test.ts
+++ b/ui/src/lib/codec.test.ts
@@ -291,6 +291,53 @@ describe('codec', () => {
draws: 1,
maxGamePoints: 420,
maxWordPoints: 90,
+ bestMoves: [],
+ });
+ });
+
+ it('decodes a StatsView carrying a per-variant best move with a blank tile', () => {
+ const b = new Builder(256);
+ // Word "ca" where the 'a' is a blank: it carries its letter but scores 0.
+ const cLetter = b.createString('c');
+ fb.BestMoveTile.startBestMoveTile(b);
+ fb.BestMoveTile.addLetter(b, cLetter);
+ fb.BestMoveTile.addValue(b, 3);
+ fb.BestMoveTile.addBlank(b, false);
+ const tileC = fb.BestMoveTile.endBestMoveTile(b);
+ const aLetter = b.createString('a');
+ fb.BestMoveTile.startBestMoveTile(b);
+ fb.BestMoveTile.addLetter(b, aLetter);
+ fb.BestMoveTile.addValue(b, 0);
+ fb.BestMoveTile.addBlank(b, true);
+ const tileA = fb.BestMoveTile.endBestMoveTile(b);
+ const word = fb.BestMoveView.createWordVector(b, [tileC, tileA]);
+ const variant = b.createString('scrabble_en');
+ fb.BestMoveView.startBestMoveView(b);
+ fb.BestMoveView.addVariant(b, variant);
+ fb.BestMoveView.addScore(b, 90);
+ fb.BestMoveView.addWord(b, word);
+ const bm = fb.BestMoveView.endBestMoveView(b);
+ const bestMoves = fb.StatsView.createBestMovesVector(b, [bm]);
+ fb.StatsView.startStatsView(b);
+ fb.StatsView.addWins(b, 7);
+ fb.StatsView.addBestMoves(b, bestMoves);
+ b.finish(fb.StatsView.endStatsView(b));
+ expect(decodeStats(b.asUint8Array())).toEqual({
+ wins: 7,
+ losses: 0,
+ draws: 0,
+ maxGamePoints: 0,
+ maxWordPoints: 0,
+ bestMoves: [
+ {
+ variant: 'scrabble_en',
+ score: 90,
+ word: [
+ { letter: 'c', value: 3, blank: false },
+ { letter: 'a', value: 0, blank: true },
+ ],
+ },
+ ],
});
});
diff --git a/ui/src/lib/codec.ts b/ui/src/lib/codec.ts
index 3184f92..8a9fd04 100644
--- a/ui/src/lib/codec.ts
+++ b/ui/src/lib/codec.ts
@@ -11,6 +11,8 @@ import type {
AccountRef,
Banner,
BannerCampaign,
+ BestMove,
+ BestMoveTile,
BlockStatus,
ChatMessage,
EvalResult,
@@ -742,12 +744,24 @@ export function decodeRedeemResult(buf: Uint8Array): AccountRef {
export function decodeStats(buf: Uint8Array): Stats {
const v = fb.StatsView.getRootAsStatsView(new ByteBuffer(buf));
+ const bestMoves: BestMove[] = [];
+ for (let i = 0; i < v.bestMovesLength(); i++) {
+ const m = v.bestMoves(i);
+ if (!m) continue;
+ const word: BestMoveTile[] = [];
+ for (let j = 0; j < m.wordLength(); j++) {
+ const t = m.word(j);
+ if (t) word.push({ letter: s(t.letter()), value: t.value(), blank: t.blank() });
+ }
+ bestMoves.push({ variant: s(m.variant()) as Variant, score: m.score(), word });
+ }
return {
wins: v.wins(),
losses: v.losses(),
draws: v.draws(),
maxGamePoints: v.maxGamePoints(),
maxWordPoints: v.maxWordPoints(),
+ bestMoves,
};
}
diff --git a/ui/src/lib/mock/data.ts b/ui/src/lib/mock/data.ts
index 3a3bac4..981543c 100644
--- a/ui/src/lib/mock/data.ts
+++ b/ui/src/lib/mock/data.ts
@@ -50,7 +50,45 @@ export const MOCK_FRIENDS: AccountRef[] = [{ accountId: 'kaya', displayName: 'Ka
export const MOCK_INCOMING: AccountRef[] = [{ accountId: 'rick', displayName: 'Rick' }];
-export const MOCK_STATS: Stats = { wins: 7, losses: 4, draws: 1, maxGamePoints: 421, maxWordPoints: 95 };
+export const MOCK_STATS: Stats = {
+ wins: 7,
+ losses: 4,
+ draws: 1,
+ maxGamePoints: 421,
+ maxWordPoints: 134,
+ // Letters are lower-cased as the backend emits them; the tile renderer upper-cases for
+ // display. The 'd' in "wonderful" is a blank (value 0) to exercise wildcard rendering.
+ // Erudit is absent on purpose, so the screen demonstrates skipping a not-yet-played variant.
+ bestMoves: [
+ {
+ variant: 'scrabble_en',
+ score: 134,
+ word: [
+ { letter: 'w', value: 4, blank: false },
+ { letter: 'o', value: 1, blank: false },
+ { letter: 'n', value: 1, blank: false },
+ { letter: 'd', value: 0, blank: true },
+ { letter: 'e', value: 1, blank: false },
+ { letter: 'r', value: 1, blank: false },
+ { letter: 'f', value: 4, blank: false },
+ { letter: 'u', value: 1, blank: false },
+ { letter: 'l', value: 1, blank: false },
+ ],
+ },
+ {
+ variant: 'scrabble_ru',
+ score: 88,
+ word: [
+ { letter: 'с', value: 1, blank: false },
+ { letter: 'ъ', value: 10, blank: false },
+ { letter: 'ё', value: 4, blank: false },
+ { letter: 'м', value: 2, blank: false },
+ { letter: 'к', value: 2, blank: false },
+ { letter: 'а', value: 1, blank: false },
+ ],
+ },
+ ],
+};
export function mockInvitations(): Invitation[] {
return [
diff --git a/ui/src/lib/model.ts b/ui/src/lib/model.ts
index ff7022a..69793d6 100644
--- a/ui/src/lib/model.ts
+++ b/ui/src/lib/model.ts
@@ -206,13 +206,33 @@ export interface FriendCode {
expiresAtUnix: number;
}
-/** A durable account's lifetime statistics. */
+/** One letter cell of a best-move word: its display letter, its tile value (0 for a
+ * blank) and whether it is a blank — enough to render it as a game tile without the
+ * variant's alphabet table. */
+export interface BestMoveTile {
+ letter: string;
+ value: number;
+ blank: boolean;
+}
+
+/** An account's highest-scoring single play within one variant: the variant, the play's
+ * total score and its main word as ordered tiles. */
+export interface BestMove {
+ variant: Variant;
+ score: number;
+ word: BestMoveTile[];
+}
+
+/** A durable account's lifetime statistics. bestMoves breaks the best move down per
+ * variant (with the word itself); it is empty for an account with no recorded play and
+ * lists only variants the account has played. */
export interface Stats {
wins: number;
losses: number;
draws: number;
maxGamePoints: number;
maxWordPoints: number;
+ bestMoves: BestMove[];
}
/** Settings the inviter chooses for a friend game. */
diff --git a/ui/src/lib/stats.test.ts b/ui/src/lib/stats.test.ts
index ccfdee2..6448d76 100644
--- a/ui/src/lib/stats.test.ts
+++ b/ui/src/lib/stats.test.ts
@@ -8,6 +8,7 @@ const s = (wins: number, losses: number, draws: number): Stats => ({
draws,
maxGamePoints: 0,
maxWordPoints: 0,
+ bestMoves: [],
});
describe('stats', () => {
diff --git a/ui/src/screens/Stats.svelte b/ui/src/screens/Stats.svelte
index 6a5a11d..edefffe 100644
--- a/ui/src/screens/Stats.svelte
+++ b/ui/src/screens/Stats.svelte
@@ -1,11 +1,13 @@
@@ -46,6 +55,18 @@
{/each}
+ {#if bestMoves.length > 0}
+