-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathuseOpeningDrillController.ts
More file actions
1445 lines (1254 loc) · 44.2 KB
/
useOpeningDrillController.ts
File metadata and controls
1445 lines (1254 loc) · 44.2 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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useState, useMemo, useCallback, useEffect, useRef } from 'react'
import { Chess } from 'chess.ts'
import { getGameMove } from 'src/api/play/play'
import { logOpeningDrill } from 'src/api/opening'
import { useTreeController } from '../useTreeController'
import { useLocalStorage } from '../useLocalStorage'
import {
GameTree,
GameNode,
StockfishEvaluation,
MaiaEvaluation,
} from 'src/types'
import {
OpeningSelection,
OpeningDrillGame,
CompletedDrill,
DrillPerformanceData,
OverallPerformanceData,
DrillConfiguration,
MoveAnalysis,
EvaluationPoint,
RatingPrediction,
RatingComparison,
} from 'src/types/openings'
import { MAIA_MODELS } from 'src/constants/common'
import { MIN_STOCKFISH_DEPTH } from 'src/constants/analysis'
import { chessSoundManager } from 'src/lib/chessSoundManager'
interface CachedAnalysisResult {
fen: string
stockfish: StockfishEvaluation | null
maia: MaiaEvaluation | null
timestamp: number
}
interface AnalysisProgress {
total: number
completed: number
currentMove: string | null
}
const parsePgnToTree = (pgn: string, gameTree: GameTree): GameNode | null => {
if (!pgn || pgn.trim() === '') return gameTree.getRoot()
const chess = new Chess()
let currentNode = gameTree.getRoot()
const moveText = pgn.replace(/\d+\./g, '').trim()
const moves = moveText.split(/\s+/).filter((move) => move && move !== '')
for (const moveStr of moves) {
try {
const moveObj = chess.move(moveStr)
if (!moveObj) break
const moveUci = moveObj.from + moveObj.to + (moveObj.promotion || '')
const existingChild = currentNode.children.find(
(child: GameNode) => child.move === moveUci,
)
if (existingChild) {
currentNode = existingChild
} else {
const newNode = gameTree.addMainMove(
currentNode,
chess.fen(),
moveUci,
moveObj.san,
)
if (newNode) {
currentNode = newNode
} else {
break
}
}
} catch (error) {
console.error('Error parsing move:', moveStr, error)
break
}
}
return currentNode
}
export const useOpeningDrillController = (
configuration: DrillConfiguration,
) => {
const [remainingDrills, setRemainingDrills] = useState<OpeningSelection[]>([])
const [currentDrill, setCurrentDrill] = useState<OpeningSelection | null>(
null,
)
const [completedDrills, setCompletedDrills] = useState<CompletedDrill[]>([])
const [currentDrillGame, setCurrentDrillGame] =
useState<OpeningDrillGame | null>(null)
const [analysisEnabled, setAnalysisEnabled] = useState(false)
const [currentDrillIndex, setCurrentDrillIndex] = useState(0)
const [allDrillsCompleted, setAllDrillsCompleted] = useState(false)
const [showPerformanceModal, setShowPerformanceModal] = useState(false)
const [showFinalModal, setShowFinalModal] = useState(false)
const [currentPerformanceData, setCurrentPerformanceData] =
useState<DrillPerformanceData | null>(null)
const [isAnalyzingDrill, setIsAnalyzingDrill] = useState(false)
const ensureAnalysisCompleteRef = useRef<
((nodes: GameNode[]) => Promise<void>) | null
>(null)
const [waitingForMaiaResponse, setWaitingForMaiaResponse] = useState(false)
const [continueAnalyzingMode, setContinueAnalyzingMode] = useState(false)
const [analysisProgress, setAnalysisProgress] = useState<AnalysisProgress>({
total: 0,
completed: 0,
currentMove: null,
})
const analysisCache = useRef<Map<string, CachedAnalysisResult>>(new Map())
const MAX_CACHE_SIZE = 100
const CACHE_CLEANUP_INTERVAL = 60000
const [currentMaiaModel, setCurrentMaiaModel] = useLocalStorage(
'currentMaiaModel',
MAIA_MODELS[0],
)
useEffect(() => {
if (!MAIA_MODELS.includes(currentMaiaModel)) {
setCurrentMaiaModel(MAIA_MODELS[0])
}
}, [currentMaiaModel, setCurrentMaiaModel])
useEffect(() => {
const cleanupCache = () => {
const cache = analysisCache.current
if (cache.size > MAX_CACHE_SIZE) {
const entries = Array.from(cache.entries())
entries
.sort((a, b) => a[1].timestamp - b[1].timestamp)
.slice(0, cache.size - MAX_CACHE_SIZE + 10)
.forEach(([key]) => cache.delete(key))
}
const tenMinutesAgo = Date.now() - 600000
for (const [key, value] of cache.entries()) {
if (value.timestamp < tenMinutesAgo) {
cache.delete(key)
}
}
}
const intervalId = setInterval(cleanupCache, CACHE_CLEANUP_INTERVAL)
return () => clearInterval(intervalId)
}, [])
useEffect(() => {
if (
configuration.drillSequence.length > 0 &&
remainingDrills.length === 0 &&
!allDrillsCompleted
) {
setRemainingDrills(configuration.drillSequence)
setCurrentDrill(configuration.drillSequence[0])
setCurrentDrillIndex(0)
}
}, [configuration.drillSequence, remainingDrills.length, allDrillsCompleted])
useEffect(() => {
if (!currentDrill || allDrillsCompleted) return
setAnalysisProgress({ total: 0, completed: 0, currentMove: null })
const startingFen =
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
const gameTree = new GameTree(startingFen)
const pgn = currentDrill.variation
? currentDrill.variation.pgn
: currentDrill.opening.pgn
const endNode = parsePgnToTree(pgn, gameTree)
const drillGame: OpeningDrillGame = {
id: currentDrill.id,
selection: currentDrill,
moves: [],
tree: gameTree,
currentFen: endNode?.fen || startingFen,
toPlay: endNode
? new Chess(endNode.fen).turn() === 'w'
? 'white'
: 'black'
: 'white',
openingEndNode: endNode,
playerMoveCount: 0,
}
setCurrentDrillGame(drillGame)
setWaitingForMaiaResponse(false)
setContinueAnalyzingMode(false)
}, [currentDrill?.id, allDrillsCompleted])
const gameTree = currentDrillGame?.tree || new GameTree(new Chess().fen())
const controller = useTreeController(
gameTree,
currentDrill?.playerColor || 'white',
)
useEffect(() => {
if (currentDrillGame && currentDrillGame.moves.length === 0) {
if (currentDrillGame.openingEndNode) {
controller.setCurrentNode(currentDrillGame.openingEndNode)
} else if (currentDrillGame.tree) {
controller.setCurrentNode(currentDrillGame.tree.getRoot())
}
}
}, [currentDrillGame?.id])
useEffect(() => {
if (currentDrill?.playerColor) {
controller.setOrientation(currentDrill.playerColor)
}
}, [currentDrill?.playerColor])
const isPlayerTurn = useMemo(() => {
if (!currentDrillGame || !controller.currentNode) return true
const chess = new Chess(controller.currentNode.fen)
const currentTurn = chess.turn() === 'w' ? 'white' : 'black'
return currentTurn === currentDrill?.playerColor
}, [currentDrillGame, controller.currentNode, currentDrill?.playerColor])
const isDrillComplete = useMemo(() => {
if (!currentDrillGame || !currentDrill) return false
return (
currentDrillGame.playerMoveCount >= currentDrill.targetMoveNumber &&
!continueAnalyzingMode
)
}, [currentDrillGame, currentDrill, continueAnalyzingMode])
const isAtOpeningEnd = useMemo(() => {
if (!currentDrillGame || !controller.currentNode) return false
return controller.currentNode === currentDrillGame.openingEndNode
}, [currentDrillGame, controller.currentNode])
const areAllDrillsCompleted = useMemo(() => {
return (
allDrillsCompleted || completedDrills.length >= configuration.drillCount
)
}, [allDrillsCompleted, completedDrills.length, configuration.drillCount])
const availableMoves = useMemo(() => {
if (!controller.currentNode || !isPlayerTurn)
return new Map<string, string[]>()
const moveMap = new Map<string, string[]>()
const chess = new Chess(controller.currentNode.fen)
const legalMoves = chess.moves({ verbose: true })
legalMoves.forEach((move) => {
const { from, to } = move
moveMap.set(from, (moveMap.get(from) ?? []).concat([to]))
})
return moveMap
}, [controller.currentNode, isPlayerTurn])
// Function to evaluate drill performance by extracting analysis from GameTree nodes
const evaluateDrillPerformance = useCallback(
async (drillGame: OpeningDrillGame): Promise<DrillPerformanceData> => {
const { selection } = drillGame
const finalNode = controller.currentNode || drillGame.tree.getRoot()
// Use the centralized minimum depth constant
const moveAnalyses: MoveAnalysis[] = []
const evaluationChart: EvaluationPoint[] = []
const extractNodeAnalysis = (
node: GameNode,
path: GameNode[] = [],
): void => {
const currentPath = [...path, node]
if (node.move && node.san) {
const moveIndex = currentPath.length - 2
const isPlayerMove =
selection.playerColor === 'white'
? moveIndex % 2 === 0
: moveIndex % 2 === 1
const stockfishEval = node.analysis?.stockfish
const maiaEval = node.analysis?.maia?.[currentMaiaModel]
// Check if analysis meets minimum depth requirement
if (stockfishEval && stockfishEval.depth < MIN_STOCKFISH_DEPTH) {
console.warn(
`Stockfish analysis depth ${stockfishEval.depth} is below minimum required depth ${MIN_STOCKFISH_DEPTH} for position ${node.fen}`,
)
}
if (!maiaEval) {
console.warn(`Missing Maia analysis for position ${node.fen}`)
}
const evaluation = stockfishEval?.model_optimal_cp as number
const prevNode = currentPath[currentPath.length - 2]
const prevEvaluation = prevNode?.analysis?.stockfish
?.model_optimal_cp as number
const evaluationLoss = Math.abs(evaluation - prevEvaluation)
const stockfishBestMove = stockfishEval?.model_move
const maiaBestMove = maiaEval?.policy
? Object.keys(maiaEval.policy).sort(
(a, b) => maiaEval.policy[b] - maiaEval.policy[a],
)[0]
: undefined
let classification: 'excellent' | 'inaccuracy' | 'blunder' | 'good' =
'good'
if (isPlayerMove && prevNode && node.move) {
const nodeClassification = GameNode.classifyMove(
prevNode,
node.move,
currentMaiaModel,
)
if (nodeClassification.blunder) {
classification = 'blunder'
} else if (nodeClassification.inaccuracy) {
classification = 'inaccuracy'
} else if (nodeClassification.excellent) {
classification = 'excellent'
} else {
classification = 'good'
}
}
const moveAnalysis: MoveAnalysis = {
move: node.move,
san: node.san,
fen: node.fen,
fenBeforeMove: prevNode?.fen,
moveNumber: Math.ceil((moveIndex + 1) / 2),
isPlayerMove,
evaluation,
classification,
evaluationLoss,
bestMove: stockfishBestMove || maiaBestMove,
bestEvaluation: stockfishEval?.model_optimal_cp,
stockfishBestMove,
maiaBestMove,
}
moveAnalyses.push(moveAnalysis)
const evaluationPoint: EvaluationPoint = {
moveNumber: moveAnalysis.moveNumber,
evaluation,
isPlayerMove,
moveClassification: classification,
}
evaluationChart.push(evaluationPoint)
}
if (node.children.length > 0) {
extractNodeAnalysis(node.children[0], currentPath)
}
}
// Start analysis from the opening end node, not from the game root
// This ensures the evaluation chart only includes post-opening moves that the player actually played
const startingNode = drillGame.openingEndNode || drillGame.tree.getRoot()
extractNodeAnalysis(startingNode)
const playerMoves = moveAnalyses.filter((m) => m.isPlayerMove)
const excellentMoves = playerMoves.filter(
(m) => m.classification === 'excellent',
)
const goodMoves = playerMoves.filter((m) => m.classification === 'good')
const inaccuracyMoves = playerMoves.filter(
(m) => m.classification === 'inaccuracy',
)
const mistakeMoves = playerMoves.filter(
(m) => m.classification === 'mistake',
)
const blunderMoves = playerMoves.filter(
(m) => m.classification === 'blunder',
)
const accuracy =
playerMoves.length > 0
? ((excellentMoves.length + goodMoves.length) / playerMoves.length) *
100
: 100
const averageEvaluationLoss =
playerMoves.length > 0
? playerMoves.reduce((sum, move) => sum + move.evaluationLoss, 0) /
playerMoves.length
: 0
const completedDrill: CompletedDrill = {
selection,
finalNode,
playerMoves: playerMoves.map((m) => m.move),
allMoves: moveAnalyses.map((m) => m.move),
totalMoves: playerMoves.length,
blunders: blunderMoves.map((m) => m.move),
goodMoves: [...excellentMoves, ...goodMoves].map((m) => m.move),
finalEvaluation:
evaluationChart[evaluationChart.length - 1]?.evaluation ?? 0,
completedAt: new Date(),
moveAnalyses,
accuracyPercentage: accuracy,
averageEvaluationLoss,
}
const feedback: string[] = []
if (accuracy >= 90) {
feedback.push('Excellent performance! You played very accurately.')
} else if (accuracy >= 70) {
feedback.push('Good job! Most of your moves were strong.')
} else {
feedback.push('This opening needs more practice.')
}
if (blunderMoves.length > 0) {
feedback.push(
`Watch out for ${blunderMoves.length} critical mistake${blunderMoves.length > 1 ? 's' : ''}.`,
)
}
const nodesByFen = new Map<string, GameNode>()
const collectNodes = (node: GameNode): void => {
nodesByFen.set(node.fen, node)
node.children.forEach(collectNodes)
}
collectNodes(drillGame.tree.getRoot())
const ratingDistribution: RatingComparison[] = MAIA_MODELS.map(
(model) => {
const rating = parseInt(model.replace('maia_kdd_', ''))
let totalLogLikelihood = 0
let totalProbability = 0
let validMoves = 0
for (const move of playerMoves) {
const beforeMoveNode = move.fenBeforeMove
? nodesByFen.get(move.fenBeforeMove)
: null
const maiaAnalysis = beforeMoveNode?.analysis?.maia?.[model]
if (maiaAnalysis?.policy && move.move in maiaAnalysis.policy) {
const moveProb = maiaAnalysis.policy[move.move]
totalProbability += moveProb
totalLogLikelihood += Math.log(Math.max(moveProb, 0.001))
validMoves++
}
}
const averageMoveProb =
validMoves > 0 ? totalProbability / validMoves : 0
const logLikelihood =
validMoves > 0 ? totalLogLikelihood / validMoves : -10
const normalizedLikelihood = Math.max(
0,
Math.min(1, (logLikelihood + 8) / 8),
)
return {
rating,
probability: averageMoveProb,
moveMatch: false,
logLikelihood,
likelihoodProbability: normalizedLikelihood,
averageMoveProb,
}
},
)
const bestRating = ratingDistribution.reduce((best, current) =>
current.likelihoodProbability > best.likelihoodProbability
? current
: best,
)
const ratingPrediction: RatingPrediction = {
predictedRating: bestRating.rating,
standardDeviation: 150,
sampleSize: playerMoves.length,
ratingDistribution,
}
return {
drill: completedDrill,
evaluationChart,
accuracy,
blunderCount: blunderMoves.length,
goodMoveCount: goodMoves.length + excellentMoves.length,
inaccuracyCount: inaccuracyMoves.length,
mistakeCount: mistakeMoves.length,
excellentMoveCount: excellentMoves.length,
feedback,
moveAnalyses,
ratingComparison: [],
ratingPrediction,
bestPlayerMoves: playerMoves
.filter((m) => m.classification === 'excellent')
.slice(0, 3),
worstPlayerMoves: [...blunderMoves, ...mistakeMoves].slice(0, 3),
averageEvaluationLoss,
openingKnowledge: Math.max(0, Math.min(100, accuracy)),
}
},
[controller.currentNode],
)
const completeDrill = useCallback(
async (gameToComplete?: OpeningDrillGame) => {
const drillGame = gameToComplete || currentDrillGame
if (!drillGame) return
try {
setIsAnalyzingDrill(true)
setAnalysisProgress({
total: 0,
completed: 0,
currentMove: 'Preparing analysis...',
})
// Submit drill data to backend
try {
await logOpeningDrill({
opening_fen: drillGame.selection.variation
? drillGame.selection.variation.fen
: drillGame.selection.opening.fen,
side_played: drillGame.selection.playerColor,
opponent: drillGame.selection.maiaVersion,
num_moves: drillGame.selection.targetMoveNumber,
moves_played_uci: drillGame.moves,
})
} catch (error) {
console.error('Failed to log drill to backend:', error)
// Continue even if backend submission fails
}
// Ensure all positions in the drill are analyzed to sufficient depth
if (ensureAnalysisCompleteRef.current) {
const drillNodes: GameNode[] = []
let currentNode = drillGame.tree.getRoot()
drillNodes.push(currentNode)
while (currentNode.children.length > 0) {
currentNode = currentNode.children[0]
drillNodes.push(currentNode)
}
await ensureAnalysisCompleteRef.current(drillNodes)
} else {
setAnalysisProgress({
total: 0,
completed: 0,
currentMove: 'Analyzing drill performance...',
})
}
const performanceData = await evaluateDrillPerformance(drillGame)
setCurrentPerformanceData(performanceData)
setCompletedDrills((prev) => {
const existingIndex = prev.findIndex(
(completedDrill) =>
completedDrill.selection.id === drillGame.selection.id,
)
if (existingIndex !== -1) {
const updated = [...prev]
updated[existingIndex] = performanceData.drill
return updated
} else {
return [...prev, performanceData.drill]
}
})
setShowPerformanceModal(true)
} catch (error) {
console.error('Error completing drill analysis:', error)
setShowPerformanceModal(true)
} finally {
setIsAnalyzingDrill(false)
}
},
[currentDrillGame, evaluateDrillPerformance],
)
const moveToNextDrill = useCallback(async () => {
// Submit drill data to backend
if (currentDrillGame) {
try {
await logOpeningDrill({
opening_fen: currentDrillGame.selection.variation
? currentDrillGame.selection.variation.fen
: currentDrillGame.selection.opening.fen,
side_played: currentDrillGame.selection.playerColor,
opponent: currentDrillGame.selection.maiaVersion,
num_moves: currentDrillGame.selection.targetMoveNumber,
moves_played_uci: currentDrillGame.moves,
})
} catch (error) {
console.error('Failed to log drill to backend:', error)
}
}
setShowPerformanceModal(false)
setCurrentPerformanceData(null)
setContinueAnalyzingMode(false)
setAnalysisEnabled(false)
setAnalysisProgress({ total: 0, completed: 0, currentMove: null })
setRemainingDrills((prev) => prev.slice(1))
const nextIndex = currentDrillIndex + 1
if (nextIndex < configuration.drillSequence.length) {
const nextDrill = configuration.drillSequence[nextIndex]
setCurrentDrill(nextDrill)
setCurrentDrillIndex(nextIndex)
} else {
setAllDrillsCompleted(true)
setShowFinalModal(true)
}
}, [currentDrillIndex, configuration.drillSequence])
// Continue analyzing current drill
const continueAnalyzing = useCallback(() => {
setShowPerformanceModal(false)
setAnalysisEnabled(true)
setContinueAnalyzingMode(true)
setWaitingForMaiaResponse(false)
}, [])
// Continue analyzing from final modal - just enable analysis mode
const continueAnalyzingFromFinal = useCallback(() => {
setShowFinalModal(false)
setAnalysisEnabled(true)
setContinueAnalyzingMode(true)
setWaitingForMaiaResponse(false)
}, [])
const showSummary = useCallback(() => {
setShowFinalModal(true)
}, [])
const showPerformance = useCallback(
async (drill?: CompletedDrill | OpeningDrillGame) => {
let performanceData: DrillPerformanceData | null = null
if (drill) {
if ('selection' in drill && 'finalNode' in drill) {
const completedDrill = drill as CompletedDrill
if (
currentPerformanceData &&
currentPerformanceData.drill.selection.id ===
completedDrill.selection.id
) {
performanceData = currentPerformanceData
} else {
try {
setIsAnalyzingDrill(true)
setAnalysisProgress({
total: 0,
completed: 0,
currentMove: 'Preparing analysis...',
})
const drillGame: OpeningDrillGame = {
id: completedDrill.selection.id,
selection: completedDrill.selection,
moves: completedDrill.allMoves || completedDrill.playerMoves,
tree: currentDrillGame?.tree || new GameTree(new Chess().fen()),
currentFen: completedDrill.finalNode?.fen || new Chess().fen(),
toPlay: completedDrill.finalNode
? new Chess(completedDrill.finalNode.fen).turn() === 'w'
? 'white'
: 'black'
: 'white',
openingEndNode: currentDrillGame?.openingEndNode || null,
playerMoveCount: completedDrill.totalMoves,
}
performanceData = await evaluateDrillPerformance(drillGame)
} catch (error) {
console.error('Error analyzing drill performance:', error)
} finally {
setIsAnalyzingDrill(false)
}
}
} else {
// This is an OpeningDrillGame - analyze it directly
const drillGame = drill as OpeningDrillGame
try {
setIsAnalyzingDrill(true)
setAnalysisProgress({
total: 0,
completed: 0,
currentMove: 'Preparing analysis...',
})
performanceData = await evaluateDrillPerformance(drillGame)
} catch (error) {
console.error('Error analyzing drill performance:', error)
} finally {
setIsAnalyzingDrill(false)
}
}
} else if (currentDrillGame) {
// No specific drill provided, analyze current drill
try {
setIsAnalyzingDrill(true)
setAnalysisProgress({
total: 0,
completed: 0,
currentMove: 'Preparing analysis...',
})
performanceData = await evaluateDrillPerformance(currentDrillGame)
} catch (error) {
console.error('Error analyzing current drill performance:', error)
} finally {
setIsAnalyzingDrill(false)
}
}
// Set the performance data and show the modal
if (performanceData) {
setCurrentPerformanceData(performanceData)
}
setShowPerformanceModal(true)
},
[currentDrillGame, currentPerformanceData, evaluateDrillPerformance],
)
// Shows performance modal for current drill
const showCurrentPerformance = useCallback(() => {
showPerformance()
}, [showPerformance])
// Reset drill session for new openings
const resetDrillSession = useCallback(() => {
setAllDrillsCompleted(false)
setRemainingDrills([])
setCompletedDrills([])
setCurrentDrill(null)
setCurrentDrillGame(null)
setCurrentDrillIndex(0)
setAnalysisEnabled(false)
setContinueAnalyzingMode(false)
setShowPerformanceModal(false)
setShowFinalModal(false)
setCurrentPerformanceData(null)
setWaitingForMaiaResponse(false)
analysisCache.current.clear()
setAnalysisProgress({ total: 0, completed: 0, currentMove: null })
}, [])
// Load a specific completed drill for analysis
const loadCompletedDrill = useCallback(
(completedDrill: CompletedDrill) => {
setCurrentDrill(completedDrill.selection)
// Check if this drill is already the current drill and we can reuse the game tree
if (
currentDrillGame &&
currentDrillGame.selection.id === completedDrill.selection.id &&
currentDrillGame.playerMoveCount === completedDrill.totalMoves
) {
setAnalysisEnabled(true)
setContinueAnalyzingMode(true)
setWaitingForMaiaResponse(false)
return
}
// Try to reconstruct the game tree from the finalNode path
const startingFen =
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
const gameTree = new GameTree(startingFen)
const pgn = completedDrill.selection.variation
? completedDrill.selection.variation.pgn
: completedDrill.selection.opening.pgn
const endNode = parsePgnToTree(pgn, gameTree)
let finalNode = endNode
if (
endNode &&
completedDrill.allMoves &&
completedDrill.allMoves.length > 0
) {
let currentNode = endNode
const chess = new Chess(endNode.fen)
for (const moveUci of completedDrill.allMoves) {
try {
const moveObj = chess.move(moveUci, { sloppy: true })
if (moveObj) {
const newNode = gameTree.addMainMove(
currentNode,
chess.fen(),
moveUci,
moveObj.san,
)
if (newNode) {
currentNode = newNode
finalNode = newNode
}
}
} catch (error) {
console.error('Error replaying move:', moveUci, error)
break
}
}
} else if (endNode && completedDrill.playerMoves.length > 0) {
let currentNode = endNode
const chess = new Chess(endNode.fen)
for (const moveUci of completedDrill.playerMoves) {
try {
const moveObj = chess.move(moveUci, { sloppy: true })
if (moveObj) {
const newNode = gameTree.addMainMove(
currentNode,
chess.fen(),
moveUci,
moveObj.san,
)
if (newNode) {
currentNode = newNode
finalNode = newNode
}
}
} catch (error) {
console.error('Error replaying player move:', moveUci, error)
break
}
}
}
const loadedGame: OpeningDrillGame = {
id: completedDrill.selection.id + '-replay',
selection: completedDrill.selection,
moves: completedDrill.allMoves || completedDrill.playerMoves,
tree: gameTree,
currentFen: finalNode?.fen || endNode?.fen || startingFen,
toPlay: finalNode
? new Chess(finalNode.fen).turn() === 'w'
? 'white'
: 'black'
: 'white',
openingEndNode: endNode,
playerMoveCount: completedDrill.totalMoves,
}
setCurrentDrillGame(loadedGame)
setAnalysisEnabled(true)
setContinueAnalyzingMode(true)
const isMaiaTurn = finalNode
? new Chess(finalNode.fen).turn() !==
(completedDrill.selection.playerColor === 'white' ? 'w' : 'b')
: false
setWaitingForMaiaResponse(isMaiaTurn)
setTimeout(() => {
if (finalNode) {
controller.setCurrentNode(finalNode)
}
}, 50)
},
[controller, currentDrillGame],
)
const navigateToDrill = useCallback(
(drillIndex: number) => {
if (drillIndex < 0 || drillIndex >= configuration.drillSequence.length) {
return
}
const targetDrill = configuration.drillSequence[drillIndex]
const completedDrill = completedDrills.find(
(cd) => cd.selection.id === targetDrill.id,
)
if (completedDrill) {
loadCompletedDrill(completedDrill)
setCurrentDrillIndex(drillIndex)
return
}
setCurrentDrill(targetDrill)
setCurrentDrillIndex(drillIndex)
const startingFen =
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
const gameTree = new GameTree(startingFen)
const pgn = targetDrill.variation
? targetDrill.variation.pgn
: targetDrill.opening.pgn
const endNode = parsePgnToTree(pgn, gameTree)
const newGame: OpeningDrillGame = {
id: targetDrill.id,
selection: targetDrill,
moves: [],
tree: gameTree,
currentFen: endNode?.fen || startingFen,
toPlay: endNode
? new Chess(endNode.fen).turn() === 'w'
? 'white'
: 'black'
: 'white',
openingEndNode: endNode,
playerMoveCount: 0,
}
setCurrentDrillGame(newGame)
setAnalysisEnabled(false)
setContinueAnalyzingMode(false)
setWaitingForMaiaResponse(false)
setRemainingDrills(configuration.drillSequence.slice(drillIndex))
},
[configuration.drillSequence, completedDrills, loadCompletedDrill],
)
const overallPerformanceData = useMemo((): OverallPerformanceData => {
if (completedDrills.length === 0) {
return {
totalDrills: configuration.drillCount,
completedDrills: [],
overallAccuracy: 0,
totalBlunders: 0,
totalGoodMoves: 0,
bestPerformance: null,
worstPerformance: null,
averageEvaluation: 0,
}
}
const totalGoodMoves = completedDrills.reduce(
(sum, drill) => sum + drill.goodMoves.length,
0,
)
const totalMoves = completedDrills.reduce(
(sum, drill) => sum + drill.totalMoves,
0,
)
const overallAccuracy =
totalMoves > 0 ? (totalGoodMoves / totalMoves) * 100 : 0
const totalBlunders = completedDrills.reduce(
(sum, drill) => sum + drill.blunders.length,
0,
)
const averageEvaluation =
completedDrills.reduce((sum, drill) => sum + drill.finalEvaluation, 0) /
completedDrills.length
const bestPerformance = completedDrills.reduce((best, drill) => {
const accuracy =
drill.totalMoves > 0
? (drill.goodMoves.length / drill.totalMoves) * 100
: 0
const bestAccuracy =
best && best.totalMoves > 0
? (best.goodMoves.length / best.totalMoves) * 100
: 0
return accuracy > bestAccuracy ? drill : best
}, completedDrills[0])
const worstPerformance = completedDrills.reduce((worst, drill) => {
const accuracy =
drill.totalMoves > 0
? (drill.goodMoves.length / drill.totalMoves) * 100
: 0
const worstAccuracy =
worst && worst.totalMoves > 0
? (worst.goodMoves.length / worst.totalMoves) * 100
: 100
return accuracy < worstAccuracy ? drill : worst
}, completedDrills[0])
return {
totalDrills: configuration.drillCount,