-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Game.scala
335 lines (283 loc) · 10.9 KB
/
Game.scala
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
package lila.game
import scalalib.model.Days
import Color.{ Black, White }
import chess.MoveOrDrop.{ color, fold }
import chess.format.pgn.SanStr
import chess.format.{ Fen, Uci }
import chess.opening.{ Opening, OpeningDb }
import chess.variant.{ FromPosition, Standard, Variant }
import chess.{
ByColor,
Castles,
Centis,
CheckCount,
Clock,
Color,
Game as ChessGame,
Mode,
MoveOrDrop,
Outcome,
Ply,
Speed,
Status
}
import lila.db.ByteArray
import lila.core.game.{ Pov, Game, Player, GameRule, Source, PgnImport, ClockHistory }
import lila.rating.PerfType
import lila.game.Blurs.addAtMoveIndex
object GameExt:
def computeMoveTimes(g: Game, color: Color): Option[List[Centis]] = {
for
clk <- g.clock
inc = clk.incrementOf(color)
history <- g.clockHistory
clocks = history(color)
yield Centis(0) :: {
val pairs = clocks.iterator.zip(clocks.iterator.drop(1))
// We need to determine if this color's last clock had inc applied.
// if finished and history.size == playedTurns then game was ended
// by a players move, such as with mate or autodraw. In this case,
// the last move of the game, and the only one without inc, is the
// last entry of the clock history for !turnColor.
//
// On the other hand, if history.size is more than playedTurns,
// then the game ended during a players turn by async event, and
// the last recorded time is in the history for turnColor.
val noLastInc = g.finished && (g.playedTurns >= history.size) == (color != g.turnColor)
pairs
.map: (first, second) =>
{
val d = first - second
if pairs.hasNext || !noLastInc then d + inc else d
}.nonNeg
.toList
}
}.orElse(g.binaryMoveTimes.map: binary =>
// TODO: make movetime.read return List after writes are disabled.
val base = BinaryFormat.moveTime.read(binary, g.playedTurns)
val mts = if color == g.startColor then base else base.drop(1)
everyOther(mts.toList)
)
def analysable(g: Game) =
g.replayable && g.playedTurns > 4 &&
Game.analysableVariants(g.variant) &&
!Game.isOldHorde(g)
extension (g: Game)
def playerIdPov(playerId: GamePlayerId): Option[Pov] = g.playerById(playerId).map(p => Pov(g, p.color))
def withClock(c: Clock) = Progress(g, g.copy(chess = g.chess.copy(clock = Some(c))))
def startClock: Option[Progress] =
g.clock.map: c =>
g.start.withClock(c.start)
def playerCanOfferDraw(color: Color) =
g.started && g.playable &&
g.ply >= 2 &&
!g.player(color).isOfferingDraw &&
!g.opponent(color).isAi &&
!g.playerHasOfferedDrawRecently(color) &&
!g.swissPreventsDraw &&
!g.rulePreventsDraw
def goBerserk(color: Color): Option[Progress] =
g.clock
.ifTrue(g.berserkable && !g.player(color).berserk)
.map: c =>
val newClock = c.goBerserk(color)
Progress(
g,
g.copy(
chess = g.chess.copy(clock = Some(newClock)),
loadClockHistory = _ =>
g.clockHistory.map: history =>
if history(color).isEmpty then history
else history.reset(color).record(color, newClock)
).updatePlayer(color, _.copy(berserk = true))
) ++
List(
Event.ClockInc(color, -c.config.berserkPenalty, newClock),
Event.Clock(newClock), // BC
Event.Berserk(color)
)
def setBlindfold(color: Color, blindfold: Boolean): Progress =
Progress(g, g.updatePlayer(color, _.copy(blindfold = blindfold)), Nil)
def moveTimes: Option[Vector[Centis]] = for
a <- GameExt.computeMoveTimes(g, g.startColor)
b <- GameExt.computeMoveTimes(g, !g.startColor)
yield lila.core.game.interleave(a, b)
// apply a move
def applyMove(
game: ChessGame, // new chess.Position
moveOrDrop: MoveOrDrop,
blur: Boolean = false
): Progress =
def copyPlayer(player: Player) =
if blur && moveOrDrop.color == player.color then
player.copy(blurs = player.blurs.addAtMoveIndex(g.playerMoves(player.color)))
else player
// This must be computed eagerly
// because it depends on the current time
val newClockHistory = for
clk <- game.clock
ch <- g.clockHistory
yield ch.record(g.turnColor, clk)
val updated = g.copy(
players = g.players.map(copyPlayer),
chess = game,
binaryMoveTimes = (!g.sourceIs(_.Import) && g.chess.clock.isEmpty).option {
BinaryFormat.moveTime.write {
g.binaryMoveTimes.so { t =>
BinaryFormat.moveTime.read(t, g.playedTurns)
} :+ Centis.ofLong(nowCentis - g.movedAt.toCentis).nonNeg
}
},
loadClockHistory = _ => newClockHistory,
status = game.situation.status | g.status,
movedAt = nowInstant
)
val state = Event.State(
turns = game.ply,
status = (g.status != updated.status).option(updated.status),
winner = game.situation.winner,
whiteOffersDraw = g.whitePlayer.isOfferingDraw,
blackOffersDraw = g.blackPlayer.isOfferingDraw
)
val clockEvent = updated.chess.clock.map(Event.Clock.apply).orElse {
updated.playableCorrespondenceClock.map(Event.CorrespondenceClock.apply)
}
val events = moveOrDrop.fold(
Event.Move(_, game.situation, state, clockEvent, updated.board.crazyData),
Event.Drop(_, game.situation, state, clockEvent, updated.board.crazyData)
) :: {
(updated.board.variant.threeCheck && game.situation.check.yes).so(List:
Event.CheckCount(
white = updated.history.checkCount.white,
black = updated.history.checkCount.black
)
)
}
Progress(g, updated, events)
end applyMove
def finish(status: Status, winner: Option[Color]): Game =
g.copy(
status = status,
players = winner.fold(g.players): c =>
g.players.update(c, _.copy(isWinner = true.some)),
chess = g.chess.copy(clock = g.clock.map(_.stop)),
loadClockHistory = clk =>
g.clockHistory.map: history =>
// If not already finished, we're ending due to an event
// in the middle of a turn, such as resignation or draw
// acceptance. In these cases, record a final clock time
// for the active color. This ensures the end time in
// clockHistory always matches the final clock time on
// the board.
if !g.finished then history.record(g.turnColor, clk)
else history
)
def abandoned = (g.status <= Status.Started) && (g.movedAt.isBefore(Game.abandonedDate))
def playerBlurPercent(color: Color): Int =
if g.playedTurns > 5
then (g.player(color).blurs.nb * 100) / g.playerMoves(color)
else 0
def drawReason =
if g.variant.isInsufficientMaterial(g.board) then DrawReason.InsufficientMaterial.some
else if g.variant.fiftyMoves(g.history) then DrawReason.FiftyMoves.some
else if g.history.threefoldRepetition then DrawReason.ThreefoldRepetition.some
else if g.drawOffers.normalizedPlies.exists(g.ply <= _) then DrawReason.MutualAgreement.some
else None
def perfType: PerfType = PerfType(g.perfKey)
end extension
private def everyOther[A](l: List[A]): List[A] =
l match
case a :: _ :: tail => a :: everyOther(tail)
case _ => l
end GameExt
object Game:
val syntheticId = GameId("synthetic")
val maxPlies = Ply(600) // unlimited would be a DoS target
val analysableVariants: Set[Variant] = Set(
chess.variant.Standard,
chess.variant.Crazyhouse,
chess.variant.Chess960,
chess.variant.KingOfTheHill,
chess.variant.ThreeCheck,
chess.variant.Antichess,
chess.variant.FromPosition,
chess.variant.Horde,
chess.variant.Atomic,
chess.variant.RacingKings
)
val unanalysableVariants: Set[Variant] = Variant.list.all.toSet -- analysableVariants
val blindModeVariants: Set[Variant] = Set(
chess.variant.Standard,
chess.variant.Chess960,
chess.variant.KingOfTheHill,
chess.variant.ThreeCheck,
chess.variant.FromPosition,
chess.variant.Antichess,
chess.variant.Atomic,
chess.variant.RacingKings,
chess.variant.Horde
)
val hordeWhitePawnsSince = instantOf(2015, 4, 11, 10, 0)
def isOldHorde(game: Game) =
game.variant == chess.variant.Horde &&
game.createdAt.isBefore(Game.hordeWhitePawnsSince)
val abandonedDays = Days(21)
def abandonedDate = nowInstant.minusDays(abandonedDays.value)
def isBoardCompatible(game: Game): Boolean =
game.clock.forall: c =>
lila.core.game.isBoardCompatible(c.config) || {
(game.hasAi || game.sourceIs(_.Friend)) && chess.Speed(c.config) >= Speed.Blitz
}
def isBotCompatible(game: Game): Boolean = {
game.hasAi || game.sourceIs(_.Friend) || game.sourceIs(_.Api)
} && isBotCompatible(game.speed)
def isBotCompatible(speed: Speed): Boolean = speed >= Speed.Bullet
def isBoardOrBotCompatible(game: Game) = isBoardCompatible(game) || isBotCompatible(game)
object BSONFields:
export lila.core.game.BSONFields.*
val whitePlayer = "p0"
val blackPlayer = "p1"
val playerIds = "is"
val binaryPieces = "ps"
val oldPgn = "pg"
val huffmanPgn = "hp"
val status = "s"
val startedAtTurn = "st"
val clock = "c"
val positionHashes = "ph"
val checkCount = "cc"
val castleLastMove = "cl"
val unmovedRooks = "ur"
val daysPerTurn = "cd"
val moveTimes = "mt"
val whiteClockHistory = "cw"
val blackClockHistory = "cb"
val rated = "ra"
val variant = "v"
val crazyData = "chd"
val bookmarks = "bm"
val source = "so"
val tournamentId = "tid"
val swissId = "iid"
val simulId = "sid"
val tvAt = "tv"
val winnerColor = "w"
val initialFen = "if"
val checkAt = "ck"
val drawOffers = "do"
val rules = "rules"
case class CastleLastMove(castles: Castles, lastMove: Option[Uci])
object CastleLastMove:
def init = CastleLastMove(Castles.init, None)
import reactivemongo.api.bson.*
import lila.db.dsl.*
import lila.db.ByteArray.byteArrayHandler
private[game] given castleLastMoveHandler: BSONHandler[CastleLastMove] = tryHandler[CastleLastMove](
{ case bin: BSONBinary =>
byteArrayHandler.readTry(bin).map(BinaryFormat.castleLastMove.read)
},
clmt => byteArrayHandler.writeTry { BinaryFormat.castleLastMove.write(clmt) } get
)
enum DrawReason:
case MutualAgreement, FiftyMoves, ThreefoldRepetition, InsufficientMaterial
private val someEmptyClockHistory = Some(ClockHistory())