-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathusePlayController.ts
More file actions
326 lines (281 loc) · 8.47 KB
/
usePlayController.ts
File metadata and controls
326 lines (281 loc) · 8.47 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
import { Color, Check, GameTree, Termination, PlayGameConfig } from 'src/types'
import { AllStats } from '../useStats'
import { PlayedGame } from 'src/types/play'
import { Chess, Piece, SQUARES } from 'chess.ts'
import { useTreeController } from '../useTreeController'
import { useMemo, useState, useCallback, useEffect } from 'react'
const nullFen = new Chess().fen()
const computeTermination = (chess: Chess): Termination | undefined => {
if (!chess.gameOver()) {
return undefined
}
if (chess.inDraw() || chess.inStalemate() || chess.inThreefoldRepetition()) {
return {
result: '1/2-1/2',
winner: 'none',
type: 'rules',
}
}
const turn = chess.turn() == 'w' ? 'white' : 'black'
if (chess.inCheckmate()) {
return {
result: turn == 'white' ? '0-1' : '1-0',
winner: turn == 'white' ? 'black' : 'white',
type: 'rules',
}
}
}
const computeTimeTermination = (
chess: Chess,
playerWhoRanOutOfTime: Color,
): Termination => {
// If there's insufficient material on the board, it's a draw
if (chess.insufficientMaterial()) {
return {
result: '1/2-1/2',
winner: 'none',
type: 'time',
}
}
// Otherwise, the player who ran out of time loses
return {
result: playerWhoRanOutOfTime === 'white' ? '0-1' : '1-0',
winner: playerWhoRanOutOfTime === 'white' ? 'black' : 'white',
type: 'time',
}
}
export const usePlayController = (id: string, config: PlayGameConfig) => {
const [gameTree, setGameTree] = useState<GameTree>(
() => new GameTree(config.startFen || nullFen),
)
const controller = useTreeController(gameTree, config.player)
const [treeVersion, setTreeVersion] = useState<number>(0)
const [resigned, setResigned] = useState<boolean>(false)
const [timeExpired, setTimeExpired] = useState<Color | null>(null)
const [baseMinutes, incrementSeconds] =
config.timeControl == 'unlimited'
? [0, 0]
: config.timeControl.split('+').map(Number)
const initialClockValue = baseMinutes * 60 * 1000
const [whiteClock, setWhiteClock] = useState<number>(initialClockValue)
const [blackClock, setBlackClock] = useState<number>(initialClockValue)
const [lastMoveTime, setLastMoveTime] = useState<number>(0)
const moveList = useMemo(
() => gameTree.toMoveArray(),
[gameTree, treeVersion],
)
const moveTimes = useMemo(
() => gameTree.toTimeArray(),
[gameTree, treeVersion],
)
const game: PlayedGame = useMemo(() => {
const mainLine = gameTree.getMainLine()
const lastNode = mainLine[mainLine.length - 1]
const turn = lastNode.turn
const chess = gameTree.toChess()
const termination = timeExpired
? computeTimeTermination(chess, timeExpired)
: resigned
? ({
result: turn == 'w' ? '0-1' : '1-0',
winner: turn == 'w' ? 'black' : 'white',
type: 'resign',
} as Termination)
: computeTermination(chess)
const moves = []
const rootNode = gameTree.getRoot()
const rootChess = new Chess(rootNode.fen)
moves.push({
board: rootNode.fen,
check: rootChess.inCheck()
? ((rootChess.turn() === 'w' ? 'white' : 'black') as Check)
: false,
})
for (let i = 1; i < mainLine.length; i++) {
const node = mainLine[i]
const nodeChess = new Chess(node.fen)
moves.push({
board: node.fen,
san: node.san || undefined,
lastMove: node.move
? ([node.move.slice(0, 2), node.move.slice(2, 4)] as [string, string])
: undefined,
uci: node.move || undefined,
check: nodeChess.inCheck()
? ((nodeChess.turn() === 'w' ? 'white' : 'black') as Check)
: false,
})
}
return {
id,
termination,
tree: gameTree,
turn: turn == 'b' ? 'black' : 'white',
}
}, [gameTree, treeVersion, resigned, timeExpired, whiteClock, blackClock, id])
const toPlay: Color | null = game.termination ? null : game.turn
const playerActive = toPlay == config.player
const { availableMoves, pieces } = useMemo(() => {
if (!controller.currentNode) return { availableMoves: [], pieces: {} }
const chess = new Chess(controller.currentNode.fen)
const verboseMoves = chess.moves({ verbose: true })
const cantMove = !playerActive || game.termination
const availableMoves = cantMove
? []
: verboseMoves.map((move) => ({
from: move.from,
to: move.to,
promotion: move.promotion,
piece: move.piece,
}))
const pieces: Record<string, Piece> = {}
for (const [square] of Object.entries(SQUARES)) {
const piece = chess.get(square)
if (piece) {
pieces[square] = piece
}
}
return { availableMoves, pieces }
}, [controller.currentNode, playerActive, game.termination, treeVersion])
const updateClock = useCallback(
(overrideTime: number | undefined = undefined): number => {
if (moveList.length < 2) {
return 0 // Clock does not start until first two moves made
}
const now = Date.now()
const elapsed =
overrideTime === undefined ? now - lastMoveTime : overrideTime
if (lastMoveTime > 0) {
if (toPlay == 'white') {
setWhiteClock(
Math.max(whiteClock - elapsed + incrementSeconds * 1000, 0),
)
} else {
setBlackClock(
Math.max(blackClock - elapsed + incrementSeconds * 1000, 0),
)
}
}
setLastMoveTime(now)
return elapsed
},
[
moveList.length,
lastMoveTime,
toPlay,
whiteClock,
blackClock,
incrementSeconds,
],
)
const expireOnTime = useCallback((color: Color) => {
const now = Date.now()
if (color == 'white') {
setWhiteClock(0)
} else {
setBlackClock(0)
}
setLastMoveTime(now)
setTimeExpired(color)
}, [])
useEffect(() => {
if (
!game.termination &&
moveList.length > 1 &&
config.timeControl != 'unlimited' &&
toPlay
) {
const activeColor = toPlay
const timeRemaining = activeColor == 'white' ? whiteClock : blackClock
const timeout = setTimeout(() => {
expireOnTime(activeColor)
}, timeRemaining)
return () => clearTimeout(timeout)
}
}, [
expireOnTime,
game.termination,
blackClock,
moveList.length,
config.timeControl,
toPlay,
whiteClock,
])
const addMoveWithTime = useCallback(
(moveUci: string, moveTime: number) => {
const lastNode = gameTree.getLastMainlineNode()
const board = new Chess(lastNode.fen)
const result = board.move(moveUci, { sloppy: true })
if (result) {
const newNode = lastNode.addChild(
board.fen(),
moveUci,
result.san,
true,
undefined,
moveTime,
)
if (newNode) {
// Tree is modified in place, so we need to trigger re-renders
setTreeVersion((prev) => prev + 1)
controller.setCurrentNode(newNode)
}
}
},
[gameTree, controller.setCurrentNode],
)
const reset = () => {
const newTree = new GameTree(config.startFen || nullFen)
setGameTree(newTree)
setResigned(false)
setTimeExpired(null)
setLastMoveTime(0)
setWhiteClock(initialClockValue)
setBlackClock(initialClockValue)
setTreeVersion((prev) => prev + 1)
}
const makePlayerMove = async (moveUci: string): Promise<void> => {
throw new Error(
'makePlayerMove should be overridden by the consuming component',
)
}
const stats: AllStats = {
lifetime: undefined,
session: { gamesWon: 0, gamesPlayed: 0 },
lastRating: undefined,
rating: 0,
}
return {
game,
gameTree: controller.tree,
currentNode: controller.currentNode,
player: config.player,
playType: config.playType,
maiaVersion: config.maiaVersion,
toPlay,
playerActive,
moveList,
moves: moveList,
moveTimes,
availableMoves,
pieces,
timeControl: config.timeControl,
whiteClock,
blackClock,
lastMoveTime,
stats,
setCurrentNode: controller.setCurrentNode,
goToNode: controller.goToNode,
goToNextNode: controller.goToNextNode,
goToPreviousNode: controller.goToPreviousNode,
goToRootNode: controller.goToRootNode,
plyCount: controller.plyCount,
orientation: controller.orientation,
setOrientation: controller.setOrientation,
addMoveWithTime,
setResigned,
reset,
makePlayerMove,
updateClock,
}
}