Backend infers play direction; UI previews words and gates submit on legality
CI / changes (pull_request) Successful in 1s
CI / unit (pull_request) Successful in 9s
CI / integration (pull_request) Successful in 12s
CI / ui (pull_request) Successful in 44s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m9s

A single tile that only extended a word perpendicular to the client-declared
direction was rejected: the UI always sent dir=H for one-tile plays (the
dirOverride/Controls toggle was orphaned in the Stage 7 game rework), so placing
"А" above "БАК" to form "АБАК" failed the solver's main-word-length check even
though the word is in the dictionary.

Make the backend infer a play's orientation from the placed tiles and the board
(internal/engine.resolveDirection): two or more tiles by the line they share, a
lone tile by the axis it abuts (longer word wins, horizontal on a tie). Direction
becomes an output, not an input: drop dir from the SubmitPlay/Eval wire requests
and add it to EvalResult. Journal replay keeps trusting the stored "H"/"V"
(SubmitPlayDir) so a rebuilt game matches the one committed.

UI: stop computing/sending direction; the preview now shows the words a move
forms with its total score (game.previewWords); the make-move control is disabled
until the play is confirmed legal; the "your turn" label hides while tiles are
pending. Delete the orphaned Controls.svelte.

Regenerate the FlatBuffers bindings (Go + TS) and update the gateway transcode
and the loadtest edge client to the new contract. Bake the decision into
ARCHITECTURE.md (§5/§9.1), FUNCTIONAL.md (+ _ru) and the backend README.
This commit is contained in:
Ilia Denisov
2026-06-11 22:42:33 +02:00
parent feee3d6511
commit 92f48a3b12
49 changed files with 419 additions and 401 deletions
+63
View File
@@ -0,0 +1,63 @@
package engine
import (
"gitea.iliadenisov.ru/developer/scrabble-solver/board"
"gitea.iliadenisov.ru/developer/scrabble-solver/scrabble"
)
// resolveDirection infers a play's orientation from the placed tiles and the
// board, so a caller need not declare it (docs/ARCHITECTURE.md §5). Two or more
// tiles fix the orientation by the line they share: a common row reads
// horizontally, otherwise vertically (a non-linear placement is left for
// Evaluate to reject). A single tile is ambiguous on its own — it may extend a
// word down a column or across a row — so the orientation is the axis along
// which it abuts existing tiles, preferring the axis that yields the longer word
// and horizontal on a tie. A tile that abuts nothing falls back to horizontal
// and is rejected downstream as disconnected (or, on the first move, as too
// short).
func resolveDirection(b *board.Board, placements []scrabble.Placement) scrabble.Direction {
if len(placements) >= 2 {
row := placements[0].Row
for _, p := range placements[1:] {
if p.Row != row {
return scrabble.Vertical
}
}
return scrabble.Horizontal
}
if len(placements) == 1 {
p := placements[0]
h := runLength(b, p.Row, p.Col, scrabble.Horizontal)
v := runLength(b, p.Row, p.Col, scrabble.Vertical)
if v >= 2 && v > h {
return scrabble.Vertical
}
if h >= 2 {
return scrabble.Horizontal
}
if v >= 2 {
return scrabble.Vertical
}
}
return scrabble.Horizontal
}
// runLength returns how many cells the word through (row, col) along dir would
// span once a tile is placed on the empty target square: the square itself plus
// the runs of filled cells immediately before and after it along dir. A result
// below two means the tile forms no word on that axis. Filled treats
// off-board coordinates as empty, so the walks stop at the board edge.
func runLength(b *board.Board, row, col int, dir scrabble.Direction) int {
dr, dc := 0, 1
if dir == scrabble.Vertical {
dr, dc = 1, 0
}
n := 1
for r, c := row-dr, col-dc; b.Filled(r, c); r, c = r-dr, c-dc {
n++
}
for r, c := row+dr, col+dc; b.Filled(r, c); r, c = r+dr, c+dc {
n++
}
return n
}
+159
View File
@@ -0,0 +1,159 @@
package engine
import (
"errors"
"testing"
"gitea.iliadenisov.ru/developer/scrabble-solver/board"
"gitea.iliadenisov.ru/developer/scrabble-solver/scrabble"
)
// boardWith returns a 15x15 board with the given (row, col) cells occupied. The
// concrete letter is irrelevant to direction inference, which reads only
// occupancy, so every filler uses alphabet index 0.
func boardWith(cells ...[2]int) *board.Board {
b := board.New(15, 15)
ps := make([]scrabble.Placement, len(cells))
for i, c := range cells {
ps[i] = scrabble.Placement{Row: c[0], Col: c[1], Letter: 0}
}
scrabble.Apply(b, scrabble.Move{Tiles: ps})
return b
}
// TestRunLength covers the word-span measurement that drives single-tile
// direction inference, including the board edge.
func TestRunLength(t *testing.T) {
tests := []struct {
name string
filled [][2]int
row, col int
dir scrabble.Direction
want int
}{
{"isolated horizontal", nil, 7, 7, scrabble.Horizontal, 1},
{"isolated vertical", nil, 7, 7, scrabble.Vertical, 1},
{"neighbour below", [][2]int{{8, 7}}, 7, 7, scrabble.Vertical, 2},
{"neighbour above", [][2]int{{6, 7}}, 7, 7, scrabble.Vertical, 2},
{"run below", [][2]int{{8, 7}, {9, 7}}, 7, 7, scrabble.Vertical, 3},
{"bridge vertical", [][2]int{{6, 7}, {8, 7}}, 7, 7, scrabble.Vertical, 3},
{"neighbour left", [][2]int{{7, 6}}, 7, 7, scrabble.Horizontal, 2},
{"neighbour right", [][2]int{{7, 8}}, 7, 7, scrabble.Horizontal, 2},
{"bridge horizontal", [][2]int{{7, 6}, {7, 8}}, 7, 7, scrabble.Horizontal, 3},
{"perpendicular ignored", [][2]int{{7, 6}}, 7, 7, scrabble.Vertical, 1},
{"top edge", [][2]int{{1, 0}}, 0, 0, scrabble.Vertical, 2},
{"left edge", [][2]int{{0, 1}}, 0, 0, scrabble.Horizontal, 2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
b := boardWith(tt.filled...)
if got := runLength(b, tt.row, tt.col, tt.dir); got != tt.want {
t.Errorf("runLength(%d,%d,%v) = %d, want %d", tt.row, tt.col, tt.dir, got, tt.want)
}
})
}
}
// TestResolveDirection covers orientation inference for both multi-tile plays
// (fixed by the shared line) and the ambiguous single tile (the axis it abuts,
// longer word winning and horizontal on a tie; disconnected falls back to
// horizontal for the downstream rejection).
func TestResolveDirection(t *testing.T) {
at := func(cells ...[2]int) []scrabble.Placement {
ps := make([]scrabble.Placement, len(cells))
for i, c := range cells {
ps[i] = scrabble.Placement{Row: c[0], Col: c[1]}
}
return ps
}
tests := []struct {
name string
filled [][2]int
play []scrabble.Placement
want scrabble.Direction
}{
{"single extends down", [][2]int{{8, 7}, {9, 7}}, at([2]int{7, 7}), scrabble.Vertical},
{"single extends up", [][2]int{{6, 7}, {5, 7}}, at([2]int{7, 7}), scrabble.Vertical},
{"single extends left", [][2]int{{7, 6}}, at([2]int{7, 7}), scrabble.Horizontal},
{"single extends right", [][2]int{{7, 8}}, at([2]int{7, 7}), scrabble.Horizontal},
{"single both axes vertical longer", [][2]int{{6, 7}, {8, 7}, {7, 6}}, at([2]int{7, 7}), scrabble.Vertical},
{"single both axes horizontal longer", [][2]int{{7, 6}, {7, 8}, {6, 7}}, at([2]int{7, 7}), scrabble.Horizontal},
{"single both axes equal prefers horizontal", [][2]int{{6, 7}, {7, 6}}, at([2]int{7, 7}), scrabble.Horizontal},
{"single disconnected falls back to horizontal", nil, at([2]int{7, 7}), scrabble.Horizontal},
{"multi shared row is horizontal", nil, at([2]int{7, 7}, [2]int{7, 8}), scrabble.Horizontal},
{"multi shared column is vertical", nil, at([2]int{7, 7}, [2]int{8, 7}), scrabble.Vertical},
{"multi non-linear is vertical", nil, at([2]int{7, 7}, [2]int{8, 8}), scrabble.Vertical},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
b := boardWith(tt.filled...)
if got := resolveDirection(b, tt.play); got != tt.want {
t.Errorf("resolveDirection = %v, want %v", got, tt.want)
}
})
}
}
// TestResolveDirectionEmpty checks the degenerate empty placement does not panic
// and falls back to horizontal (Evaluate rejects the empty play downstream).
func TestResolveDirectionEmpty(t *testing.T) {
if got := resolveDirection(boardWith(), nil); got != scrabble.Horizontal {
t.Errorf("resolveDirection(empty) = %v, want Horizontal", got)
}
}
// TestSubmitPlaySingleTileVerticalExtension is the regression for the reported
// bug: a single tile placed above an existing vertical word forms a legal play
// the engine must accept by inferring the vertical orientation. Trusting a
// horizontal orientation (the pre-fix client default) wrongly rejects it.
func TestSubmitPlaySingleTileVerticalExtension(t *testing.T) {
// БАК runs down column 7 (rows 7..9); the mover holds А and plays it at
// (6,7), prefixing АБАК. This mirrors the contour game that surfaced the bug.
setup := func(t *testing.T) (*Game, []TileRecord) {
t.Helper()
g, err := New(testReg, Options{Variant: VariantErudit, Version: testVersion, Players: 2, Seed: 1})
if err != nil {
t.Fatalf("new erudit game: %v", err)
}
idx := func(s string) byte {
i, err := g.rules.Alphabet.Index(s)
if err != nil {
t.Fatalf("index %q: %v", s, err)
}
return i
}
scrabble.Apply(g.board, scrabble.Move{Tiles: []scrabble.Placement{
{Row: 7, Col: 7, Letter: idx("б")},
{Row: 8, Col: 7, Letter: idx("а")},
{Row: 9, Col: 7, Letter: idx("к")},
}})
g.hands[0] = []byte{idx("а")}
return g, []TileRecord{{Row: 6, Col: 7, Letter: "а"}}
}
t.Run("inferred direction accepts the play", func(t *testing.T) {
g, tiles := setup(t)
rec, err := g.SubmitPlay(tiles)
if err != nil {
t.Fatalf("submit play: %v", err)
}
if rec.Dir != Vertical {
t.Errorf("direction = %v, want Vertical", rec.Dir)
}
if len(rec.Words) == 0 || rec.Words[0] != "абак" {
t.Errorf("words = %v, want main word абак", rec.Words)
}
if rec.Score <= 0 {
t.Errorf("score = %d, want positive", rec.Score)
}
})
t.Run("trusting horizontal rejects it", func(t *testing.T) {
g, tiles := setup(t)
if _, err := g.SubmitPlayDir(Horizontal, tiles); !errors.Is(err, ErrIllegalPlay) {
t.Errorf("submit horizontal = %v, want ErrIllegalPlay", err)
}
})
}
+22 -7
View File
@@ -52,11 +52,25 @@ func fromScrabbleDir(d scrabble.Direction) Direction {
// SubmitPlay validates and applies the current player's play described in decoded
// terms: each TileRecord carries a concrete letter (the letter a blank stands for
// when Blank is set) and a board coordinate. It encodes the tiles through the
// when Blank is set) and a board coordinate. It infers the play's orientation
// from the tiles and the board (resolveDirection), encodes the tiles through the
// ruleset alphabet and delegates to Play, so it returns the same errors
// (ErrTilesNotOnRack, ErrIllegalPlay, ErrGameOver) plus ErrIllegalPlay when a
// letter is outside the variant's alphabet.
func (g *Game) SubmitPlay(dir Direction, tiles []TileRecord) (MoveRecord, error) {
func (g *Game) SubmitPlay(tiles []TileRecord) (MoveRecord, error) {
placements, err := g.placements(tiles)
if err != nil {
return MoveRecord{}, err
}
return g.Play(resolveDirection(g.board, placements), placements)
}
// SubmitPlayDir is SubmitPlay with the orientation supplied rather than inferred.
// It exists for journal replay, which reproduces a committed game exactly from
// the stored "H"/"V" rather than re-deriving it (docs/ARCHITECTURE.md §9.1):
// re-derivation would tie historical reconstruction to the current resolver, so
// replay trusts the recorded direction. Live play uses SubmitPlay.
func (g *Game) SubmitPlayDir(dir Direction, tiles []TileRecord) (MoveRecord, error) {
placements, err := g.placements(tiles)
if err != nil {
return MoveRecord{}, err
@@ -78,10 +92,11 @@ func (g *Game) SubmitExchange(tiles []string) (MoveRecord, error) {
// EvaluatePlay scores and validates a tentative play without committing it,
// backing the unlimited "what would my next move score, and is it legal?" tool.
// It returns the decoded move (placed tiles, the words it forms and its score)
// or ErrIllegalPlay when the solver rejects it. The board, racks, bag and turn
// are left untouched.
func (g *Game) EvaluatePlay(dir Direction, tiles []TileRecord) (MoveRecord, error) {
// It infers the play's orientation from the tiles and the board exactly as
// SubmitPlay does, then returns the decoded move (placed tiles, the words it
// forms, its orientation and its score) or ErrIllegalPlay when the solver
// rejects it. The board, racks, bag and turn are left untouched.
func (g *Game) EvaluatePlay(tiles []TileRecord) (MoveRecord, error) {
if g.over {
return MoveRecord{}, ErrGameOver
}
@@ -89,7 +104,7 @@ func (g *Game) EvaluatePlay(dir Direction, tiles []TileRecord) (MoveRecord, erro
if err != nil {
return MoveRecord{}, err
}
move, err := g.solver.ValidatePlay(g.board, dir.scrabbleDir(), placements)
move, err := g.solver.ValidatePlay(g.board, resolveDirection(g.board, placements), placements)
if err != nil {
return MoveRecord{}, fmt.Errorf("%w: %v", ErrIllegalPlay, err)
}
+3 -3
View File
@@ -25,7 +25,7 @@ func TestSubmitPlayMatchesHint(t *testing.T) {
if !ok {
t.Fatal("opening game has no hint")
}
rec, err := g.SubmitPlay(hint.Dir, hint.Tiles)
rec, err := g.SubmitPlay(hint.Tiles)
if err != nil {
t.Fatalf("submit play: %v", err)
}
@@ -85,7 +85,7 @@ func TestEvaluatePlayDoesNotCommit(t *testing.T) {
boardBefore := g.BoardClone()
scoreBefore, toMoveBefore, bagBefore := g.Score(0), g.ToMove(), g.BagLen()
rec, err := g.EvaluatePlay(hint.Dir, hint.Tiles)
rec, err := g.EvaluatePlay(hint.Tiles)
if err != nil {
t.Fatalf("evaluate play: %v", err)
}
@@ -106,7 +106,7 @@ func TestEvaluatePlayDoesNotCommit(t *testing.T) {
func TestEvaluatePlayRejectsIllegal(t *testing.T) {
g := newEnglishGame(t, 1)
letter := g.Hand(0)[0]
_, err := g.EvaluatePlay(Horizontal, []TileRecord{{Row: 0, Col: 0, Letter: letter}})
_, err := g.EvaluatePlay([]TileRecord{{Row: 0, Col: 0, Letter: letter}})
if !errors.Is(err, ErrIllegalPlay) {
t.Errorf("evaluate off-centre opening = %v, want ErrIllegalPlay", err)
}
+5 -5
View File
@@ -12,7 +12,7 @@ func TestResignLeadingPlayerStillLoses(t *testing.T) {
if !ok {
t.Fatal("opening game has no hint")
}
played, err := g.SubmitPlay(hint.Dir, hint.Tiles)
played, err := g.SubmitPlay(hint.Tiles)
if err != nil {
t.Fatalf("player 0 play: %v", err)
}
@@ -56,7 +56,7 @@ func TestResignTrailingPlayerLoses(t *testing.T) {
if !ok {
t.Fatal("opening game has no hint")
}
if _, err := g.SubmitPlay(hint.Dir, hint.Tiles); err != nil { // player 0 scores
if _, err := g.SubmitPlay(hint.Tiles); err != nil { // player 0 scores
t.Fatalf("player 0 play: %v", err)
}
@@ -79,7 +79,7 @@ func TestResignSeatOffTurn(t *testing.T) {
if !ok {
t.Fatal("opening game has no hint")
}
if _, err := g.SubmitPlay(hint.Dir, hint.Tiles); err != nil { // player 0 moves
if _, err := g.SubmitPlay(hint.Tiles); err != nil { // player 0 moves
t.Fatalf("player 0 play: %v", err)
}
if g.ToMove() != 1 {
@@ -165,7 +165,7 @@ func TestMultiplayerLastActiveWins(t *testing.T) {
if !ok {
t.Fatal("opening game has no hint")
}
played, err := g.SubmitPlay(hint.Dir, hint.Tiles) // seat 0 takes the lead
played, err := g.SubmitPlay(hint.Tiles) // seat 0 takes the lead
if err != nil {
t.Fatalf("seat 0 play: %v", err)
}
@@ -245,7 +245,7 @@ func TestResignedSeatExcludedFromWinOnScorelessEnd(t *testing.T) {
if !ok {
t.Fatal("opening game has no hint")
}
played, err := g.SubmitPlay(hint.Dir, hint.Tiles) // seat 0 leads
played, err := g.SubmitPlay(hint.Tiles) // seat 0 leads
if err != nil {
t.Fatalf("seat 0 play: %v", err)
}