forked from lichess-org/mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffline_computer_game_controller.dart
More file actions
972 lines (840 loc) · 34.4 KB
/
offline_computer_game_controller.dart
File metadata and controls
972 lines (840 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
import 'dart:async';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:dartchess/dartchess.dart';
import 'package:deep_pick/deep_pick.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:lichess_mobile/src/model/analysis/analysis_controller.dart';
import 'package:lichess_mobile/src/model/common/chess.dart';
import 'package:lichess_mobile/src/model/common/chess960.dart';
import 'package:lichess_mobile/src/model/common/eval.dart';
import 'package:lichess_mobile/src/model/common/id.dart';
import 'package:lichess_mobile/src/model/common/perf.dart';
import 'package:lichess_mobile/src/model/common/service/move_feedback.dart';
import 'package:lichess_mobile/src/model/common/socket.dart';
import 'package:lichess_mobile/src/model/common/speed.dart';
import 'package:lichess_mobile/src/model/common/uci.dart';
import 'package:lichess_mobile/src/model/engine/engine.dart';
import 'package:lichess_mobile/src/model/engine/evaluation_service.dart';
import 'package:lichess_mobile/src/model/engine/work.dart';
import 'package:lichess_mobile/src/model/explorer/opening_explorer.dart';
import 'package:lichess_mobile/src/model/explorer/opening_explorer_preferences.dart';
import 'package:lichess_mobile/src/model/explorer/opening_explorer_repository.dart';
import 'package:lichess_mobile/src/model/explorer/tablebase.dart';
import 'package:lichess_mobile/src/model/explorer/tablebase_repository.dart';
import 'package:lichess_mobile/src/model/game/game.dart';
import 'package:lichess_mobile/src/model/game/game_status.dart';
import 'package:lichess_mobile/src/model/game/material_diff.dart';
import 'package:lichess_mobile/src/model/game/offline_computer_game.dart';
import 'package:lichess_mobile/src/model/game/player.dart';
import 'package:lichess_mobile/src/model/offline_computer/computer_analysis.dart';
import 'package:lichess_mobile/src/model/offline_computer/offline_computer_game_storage.dart';
import 'package:lichess_mobile/src/model/offline_computer/practice_comment.dart';
import 'package:lichess_mobile/src/model/offline_computer/tablebase_eval.dart';
import 'package:lichess_mobile/src/network/socket.dart';
import 'package:logging/logging.dart';
import 'package:multistockfish/multistockfish.dart';
part 'offline_computer_game_controller.freezed.dart';
final _random = Random();
final _logger = Logger('OfflineComputerGameController');
/// The number of CPU cores to use for engine evaluation.
final numberOfCoresForEvaluation = max(1, maxEngineCores - 1);
/// Ply threshold for opening phase. Below this, we check the master database
/// to consider book moves as good regardless of engine evaluation.
const _kOpeningPlyThreshold = 30;
/// Max search time for hints evaluation.
const _kHintsMaxSearchTime = Duration(milliseconds: 3000);
/// Depth threshold for using an engine evaluation for hints.
///
/// Lower end devices will probably not reach it so the evaluation will run for the full search time
/// but it helps to get faster feedback on move quality and hints on higher end devices.
// TODO: consider using searched nodes instead of depth
const _kHintsEvalMinDepth = kDebugMode ? 14 : 18;
/// Min search time for a move evaluation in practice mode when the move is not in the pre-move PVs.
const _kMoveEvalMinSearchTime = Duration(milliseconds: 1000);
/// Max search time for a move evaluation in practice mode when the move is not in the pre-move PVs.
///
/// We want a fast feedback here, and since multipv=1 the search should be fast.
const _kMoveEvalMaxSearchTime = Duration(milliseconds: 2000);
/// Depth threshold for using an engine evaluation for move evaluation in practice mode.
///
/// The search is done with multipv=1 here, so we can reach higher depths.
const _kMoveEvalMinDepth = kDebugMode ? 14 : 18;
/// Stockfish flavor to use for the engine opponent and hint generation.
///
/// We use Fairy-Stockfish here for the negative skill levels and variant support.
const _kComputerStockfishFlavor = StockfishFlavor.variant;
final offlineComputerGameControllerProvider =
NotifierProvider.autoDispose<OfflineComputerGameController, OfflineComputerGameState>(
OfflineComputerGameController.new,
name: 'OfflineComputerGameControllerProvider',
);
class OfflineComputerGameController extends Notifier<OfflineComputerGameState> {
late SocketClient socketClient;
StreamSubscription<SocketEvent>? _socketSubscription;
Timer? _getEvalTimer;
@override
OfflineComputerGameState build() {
socketClient = ref.watch(socketPoolProvider).open(AnalysisController.socketUri);
_socketSubscription?.cancel();
_socketSubscription = socketClient.stream.listen(_handleSocketEvent);
final evaluationService = ref.watch(evaluationServiceProvider);
ref.onDispose(() {
evaluationService.quit();
_socketSubscription?.cancel();
_getEvalTimer?.cancel();
});
return OfflineComputerGameState.initial(
stockfishLevel: StockfishLevel.defaultLevel,
playerSide: Side.white,
);
}
void startNewGame({
required StockfishLevel stockfishLevel,
required Side playerSide,
required bool casual,
required bool practiceMode,
Variant variant = Variant.standard,
String? initialFen,
}) {
state = OfflineComputerGameState.initial(
stockfishLevel: stockfishLevel,
playerSide: playerSide,
casual: casual,
practiceMode: practiceMode,
variant: variant,
initialFen: initialFen,
);
if (state.turn != playerSide) {
_playEngineMove();
} else if (casual || practiceMode) {
_computeHints();
}
}
/// Load a game from storage.
void loadGame(SavedOfflineComputerGame savedGame) {
final game = savedGame.game;
state = OfflineComputerGameState(game: game, stepCursor: game.steps.length - 1);
if (game.playable && state.turn == game.playerSide && (game.casual || game.practiceMode)) {
_computeHints();
} else if (game.playable && state.turn != game.playerSide) {
_playEngineMove();
}
}
void makeMove(Move move) {
if (state.isEngineThinking || state.isEvaluatingMove || !state.game.playable) return;
if (move case NormalMove() when isPromotionPawnMove(state.currentPosition, move)) {
state = state.copyWith(promotionMove: move);
return;
}
if (state.game.practiceMode) {
_makeMoveWithEvaluation(move);
} else {
_applyMove(move);
if (state.game.playable) {
_playEngineMove();
}
}
}
void onPromotionSelection(Role? role) {
if (role == null) {
state = state.copyWith(promotionMove: null);
return;
}
final promotionMove = state.promotionMove;
if (promotionMove != null) {
final move = promotionMove.withPromotion(role);
state = state.copyWith(promotionMove: null);
if (state.game.practiceMode) {
_makeMoveWithEvaluation(move);
} else {
_applyMove(move);
if (state.game.playable) {
_playEngineMove();
}
}
}
}
SanMove _applyMove(Move move) {
final (newPos, newSan) = state.currentPosition.makeSan(Move.parse(move.uci)!);
final sanMove = SanMove(newSan, move);
final newStep = GameStep(
position: newPos,
sanMove: sanMove,
diff: MaterialDiff.fromPosition(newPos),
);
state = state.copyWith(
game: state.game.copyWith(steps: state.game.steps.add(newStep)),
stepCursor: state.stepCursor + 1,
hintIndex: null,
showingSuggestedMove: null,
);
if (state.game.steps.count((p) => p.position.board == newStep.position.board) == 3) {
state = state.copyWith(game: state.game.copyWith(isThreefoldRepetition: true));
} else {
state = state.copyWith(game: state.game.copyWith(isThreefoldRepetition: false));
}
if (state.currentPosition.isCheckmate) {
state = state.copyWith(
game: state.game.copyWith(status: GameStatus.mate, winner: state.turn.opposite),
);
} else if (state.currentPosition.isStalemate) {
state = state.copyWith(game: state.game.copyWith(status: GameStatus.stalemate));
} else if (state.currentPosition.isInsufficientMaterial) {
state = state.copyWith(game: state.game.copyWith(status: GameStatus.draw));
} else if (state.currentPosition.isVariantEnd) {
state = state.copyWith(
game: state.game.copyWith(
status: GameStatus.variantEnd,
winner: state.currentPosition.variantOutcome?.winner,
),
);
}
_moveFeedback(sanMove);
return sanMove;
}
/// Make a player move with practice mode evaluation.
///
/// Uses the cached PV data from _computeHints as the "before" state,
/// then evaluates the position after the move to determine how good the move was.
/// If hint computation is still in progress, waits for it to complete first.
///
/// In the opening phase (before [_kOpeningPlyThreshold]), also fetches the master
/// database to consider book moves as good regardless of engine evaluation.
Future<void> _makeMoveWithEvaluation(Move move) async {
if (!state.game.practiceMode || !state.game.playable) return;
var preMoveAnalysis = state.currentAnalysis;
final cursorBeforeMove = state.stepCursor;
final positionBefore = state.currentPosition;
final plyBeforeMove = state.currentPosition.ply;
final stepsBeforeMove = state.game.steps
.skip(1)
.map((s) => Step(position: s.position, sanMove: s.sanMove!))
.toIList();
state = state.copyWith(isEvaluatingMove: true);
final sanMove = _applyMove(move);
final stepCursorAfterMove = state.stepCursor;
if (!state.game.playable) {
state = state.copyWith(isEvaluatingMove: false);
return;
}
// If hints were still loading when we made the move, wait for them to complete so we can get
// the "before" evaluation for comparison.
// Wait time must be longer than _kHintsMaxSearchTime to account for engine startup overhead.
if (state.isLoadingHint) {
final maxWaitTime = _kHintsMaxSearchTime + const Duration(milliseconds: 1000);
final deadline = DateTime.now().add(maxWaitTime);
while (state.isLoadingHint && ref.mounted && DateTime.now().isBefore(deadline)) {
await Future<void>.delayed(const Duration(milliseconds: 50));
}
if (!ref.mounted) return;
preMoveAnalysis = state.game.steps[cursorBeforeMove].computerAnalysis;
} else if (preMoveAnalysis?.eval == null) {
// Not loading hints and hints are null? Let's run a quick evaluation
final evalBefore = await _getEval(
_makeMoveEvalWork(stepsBeforeMove),
minSearchTime: _kMoveEvalMinSearchTime,
depthThreshold: _kMoveEvalMinDepth,
tablebaseLookupPosition: positionBefore,
);
_logger.info(
'Before move eval fallback: depth=${evalBefore?.depth}, searchTime=${evalBefore is LocalEval ? evalBefore.searchTime : null} nodes=${evalBefore?.nodes} score=${evalBefore?.evalString}',
);
if (!ref.mounted) return;
if (evalBefore != null) {
preMoveAnalysis = ComputerAnalysis(eval: evalBefore);
_setStepAnalysis(cursorBeforeMove, preMoveAnalysis);
}
}
final preMoveEval = preMoveAnalysis?.eval;
// If we still don't have cached evaluation, proceed without practice comment
if (preMoveEval == null || preMoveEval.pvs.isEmpty) {
state = state.copyWith(isEvaluatingMove: false);
if (state.turn != state.game.playerSide) {
_playEngineMove();
}
return;
}
final playerSide = state.game.playerSide;
final normalizedMoveUci = sanMove.isCastles ? normalizeUci(move.uci) : move.uci;
final matchingPv = preMoveEval.pvs.firstWhereOrNull(
(pv) => pv.moves.isNotEmpty && pv.moves.first == normalizedMoveUci,
);
// Makes or updates the comment verdict to goodMove if the move is a known book move.
if (state.game.meta.variant == Variant.standard && plyBeforeMove < _kOpeningPlyThreshold) {
_makeCommentFromOpeningDb(
sanMove,
stepCursor: stepCursorAfterMove,
positionBefore: positionBefore,
fromPosition: state.currentPosition,
);
}
// Fast path: move was in the pre-move PVs.
if (matchingPv != null) {
final comment = _createPracticeComment(
sanMove: sanMove,
preMoveEval: preMoveEval,
winningChancesAfter: matchingPv.winningChances(playerSide),
evalAfterString: matchingPv.evalString,
playerSide: playerSide,
);
_setComment(stepCursorAfterMove, comment);
state = state.copyWith(isEvaluatingMove: false);
if (state.game.playable && state.turn != state.game.playerSide) {
_playEngineMove();
}
return;
}
// Slow path: move not in computed hints PVs, evaluate the resulting position.
_logger.info('Move not in computed hints PVs, evaluating: ${move.uci}');
try {
final stepsAfter = state.game.steps
.skip(1)
.map((s) => Step(position: s.position, sanMove: s.sanMove!))
.toIList();
final workAfter = _makeMoveEvalWork(stepsAfter);
final positionAfterMove = state.currentPosition;
final evalAfter = await _getEval(
workAfter,
minSearchTime: _kMoveEvalMinSearchTime,
depthThreshold: _kMoveEvalMinDepth,
tablebaseLookupPosition: positionAfterMove,
);
if (!ref.mounted) return;
if (evalAfter != null) {
_logger.info(
'Move eval computed for ply=${workAfter.position.ply} depth=${evalAfter.depth}, searchTime=${evalAfter is LocalEval ? evalAfter.searchTime : null} nodes=${evalAfter.nodes} score=${evalAfter.evalString}',
);
final comment = _createPracticeComment(
sanMove: sanMove,
preMoveEval: preMoveEval,
winningChancesAfter: -evalAfter.winningChances(playerSide.opposite),
evalAfterString: evalAfter.evalString,
playerSide: playerSide,
);
_setComment(stepCursorAfterMove, comment);
}
state = state.copyWith(isEvaluatingMove: false);
if (state.game.playable && state.turn != state.game.playerSide) {
_playEngineMove();
}
} catch (e) {
_logger.warning('Error evaluating move: $e');
if (ref.mounted) {
state = state.copyWith(isEvaluatingMove: false);
if (state.game.playable && state.turn != state.game.playerSide) {
_playEngineMove();
}
}
}
}
EvalWork _makeMoveEvalWork(IList<Step> steps) {
return EvalWork(
id: state.game.id,
stockfishFlavor: _kComputerStockfishFlavor,
variant: state.game.meta.variant,
threads: numberOfCoresForEvaluation,
hashSize: ref.read(evaluationServiceProvider).maxMemory,
searchTime: _kMoveEvalMaxSearchTime,
// We want the fastest search here and we only need the eval
multiPv: 1,
threatMode: false,
initialPosition: state.game.initialPosition,
steps: steps,
);
}
/// Gets an evaluation by requesting at the same time the local engine and a cloud eval and optionnally doing a tablebase lookup.
///
/// Returns the first eval that comes back with a valid score.
Future<ClientEval?> _getEval(
EvalWork work, {
int? depthThreshold,
Duration? minSearchTime,
/// Optional position for doing a tablebase lookup in parallel. If provided, the tablebase eval will be returned if it's conclusive and returned before the engine eval.
Position? tablebaseLookupPosition,
}) {
final evaluationService = ref.read(evaluationServiceProvider);
final Completer<ClientEval?> completer = Completer();
// Fallback timer in case neither engine nor cloud eval return in time (should not happen for
// engine).
_getEvalTimer?.cancel();
_getEvalTimer = Timer(work.searchTime + const Duration(seconds: 3), () {
if (!completer.isCompleted) {
completer.complete(null);
}
});
evaluationService
.findEval(work, depthThreshold: depthThreshold, minSearchTime: minSearchTime)
.then((eval) {
if (!completer.isCompleted && eval != null) {
completer.complete(eval);
}
});
if (state.game.meta.variant == Variant.standard && work.position.ply < _kOpeningPlyThreshold) {
_getCloudEval(work, numEvalLines: work.multiPv).then((cloudEval) {
if (!completer.isCompleted && cloudEval != null) {
completer.complete(cloudEval);
if (evaluationService.evaluationState.value.currentWork == work) {
evaluationService.stop();
}
}
});
}
if (tablebaseLookupPosition != null) {
if (isTablebaseRelevant(tablebaseLookupPosition)) {
_fetchTablebaseEval(tablebaseLookupPosition).then((tablebaseEval) {
if (!completer.isCompleted && tablebaseEval != null) {
completer.complete(tablebaseEval);
if (evaluationService.evaluationState.value.currentWork == work) {
evaluationService.stop();
}
}
});
}
}
return completer.future;
}
void _handleSocketEvent(SocketEvent event) {
// not handling any events for now, but we keep the connection open
_logger.finer('Received socket event: ${event.topic}');
}
Future<CloudEval?> _getCloudEval(EvalWork work, {required int numEvalLines}) async {
CloudEval? eval;
try {
final uciPath = UciPath.fromUciMoves(
work.steps.map((s) => s.sanMove.normalizeUci(state.game.meta.variant)),
);
_logger.fine(
'Requesting cloud eval for ply ${work.position.ply} and fen ${work.position.fen}',
);
socketClient.send('evalGet', {
'fen': work.position.fen,
'path': uciPath.value,
if (work.position.rule != Rule.chess) 'variant': Variant.fromRule(work.position.rule).name,
'mpv': numEvalLines,
});
await for (final event
in socketClient.stream
.where((e) => e.topic == 'evalHit')
.timeout(const Duration(seconds: 2))) {
final path = pick(event.data, 'path').asStringOrThrow();
if (path != uciPath.value) {
continue;
}
final nodes = pick(event.data, 'knodes').asIntOrThrow() * 1000;
final depth = pick(event.data, 'depth').asIntOrThrow();
final pvs = pick(event.data, 'pvs')
.asListOrThrow(
(pv) => PvData(
moves: pv('moves').asStringOrThrow().split(' ').toIList(),
cp: pv('cp').asIntOrNull(),
mate: pv('mate').asIntOrNull(),
),
)
.toIList();
_logger.fine('Got a cloud eval at ply ${work.position.ply} with depth $depth');
eval = CloudEval(depth: depth, nodes: nodes, pvs: pvs, position: work.position);
break;
}
} catch (e) {
_logger.fine('Could not get cloud eval: $e');
}
return eval;
}
/// Creates a practice comment based on pre-move PV data and the post-move eval.
PracticeComment _createPracticeComment({
required SanMove sanMove,
required ClientEval preMoveEval,
required double winningChancesAfter,
required String? evalAfterString,
required Side playerSide,
}) {
final winningChancesBefore = preMoveEval.winningChances(playerSide);
final shift = winningChancesBefore - winningChancesAfter;
final bestPv = preMoveEval.pvs.first;
final bestMove = bestPv.moves.isNotEmpty ? Move.parse(bestPv.moves.first) : null;
final playedMoveIsBest =
bestMove != null && bestMove.uci == sanMove.normalizeUci(state.game.meta.variant);
final isGoodMove = shift < kGoodMoveThreshold;
// Find alternative good move if the played move was good
Move? alternativeGoodMove;
if (isGoodMove && preMoveEval.pvs.length > 1) {
for (final pv in preMoveEval.pvs.skip(1)) {
if (pv.moves.isEmpty) continue;
if (winningChancesBefore - pv.winningChances(playerSide) < kGoodMoveThreshold &&
pv.moves.first != sanMove.normalizeUci(state.game.meta.variant)) {
alternativeGoodMove = Move.parse(pv.moves.first);
break;
}
}
}
final verdict = MoveVerdict.fromShift(
shift,
hasBetterMove: !playedMoveIsBest,
winningChancesBefore: winningChancesBefore,
winningChancesAfter: winningChancesAfter,
);
final positionBeforeMove = state.game.stepAt(state.stepCursor - 1).position;
SanMove? bestMoveSan;
if (!playedMoveIsBest && bestMove != null) {
if (positionBeforeMove.isLegal(bestMove)) {
final (_, san) = positionBeforeMove.makeSan(bestMove);
bestMoveSan = SanMove(san, bestMove);
}
}
SanMove? alternativeGoodMoveSan;
if (alternativeGoodMove != null) {
if (positionBeforeMove.isLegal(alternativeGoodMove)) {
final (_, san) = positionBeforeMove.makeSan(alternativeGoodMove);
alternativeGoodMoveSan = SanMove(san, alternativeGoodMove);
}
}
return PracticeComment(
verdict: verdict,
moveSuggestion: bestMoveSan ?? alternativeGoodMoveSan,
evalAfter: evalAfterString,
isBookMove: false,
);
}
Future<void> _makeCommentFromOpeningDb(
SanMove sanMove, {
required int stepCursor,
required Position positionBefore,
required Position fromPosition,
}) async {
final masterEntry = await _fetchMasterDatabase(positionBefore.fen);
if (!ref.mounted || masterEntry == null) return;
if (state.currentPosition != fromPosition) return;
final currentComment = state.game.steps[stepCursor].computerAnalysis?.practiceComment;
if (currentComment?.isBookMove == true) return;
final isBookMove = masterEntry.moves.any(
(m) => m.uci == sanMove.normalizeUci(state.game.meta.variant) && m.games > 1,
);
if (!isBookMove) return;
if (currentComment != null) {
final updatedComment = currentComment.copyWith(
verdict: MoveVerdict.goodMove,
isBookMove: true,
);
_setComment(stepCursor, updatedComment);
} else {
_setComment(
stepCursor,
const PracticeComment(verdict: MoveVerdict.goodMove, isBookMove: true),
);
}
}
/// Fetch the master database for the given FEN.
///
/// Returns null if the request fails (e.g., no connectivity) or times out.
Future<OpeningExplorerEntry?> _fetchMasterDatabase(String fen) async {
try {
final repository = ref.read(openingExplorerRepositoryProvider);
return await repository
.getMasterDatabase(fen, since: MasterDb.kEarliestYear)
.timeout(const Duration(seconds: 2));
} catch (e) {
_logger.fine('Failed to fetch master database: $e');
return null;
}
}
/// Fetches the tablebase eval for the given position.
///
/// Returns null if the network request fails or the entry is not conclusive.
Future<ClientEval?> _fetchTablebaseEval(Position position) async {
try {
final entry = await ref.read(tablebaseRepositoryProvider).getTablebaseEntry(position.fen);
return tablebaseEntryToCloudEval(entry, position);
} catch (e) {
_logger.fine('Could not get tablebase eval: $e');
return null;
}
}
Future<void> _playEngineMove() async {
if (!state.game.playable) return;
state = state.copyWith(isEngineThinking: true);
try {
final evaluationService = ref.read(evaluationServiceProvider);
final steps = state.game.steps
.skip(1)
.map((s) => Step(position: s.position, sanMove: s.sanMove!))
.toIList();
final work = MoveWork(
id: state.game.id,
variant: state.game.meta.variant,
hashSize: evaluationService.maxMemory,
initialPosition: state.game.initialPosition,
steps: steps,
level: state.game.stockfishLevel,
);
final uciMove = await evaluationService.findMove(work);
final move = NormalMove.fromUci(uciMove);
if (state.game.playable) {
_applyMove(move);
// After engine move, precompute hints for player's turn (in casual or practice mode)
if (state.game.playable && (state.game.casual || state.game.practiceMode)) {
_computeHints();
}
}
} catch (e) {
// Engine was stopped or error occurred, ignore
} finally {
if (state.game.playable || state.game.finished) {
state = state.copyWith(isEngineThinking: false);
}
}
}
void resign() {
if (!state.game.resignable) return;
state = state.copyWith(
game: state.game.copyWith(status: GameStatus.resign, winner: state.game.playerSide.opposite),
isEngineThinking: false,
);
}
/// Claim a draw due to threefold repetition.
void claimThreefoldDraw() {
if (!state.game.playable || state.game.isThreefoldRepetition != true) return;
ref.read(evaluationServiceProvider).stop();
state = state.copyWith(
game: state.game.copyWith(status: GameStatus.draw, isThreefoldRepetition: false),
isEngineThinking: false,
);
}
void takeback() {
if (!state.canTakeback) return;
if (!state.game.casual && !state.game.practiceMode) return;
ref.read(evaluationServiceProvider).stop();
int stepsToRemove = 1;
if (state.game.steps.length > 2 && state.turn == state.game.playerSide) {
// If it's the player's turn, remove both moves
stepsToRemove = 2;
}
final newSteps = state.game.steps.removeLast();
final finalSteps = stepsToRemove == 2 && newSteps.length > 1 ? newSteps.removeLast() : newSteps;
state = state.copyWith(
game: state.game.copyWith(steps: finalSteps, isThreefoldRepetition: false),
stepCursor: finalSteps.length - 1,
isEngineThinking: false,
isEvaluatingMove: false,
hintIndex: null,
showingSuggestedMove: null,
);
if (state.turn != state.game.playerSide && state.game.playable) {
_playEngineMove();
} else if (state.game.playable && (state.game.casual || state.game.practiceMode)) {
_computeHints();
}
}
void goForward() {
if (state.canGoForward) {
state = state.copyWith(stepCursor: state.stepCursor + 1, promotionMove: null);
}
}
void goBack() {
if (state.canGoBack) {
state = state.copyWith(stepCursor: state.stepCursor - 1, promotionMove: null);
}
}
/// Show or cycle through hints.
///
/// Hints are precomputed when it's the player's turn (in casual or practice mode).
/// This method just cycles through the available hints.
void hint() {
if (!state.game.casual && !state.game.practiceMode) return;
if (!state.game.playable || state.isEngineThinking || state.isLoadingHint) return;
if (state.turn != state.game.playerSide) return;
final existingHints = state.hintMoves;
if (existingHints == null || existingHints.isEmpty) return;
final currentIndex = state.hintIndex;
// Show the first hint, or cycle to the next one
if (currentIndex == null) {
state = state.copyWith(hintIndex: 0);
} else {
state = state.copyWith(hintIndex: (currentIndex + 1) % existingHints.length);
}
}
/// Precompute hints for the current position.
///
/// Called automatically when it's the player's turn (in casual or practice mode).
/// In practice mode, also caches the evaluation for later comparison.
Future<void> _computeHints() async {
if (!state.game.casual && !state.game.practiceMode) return;
if (!state.game.playable || state.turn != state.game.playerSide) return;
if (state.currentAnalysis?.eval != null) return;
final hintStepCursor = state.stepCursor;
final hintPosition = state.currentPosition;
state = state.copyWith(isLoadingHint: true, hintIndex: null);
try {
final evaluationService = ref.read(evaluationServiceProvider);
final steps = state.game.steps
.skip(1)
.map((s) => Step(position: s.position, sanMove: s.sanMove!))
.toIList();
final work = EvalWork(
id: state.game.id,
stockfishFlavor: _kComputerStockfishFlavor,
variant: state.game.meta.variant,
threads: numberOfCoresForEvaluation,
hashSize: evaluationService.maxMemory,
searchTime: _kHintsMaxSearchTime,
multiPv: 2, // 2 lines of hints to show an alternative move
threatMode: false,
initialPosition: state.game.initialPosition,
steps: steps,
);
final finalEval = await _getEval(
work,
// Let's use a longer minimal search here because of the multipv and because it is computed
// during player's turn
minSearchTime: const Duration(milliseconds: 1500),
depthThreshold: _kHintsEvalMinDepth,
);
if (!ref.mounted) return;
_logger.info(
'Hints computed for ply=${work.position.ply} depth=${finalEval?.depth}, searchTime=${finalEval is LocalEval ? finalEval.searchTime : null} nodes=${finalEval?.nodes} score=${finalEval?.evalString}',
);
// Guard against a stale call: a takeback may have removed steps so the cursor is
// out of bounds, or the position at that cursor has changed.
if (finalEval != null &&
hintStepCursor < state.game.steps.length &&
state.game.steps[hintStepCursor].position == hintPosition) {
_setStepAnalysis(hintStepCursor, ComputerAnalysis(eval: finalEval));
}
} finally {
if (ref.mounted) {
state = state.copyWith(isLoadingHint: false);
}
}
}
/// Toggle showing a suggested move on the board.
void toggleSuggestedMove(NormalMove? move) {
if (state.showingSuggestedMove == move) {
state = state.copyWith(showingSuggestedMove: null);
} else {
state = state.copyWith(showingSuggestedMove: move);
}
}
void _moveFeedback(SanMove sanMove) {
final isCheck = sanMove.san.contains('+');
if (sanMove.san.contains('x')) {
ref
.read(moveFeedbackServiceProvider)
.captureFeedback(state.game.meta.variant, check: isCheck);
} else {
ref.read(moveFeedbackServiceProvider).moveFeedback(check: isCheck);
}
}
/// Updates the computer analysis on the game step at [stepIndex].
void _setStepAnalysis(int stepIndex, ComputerAnalysis analysis) {
final updatedStep = state.game.steps[stepIndex].copyWith(computerAnalysis: analysis);
state = state.copyWith(
game: state.game.copyWith(steps: state.game.steps.put(stepIndex, updatedStep)),
);
}
/// Saves a practice comment on the game step at [stepIndex].
void _setComment(int stepIndex, PracticeComment comment) {
_setStepAnalysis(stepIndex, ComputerAnalysis(practiceComment: comment));
}
}
@freezed
sealed class OfflineComputerGameState with _$OfflineComputerGameState {
const OfflineComputerGameState._();
const factory OfflineComputerGameState({
required OfflineComputerGame game,
@Default(0) int stepCursor,
@Default(null) NormalMove? promotionMove,
@Default(false) bool isEngineThinking,
@Default(false) bool isLoadingHint,
/// Current hint index for cycling through hints. Null means no hint is shown yet.
@Default(null) int? hintIndex,
/// Whether the engine is evaluating the player's move in practice mode.
@Default(false) bool isEvaluatingMove,
/// The suggested move to show on the board (when user taps on "Best was X" in practice mode).
@Default(null) NormalMove? showingSuggestedMove,
}) = _OfflineComputerGameState;
factory OfflineComputerGameState.initial({
required StockfishLevel stockfishLevel,
required Side playerSide,
Variant variant = Variant.standard,
bool casual = true,
bool practiceMode = false,
String? initialFen,
}) {
final Position position;
final Variant effectiveVariant;
final String? effectiveInitialFen;
if (initialFen != null) {
position = Chess.fromSetup(Setup.parseFen(initialFen));
effectiveVariant = Variant.fromPosition;
effectiveInitialFen = initialFen;
} else if (variant == Variant.chess960) {
position = randomChess960Position();
effectiveVariant = Variant.chess960;
effectiveInitialFen = position.fen;
} else {
position = variant.initialPosition;
effectiveVariant = variant;
effectiveInitialFen = null;
}
final sessionId = StringId('ocg_${_random.nextInt(1 << 32).toRadixString(16).padLeft(8, '0')}');
return OfflineComputerGameState(
game: OfflineComputerGame(
id: sessionId,
steps: [GameStep(position: position)].lock,
status: GameStatus.started,
initialFen: effectiveInitialFen,
meta: GameMeta(
createdAt: DateTime.now(),
rated: false,
variant: effectiveVariant,
speed: Speed.classical,
perf: Perf.fromVariantAndSpeed(effectiveVariant, Speed.classical),
),
playerSide: playerSide,
stockfishLevel: stockfishLevel,
casual: casual,
practiceMode: practiceMode,
humanPlayer: const Player(onGame: true),
enginePlayer: stockfishPlayer(),
),
);
}
/// The computer analysis for the current step.
ComputerAnalysis? get currentAnalysis => game.steps[stepCursor].computerAnalysis;
/// The practice comment which can be on the last step or the previous step (after computer played a move).
PracticeComment? get practiceComment =>
game.steps.last.computerAnalysis?.practiceComment ??
(game.steps.length >= 2
? game.steps[game.steps.length - 2].computerAnalysis?.practiceComment
: null);
/// The hint moves for the current position.
IList<Move>? get hintMoves => currentAnalysis?.hintMoves;
Position get currentPosition => game.stepAt(stepCursor).position;
Side get turn => currentPosition.turn;
bool get finished => game.finished;
NormalMove? get lastMove =>
stepCursor > 0 ? NormalMove.fromUci(game.steps[stepCursor].sanMove!.move.uci) : null;
MaterialDiffSide? currentMaterialDiff(Side side) {
return game.steps[stepCursor].diff?.bySide(side);
}
List<String> get moves => game.steps.skip(1).map((e) => e.sanMove!.san).toList(growable: false);
bool get canGoForward => stepCursor < game.steps.length - 1;
bool get canGoBack => stepCursor > 0;
/// Player can take back if it's their turn and there are moves to take back.
bool get canTakeback =>
game.playable && game.steps.length > 1 && !isEngineThinking && !isEvaluatingMove;
/// The square to highlight for the current hint.
Square? get hintSquare {
final moves = hintMoves;
final index = hintIndex;
if (moves == null || moves.isEmpty || index == null) return null;
final move = moves[index];
return switch (move) {
NormalMove(:final from) => from,
DropMove() => null,
};
}
}