diff --git a/pkg/engine_game.go b/pkg/engine_game.go index ba1be61..51492e4 100644 --- a/pkg/engine_game.go +++ b/pkg/engine_game.go @@ -3,6 +3,7 @@ package pkg import ( "context" "fmt" + "math/rand/v2" "time" "github.com/nate-xyz/chess-cli/api" @@ -102,7 +103,8 @@ func startEngineGame(path string, level int, player chess.Color) { }() } -// engineMove asks Stockfish for its move and plays it. +// engineMove asks Stockfish for its move and plays it once it has taken a +// person's time over it (see engine_think.go), its clock running meanwhile. func (g *GameScreen) engineMove() { e, gen := g.engine, g.engineGen game := Root.gameState.Game @@ -111,11 +113,21 @@ func (g *GameScreen) engineMove() { for i, m := range game.Moves() { moves = append(moves, chess.UCINotation{}.Encode(game.Positions()[i], m)) } + w, b := g.remaining() + left := w + if g.engineColor == chess.Black { + left = b + } + think := engineThinkTime(game, left, g.clock.increment, g.clock.on, rand.New(rand.NewPCG(rand.Uint64(), rand.Uint64()))) + asked := time.Now() g.UpdateStatus() go func() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() uci, err := e.BestMove(ctx, start, moves) + if err == nil { + time.Sleep(think - time.Since(asked)) // (no wait if it took longer) + } Root.App.QueueUpdateDraw(func() { if gen != g.engineGen || g.engine != e { return // the game was left or restarted meanwhile diff --git a/pkg/engine_test.go b/pkg/engine_test.go index 1cf05b1..a06a8c8 100644 --- a/pkg/engine_test.go +++ b/pkg/engine_test.go @@ -2,6 +2,7 @@ package pkg import ( "context" + "math/rand/v2" "os" "runtime" "strings" @@ -13,6 +14,8 @@ import ( func TestMain(m *testing.M) { soundsMuted.Store(true) // tests never make a noise + // Stockfish replies at once (TestThinkTime covers the waiting) + engineThinkTime = func(*chess.Game, time.Duration, time.Duration, bool, *rand.Rand) time.Duration { return 0 } os.Exit(m.Run()) } diff --git a/pkg/engine_think.go b/pkg/engine_think.go new file mode 100644 index 0000000..a2bb208 --- /dev/null +++ b/pkg/engine_think.go @@ -0,0 +1,96 @@ +package pkg + +import ( + "math" + "math/rand/v2" + "time" + + "github.com/notnil/chess" +) + +// How long Stockfish takes over a move in a local game. It finds its move +// in well under a second at any level, so the reply is held back to a time a +// person might take: a share of the clock, less for the opening, a forced +// move or an obvious recapture, more for a position with lots going on, +// with some randomness so it doesn't feel mechanical. + +const ( + thinkNoClock = 3 * time.Second // the typical move without a clock + thinkMaxNoClk = 8 * time.Second + thinkMin = 400 * time.Millisecond + thinkMax = 30 * time.Second +) + +// engineThinkTime is thinkTime; tests replace it so they don't wait. +var engineThinkTime = thinkTime + +// thinkTime is how long to take over the move in pos. left and inc are the +// engine's time and increment; clock is false in a game without one. +func thinkTime(game *chess.Game, left, inc time.Duration, clock bool, r *rand.Rand) time.Duration { + pos := game.Position() + legal := pos.ValidMoves() + if len(legal) <= 1 { // nothing to think about + return jitter(500*time.Millisecond, r, 0.3) + } + + // the usual time for a move: a share of what's left, or a fixed + // amount without a clock + moveNo := len(game.Moves())/2 + 1 + budget := thinkNoClock + if clock { + movesLeft := max(40, 70-moveNo) // people plan for a long game + budget = left/time.Duration(movesLeft) + inc*3/4 + } + + // how much there is to think about + f := 1.0 + switch { + case moveNo <= 4: // known opening moves come quickly + f *= 0.25 + case moveNo <= 10: + f *= 0.6 + } + captures, checks := 0, 0 + for _, m := range legal { + if m.HasTag(chess.Capture) { + captures++ + } + if m.HasTag(chess.Check) { + checks++ + } + } + f *= 0.5 + math.Min(float64(len(legal)), 45)/45*0.5 + math.Min(float64(captures+checks), 6)*0.06 + if recapture(game, legal) { + f *= 0.5 + } + + t := jitter(time.Duration(float64(budget)*f), r, 0.35) + limit := thinkMaxNoClk + if clock { + limit = min(thinkMax, left/10) // never spend much of what's left + } + return max(min(thinkMin, limit), min(t, limit)) +} + +// recapture reports whether the last move took a piece that can be taken +// back: usually an obvious reply. +func recapture(game *chess.Game, legal []*chess.Move) bool { + moves := game.Moves() + if len(moves) == 0 || !moves[len(moves)-1].HasTag(chess.Capture) { + return false + } + to := moves[len(moves)-1].S2() + for _, m := range legal { + if m.S2() == to { + return true + } + } + return false +} + +// jitter scales d by a random factor around 1 (log-normal with spread s, +// kept within ½–2×). +func jitter(d time.Duration, r *rand.Rand, s float64) time.Duration { + k := math.Exp(r.NormFloat64() * s) + return time.Duration(float64(d) * math.Max(0.5, math.Min(2, k))) +} diff --git a/pkg/engine_think_test.go b/pkg/engine_think_test.go new file mode 100644 index 0000000..1ed5a66 --- /dev/null +++ b/pkg/engine_think_test.go @@ -0,0 +1,66 @@ +package pkg + +import ( + "math/rand/v2" + "testing" + "time" +) + +// Stockfish's thinking time looks like a person's: quick in the opening and +// for forced moves and recaptures, longer in a busy middlegame, a fair share +// of the clock, never much of what's left. +func TestThinkTime(t *testing.T) { + r := rand.New(rand.NewPCG(1, 2)) + // the median of many draws, so the randomness doesn't decide the test + median := func(sans string, left, inc time.Duration, clock bool) time.Duration { + t.Helper() + g, err := gameFromSAN("", sans) + if err != nil { + t.Fatal(err) + } + var ts []time.Duration + for range 201 { + d := thinkTime(g, left, inc, clock, r) + if d < 0 || (clock && d > max(thinkMin, left/10)) || (!clock && d > thinkMaxNoClk) { + t.Fatalf("%q: %v with %v left", sans, d, left) + } + ts = append(ts, d) + } + for i := range ts { // (insertion sort; it's small) + for j := i; j > 0 && ts[j] < ts[j-1]; j-- { + ts[j], ts[j-1] = ts[j-1], ts[j] + } + } + return ts[len(ts)/2] + } + const ten = 10 * time.Minute + middlegame := "e4 e5 Nf3 Nc6 Bc4 Bc5 c3 Nf6 d4 exd4 cxd4 Bb4+ Bd2 Bxd2+ Nbxd2 d5 exd5 Nxd5 Qb3 Nce7 O-O O-O Rfe1 c6" + opening := median("e4", ten, 0, true) + busy := median(middlegame, ten, 0, true) + if !(opening < busy/2) { + t.Errorf("opening %v, middlegame %v: the opening should be much quicker", opening, busy) + } + if busy < 5*time.Second || busy > 25*time.Second { + t.Errorf("middlegame move at 10+0 takes %v, want 5-25 s", busy) + } + // one legal move: after 1. e4 f5 2. Qh5+ Black must play g6 + if forced := median("e4 f5 Qh5+", ten, 0, true); forced > time.Second { + t.Errorf("forced move takes %v", forced) + } + // taking back: after ...Bxd2+ White recaptures quickly + retake := median("e4 e5 Nf3 Nc6 Bc4 Bc5 c3 Nf6 d4 exd4 cxd4 Bb4+ Bd2 Bxd2+", ten, 0, true) + if !(retake < busy) { + t.Errorf("recapture %v, middlegame %v", retake, busy) + } + // low on time: quick + if low := median(middlegame, 20*time.Second, 0, true); low > 2*time.Second { + t.Errorf("with 20 s left it takes %v", low) + } + // an increment buys time; no clock is a few seconds + if inc := median(middlegame, time.Minute, 5*time.Second, true); inc < 2*time.Second { + t.Errorf("1+5 with a minute left: %v", inc) + } + if none := median(middlegame, 0, 0, false); none < time.Second || none > thinkMaxNoClk { + t.Errorf("no clock: %v", none) + } +}