feat: "multiple words per turn" rule for Russian games
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 9s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 45s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m10s

Add a per-game rule chosen on New Game for Russian variants (default off = the
single-word rule; on = standard Scrabble). Off, only the main word along the play
direction is validated and scored; perpendicular cross-words are ignored,
including in robot move generation. The rule rides every create and enqueue
request and joins the matchmaking key, so games and auto-match stay one uniform
path; "Russian-only" is a UI affordance (English always sends standard and shows
no toggle).

- Engine: consume scrabble-solver v1.1.0's PlayOptions{IgnoreCrossWords}, threaded
  through engine.Options.MultipleWordsPerTurn -> playOpts() into validate, score
  and generate.
- Backend: thread the flag through game CreateParams/Game + store (games column),
  lobby InvitationSettings + invitation row, and the matchmaker queue key (variant
  + rule); persisted, so a rebuilt-from-journal game keeps it. Baseline migration
  gains multiple_words_per_turn (DB not versioned); jet regenerated.
- Edge: multiple_words_per_turn added to the EnqueueRequest / CreateInvitationRequest
  FlatBuffers tables (Go + TS regenerated) and threaded through the gateway.
- UI: a "Multiple words per turn" toggle on New Game, shown for Russian variants
  only (auto-match and friend invite), default off; English silently sends standard.
- Tests: backend engine/matchmaker; UI unit (gating) + Playwright e2e (solver
  corner-case + GCG fixtures ship in v1.1.0). Docs + PRERELEASE tracker updated.
This commit is contained in:
Ilia Denisov
2026-06-12 02:17:30 +02:00
parent d4a1616d03
commit 74455c7b12
46 changed files with 643 additions and 296 deletions
+28 -21
View File
@@ -49,6 +49,8 @@ type InvitationSettings struct {
HintsAllowed bool
HintsPerPlayer int
DropoutTiles engine.DropoutTiles
// MultipleWordsPerTurn true selects standard Scrabble; false the single-word rule.
MultipleWordsPerTurn bool
}
// Invitee is one invited player's seat and response.
@@ -214,14 +216,15 @@ func (svc *InvitationService) CreateInvitation(ctx context.Context, inviterID uu
return Invitation{}, fmt.Errorf("lobby: new invitation id: %w", err)
}
ins := invitationInsert{
id: id,
inviterID: inviterID,
variant: settings.Variant.String(),
turnTimeoutSecs: int(settings.TurnTimeout / time.Second),
hintsAllowed: settings.HintsAllowed,
hintsPerPlayer: settings.HintsPerPlayer,
dropoutTiles: settings.DropoutTiles.String(),
expiresAt: svc.now().Add(invitationTTL),
id: id,
inviterID: inviterID,
variant: settings.Variant.String(),
turnTimeoutSecs: int(settings.TurnTimeout / time.Second),
hintsAllowed: settings.HintsAllowed,
hintsPerPlayer: settings.HintsPerPlayer,
dropoutTiles: settings.DropoutTiles.String(),
multipleWordsPerTurn: settings.MultipleWordsPerTurn,
expiresAt: svc.now().Add(invitationTTL),
}
if err := svc.store.insertInvitation(ctx, ins, inviteeIDs); err != nil {
return Invitation{}, err
@@ -265,12 +268,13 @@ func (svc *InvitationService) startGame(ctx context.Context, invitationID uuid.U
seats[iv.Seat] = iv.AccountID
}
g, err := svc.games.Create(ctx, game.CreateParams{
Variant: inv.Settings.Variant,
Seats: seats,
TurnTimeout: inv.Settings.TurnTimeout,
HintsAllowed: inv.Settings.HintsAllowed,
HintsPerPlayer: inv.Settings.HintsPerPlayer,
DropoutTiles: inv.Settings.DropoutTiles,
Variant: inv.Settings.Variant,
Seats: seats,
TurnTimeout: inv.Settings.TurnTimeout,
HintsAllowed: inv.Settings.HintsAllowed,
HintsPerPlayer: inv.Settings.HintsPerPlayer,
DropoutTiles: inv.Settings.DropoutTiles,
MultipleWordsPerTurn: inv.Settings.MultipleWordsPerTurn,
})
if err != nil {
return err
@@ -322,6 +326,8 @@ type invitationInsert struct {
hintsPerPlayer int
dropoutTiles string
expiresAt time.Time
// multipleWordsPerTurn false selects the single-word rule.
multipleWordsPerTurn bool
}
// respondResult reports the state after an invitee response.
@@ -335,8 +341,8 @@ func (s *Store) insertInvitation(ctx context.Context, ins invitationInsert, invi
ii := table.GameInvitations.INSERT(
table.GameInvitations.InvitationID, table.GameInvitations.InviterID, table.GameInvitations.Variant,
table.GameInvitations.TurnTimeoutSecs, table.GameInvitations.HintsAllowed, table.GameInvitations.HintsPerPlayer,
table.GameInvitations.DropoutTiles, table.GameInvitations.ExpiresAt,
).VALUES(ins.id, ins.inviterID, ins.variant, ins.turnTimeoutSecs, ins.hintsAllowed, ins.hintsPerPlayer, ins.dropoutTiles, ins.expiresAt)
table.GameInvitations.DropoutTiles, table.GameInvitations.MultipleWordsPerTurn, table.GameInvitations.ExpiresAt,
).VALUES(ins.id, ins.inviterID, ins.variant, ins.turnTimeoutSecs, ins.hintsAllowed, ins.hintsPerPlayer, ins.dropoutTiles, ins.multipleWordsPerTurn, ins.expiresAt)
if _, err := ii.ExecContext(ctx, tx); err != nil {
return fmt.Errorf("insert invitation: %w", err)
}
@@ -377,11 +383,12 @@ func (s *Store) loadInvitation(ctx context.Context, id uuid.UUID) (Invitation, e
ID: row.InvitationID,
InviterID: row.InviterID,
Settings: InvitationSettings{
Variant: variant,
TurnTimeout: time.Duration(row.TurnTimeoutSecs) * time.Second,
HintsAllowed: row.HintsAllowed,
HintsPerPlayer: int(row.HintsPerPlayer),
DropoutTiles: dropout,
Variant: variant,
TurnTimeout: time.Duration(row.TurnTimeoutSecs) * time.Second,
HintsAllowed: row.HintsAllowed,
HintsPerPlayer: int(row.HintsPerPlayer),
DropoutTiles: dropout,
MultipleWordsPerTurn: row.MultipleWordsPerTurn,
},
Status: row.Status,
GameID: row.GameID,
+49 -36
View File
@@ -14,6 +14,14 @@ import (
"scrabble/backend/internal/notify"
)
// matchKey buckets the auto-match pool: two players are paired only when they chose
// the same variant and the same per-turn word rule (multipleWords), so a game always
// starts under a rule both players asked for.
type matchKey struct {
variant engine.Variant
multipleWords bool
}
// Matchmaker is the in-memory auto-match pool: a FIFO queue per variant that pairs
// the next two humans into a two-player game, or — when no human arrives within
// the wait window — substitutes a robot. It holds no database state and is lost on
@@ -35,8 +43,8 @@ type Matchmaker struct {
log *zap.Logger
mu sync.Mutex
queues map[engine.Variant][]uuid.UUID
queued map[uuid.UUID]engine.Variant
queues map[matchKey][]uuid.UUID
queued map[uuid.UUID]matchKey
waitingSince map[uuid.UUID]time.Time
results map[uuid.UUID]game.Game
rng *rand.Rand
@@ -55,8 +63,8 @@ func NewMatchmaker(games GameCreator, robots RobotProvider, waitDelay time.Durat
clock: func() time.Time { return time.Now().UTC() },
pub: notify.Nop{},
log: log,
queues: make(map[engine.Variant][]uuid.UUID),
queued: make(map[uuid.UUID]engine.Variant),
queues: make(map[matchKey][]uuid.UUID),
queued: make(map[uuid.UUID]matchKey),
waitingSince: make(map[uuid.UUID]time.Time),
results: make(map[uuid.UUID]game.Game),
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
@@ -101,34 +109,36 @@ type EnqueueResult struct {
Game game.Game
}
// Enqueue joins accountID to the variant pool. If an opponent already waits, the
// two are paired (seat order randomised for first-move fairness) and a game starts
// immediately; otherwise the account waits, and a later pairing or robot
// substitution is delivered through Poll. An account already waiting in any pool
// gets ErrAlreadyQueued.
func (m *Matchmaker) Enqueue(ctx context.Context, accountID uuid.UUID, variant engine.Variant) (EnqueueResult, error) {
// Enqueue joins accountID to the auto-match pool for variant under the chosen
// per-turn word rule (multipleWords). If an opponent already waits for the same
// variant and rule, the two are paired (seat order randomised for first-move
// fairness) and a game starts immediately; otherwise the account waits, and a later
// pairing or robot substitution is delivered through Poll. An account already waiting
// in any pool gets ErrAlreadyQueued.
func (m *Matchmaker) Enqueue(ctx context.Context, accountID uuid.UUID, variant engine.Variant, multipleWords bool) (EnqueueResult, error) {
key := matchKey{variant: variant, multipleWords: multipleWords}
m.mu.Lock()
if _, ok := m.queued[accountID]; ok {
m.mu.Unlock()
return EnqueueResult{}, ErrAlreadyQueued
}
q := m.queues[variant]
q := m.queues[key]
if len(q) == 0 {
m.queues[variant] = append(q, accountID)
m.queued[accountID] = variant
m.queues[key] = append(q, accountID)
m.queued[accountID] = key
m.waitingSince[accountID] = m.clock()
m.mu.Unlock()
return EnqueueResult{}, nil
}
opponent := q[0]
m.removeLocked(opponent, variant)
m.removeLocked(opponent, key)
seats := []uuid.UUID{opponent, accountID}
if m.rng.Intn(2) == 0 {
seats[0], seats[1] = seats[1], seats[0]
}
m.mu.Unlock()
g, err := m.games.Create(ctx, autoMatchParams(variant, seats))
g, err := m.games.Create(ctx, autoMatchParams(key, seats))
if err != nil {
return EnqueueResult{}, err
}
@@ -161,19 +171,21 @@ func (m *Matchmaker) Cancel(_ context.Context, accountID uuid.UUID) bool {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.results, accountID)
variant, ok := m.queued[accountID]
key, ok := m.queued[accountID]
if !ok {
return false
}
m.removeLocked(accountID, variant)
m.removeLocked(accountID, key)
return true
}
// QueueLen returns the number of accounts waiting in the variant pool.
// QueueLen returns the number of accounts waiting in the variant pool, summed across
// both per-turn word rules.
func (m *Matchmaker) QueueLen(variant engine.Variant) int {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.queues[variant])
return len(m.queues[matchKey{variant: variant, multipleWords: false}]) +
len(m.queues[matchKey{variant: variant, multipleWords: true}])
}
// RunReaper substitutes a robot for any player that has waited past waitDelay,
@@ -198,9 +210,9 @@ func (m *Matchmaker) RunReaper(ctx context.Context, interval time.Duration) {
// momentarily empty pool just defers substitution to a later tick.
func (m *Matchmaker) Reap(ctx context.Context, now time.Time) {
type sub struct {
human uuid.UUID
variant engine.Variant
seats []uuid.UUID
human uuid.UUID
key matchKey
seats []uuid.UUID
}
m.mu.Lock()
var due []uuid.UUID
@@ -211,23 +223,23 @@ func (m *Matchmaker) Reap(ctx context.Context, now time.Time) {
}
var subs []sub
for _, acc := range due {
variant := m.queued[acc]
robotID, err := m.robots.Pick(variant)
key := m.queued[acc]
robotID, err := m.robots.Pick(key.variant)
if err != nil {
m.log.Warn("robot substitution deferred", zap.Error(err))
continue
}
m.removeLocked(acc, variant)
m.removeLocked(acc, key)
seats := []uuid.UUID{acc, robotID}
if m.rng.Intn(2) == 0 {
seats[0], seats[1] = seats[1], seats[0]
}
subs = append(subs, sub{human: acc, variant: variant, seats: seats})
subs = append(subs, sub{human: acc, key: key, seats: seats})
}
m.mu.Unlock()
for _, s := range subs {
g, err := m.games.Create(ctx, autoMatchParams(s.variant, s.seats))
g, err := m.games.Create(ctx, autoMatchParams(s.key, s.seats))
if err != nil {
m.log.Warn("robot substitution failed", zap.String("human", s.human.String()), zap.Error(err))
continue
@@ -241,13 +253,13 @@ func (m *Matchmaker) Reap(ctx context.Context, now time.Time) {
// removeLocked drops accountID from the queue, the queued index and the waiting
// clock. The caller holds m.mu.
func (m *Matchmaker) removeLocked(accountID uuid.UUID, variant engine.Variant) {
func (m *Matchmaker) removeLocked(accountID uuid.UUID, key matchKey) {
delete(m.queued, accountID)
delete(m.waitingSince, accountID)
q := m.queues[variant]
q := m.queues[key]
for i, id := range q {
if id == accountID {
m.queues[variant] = append(q[:i], q[i+1:]...)
m.queues[key] = append(q[:i], q[i+1:]...)
break
}
}
@@ -255,12 +267,13 @@ func (m *Matchmaker) removeLocked(accountID uuid.UUID, variant engine.Variant) {
// autoMatchParams builds the create parameters for a two-player auto-match with
// the casual defaults.
func autoMatchParams(variant engine.Variant, seats []uuid.UUID) game.CreateParams {
func autoMatchParams(key matchKey, seats []uuid.UUID) game.CreateParams {
return game.CreateParams{
Variant: variant,
Seats: seats,
TurnTimeout: game.DefaultTurnTimeout,
HintsAllowed: autoMatchHintsAllowed,
HintsPerPlayer: autoMatchHintsPerPlayer,
Variant: key.variant,
Seats: seats,
TurnTimeout: game.DefaultTurnTimeout,
HintsAllowed: autoMatchHintsAllowed,
HintsPerPlayer: autoMatchHintsPerPlayer,
MultipleWordsPerTurn: key.multipleWords,
}
}
+66 -12
View File
@@ -80,7 +80,7 @@ func TestMatchmakerPairsTwoHumans(t *testing.T) {
ctx := context.Background()
a, b := uuid.New(), uuid.New()
r1, err := mm.Enqueue(ctx, a, engine.VariantEnglish)
r1, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true)
if err != nil {
t.Fatalf("enqueue a: %v", err)
}
@@ -91,7 +91,7 @@ func TestMatchmakerPairsTwoHumans(t *testing.T) {
t.Fatalf("queue len = %d, want 1", mm.QueueLen(engine.VariantEnglish))
}
r2, err := mm.Enqueue(ctx, b, engine.VariantEnglish)
r2, err := mm.Enqueue(ctx, b, engine.VariantEnglish, true)
if err != nil {
t.Fatalf("enqueue b: %v", err)
}
@@ -129,10 +129,10 @@ func TestMatchmakerAlreadyQueued(t *testing.T) {
mm := newTestMatchmaker(&fakeCreator{}, uuid.New())
ctx := context.Background()
a := uuid.New()
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue: %v", err)
}
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); !errors.Is(err, ErrAlreadyQueued) {
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true); !errors.Is(err, ErrAlreadyQueued) {
t.Fatalf("second enqueue err = %v, want ErrAlreadyQueued", err)
}
}
@@ -141,7 +141,7 @@ func TestMatchmakerCancel(t *testing.T) {
mm := newTestMatchmaker(&fakeCreator{}, uuid.New())
ctx := context.Background()
a := uuid.New()
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue: %v", err)
}
if !mm.Cancel(ctx, a) {
@@ -159,10 +159,10 @@ func TestMatchmakerVariantsAreSeparate(t *testing.T) {
creator := &fakeCreator{}
mm := newTestMatchmaker(creator, uuid.New())
ctx := context.Background()
if _, err := mm.Enqueue(ctx, uuid.New(), engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, uuid.New(), engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue en: %v", err)
}
if _, err := mm.Enqueue(ctx, uuid.New(), engine.VariantRussianScrabble); err != nil {
if _, err := mm.Enqueue(ctx, uuid.New(), engine.VariantRussianScrabble, true); err != nil {
t.Fatalf("enqueue ru: %v", err)
}
if len(creator.created) != 0 {
@@ -179,7 +179,7 @@ func TestMatchmakerFIFO(t *testing.T) {
ctx := context.Background()
a, b, c := uuid.New(), uuid.New(), uuid.New()
for _, id := range []uuid.UUID{a, b, c} {
if _, err := mm.Enqueue(ctx, id, engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, id, engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue %s: %v", id, err)
}
}
@@ -204,7 +204,7 @@ func TestMatchmakerReaperSubstitutesRobot(t *testing.T) {
ctx := context.Background()
a := uuid.New()
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue: %v", err)
}
@@ -237,7 +237,7 @@ func TestMatchmakerReaperSkipsCancelled(t *testing.T) {
ctx := context.Background()
a := uuid.New()
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue: %v", err)
}
mm.Cancel(ctx, a)
@@ -258,7 +258,7 @@ func TestMatchmakerCancelClearsPendingResult(t *testing.T) {
ctx := context.Background()
a := uuid.New()
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue: %v", err)
}
mm.Reap(ctx, base.Add(testWaitDelay+time.Second)) // substitution stores a pending result
@@ -276,7 +276,7 @@ func TestMatchmakerReaperDefersWithoutRobot(t *testing.T) {
ctx := context.Background()
a := uuid.New()
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil {
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true); err != nil {
t.Fatalf("enqueue: %v", err)
}
mm.Reap(ctx, base.Add(testWaitDelay+time.Second))
@@ -287,3 +287,57 @@ func TestMatchmakerReaperDefersWithoutRobot(t *testing.T) {
t.Errorf("waiter must stay queued when substitution is deferred; len %d", mm.QueueLen(engine.VariantEnglish))
}
}
// TestMatchmakerRulesAreSeparate confirms two players who chose the same variant but a
// different per-turn word rule are not paired, and that the rule reaches the started game.
func TestMatchmakerRulesAreSeparate(t *testing.T) {
creator := &fakeCreator{}
mm := newTestMatchmaker(creator, uuid.New())
ctx := context.Background()
// Same variant, opposite rules: they must not match.
if _, err := mm.Enqueue(ctx, uuid.New(), engine.VariantRussianScrabble, false); err != nil {
t.Fatalf("enqueue single-word: %v", err)
}
if _, err := mm.Enqueue(ctx, uuid.New(), engine.VariantRussianScrabble, true); err != nil {
t.Fatalf("enqueue standard: %v", err)
}
if len(creator.created) != 0 {
t.Fatalf("different rules must not match; created %d", len(creator.created))
}
// A second single-word player pairs with the first; the game carries the rule.
r, err := mm.Enqueue(ctx, uuid.New(), engine.VariantRussianScrabble, false)
if err != nil {
t.Fatalf("enqueue single-word opponent: %v", err)
}
if !r.Matched {
t.Fatal("same variant and rule must match")
}
if len(creator.created) != 1 {
t.Fatalf("created %d games, want 1", len(creator.created))
}
if creator.created[0].MultipleWordsPerTurn {
t.Error("single-word match must create a game with MultipleWordsPerTurn=false")
}
}
// TestMatchmakerReaperKeepsRule confirms a robot substitution carries the waiter's rule.
func TestMatchmakerReaperKeepsRule(t *testing.T) {
creator := &fakeCreator{}
mm := newTestMatchmaker(creator, uuid.New())
base := time.Now()
mm.clock = func() time.Time { return base }
ctx := context.Background()
if _, err := mm.Enqueue(ctx, uuid.New(), engine.VariantRussianScrabble, false); err != nil {
t.Fatalf("enqueue: %v", err)
}
mm.Reap(ctx, base.Add(testWaitDelay+time.Second))
if len(creator.created) != 1 {
t.Fatalf("created %d games, want 1", len(creator.created))
}
if creator.created[0].MultipleWordsPerTurn {
t.Error("robot substitution must keep the waiter's single-word rule")
}
}