lila/modules/game/src/main/Game.scala

739 lines
22 KiB
Scala
Raw Normal View History

2013-03-22 10:36:09 -06:00
package lila.game
import chess.Color.{ White, Black }
2016-10-30 17:21:48 -06:00
import chess.format.{ Uci, FEN }
2016-09-04 11:07:21 -06:00
import chess.opening.{ FullOpening, FullOpeningDB }
import chess.variant.{ Variant, Standard }
import chess.{ Speed, PieceMap, MoveMetrics, History => ChessHistory, CheckCount, Castles, Board, MoveOrDrop, Pos, Game => ChessGame, Clock, Status, Color, Mode, PositionHash, UnmovedRooks, Centis, Situation }
2013-12-05 12:40:11 -07:00
import org.joda.time.DateTime
2013-09-30 15:10:42 -06:00
import lila.common.Sequence
2013-12-01 05:01:17 -07:00
import lila.db.ByteArray
2014-07-31 16:45:20 -06:00
import lila.rating.PerfType
2013-05-24 11:04:49 -06:00
import lila.user.User
2013-03-22 10:36:09 -06:00
case class Game(
id: String,
whitePlayer: Player,
blackPlayer: Player,
chess: ChessGame,
2018-01-22 13:58:33 -07:00
pgnStorage: PgnStorage,
2013-03-22 10:36:09 -06:00
status: Status,
2014-11-30 03:22:23 -07:00
daysPerTurn: Option[Int],
binaryMoveTimes: Option[ByteArray] = None,
2018-01-23 09:44:36 -07:00
clockHistory: Option[ClockHistory] = Some(ClockHistory()),
2013-03-22 10:36:09 -06:00
mode: Mode = Mode.default,
next: Option[String] = None,
bookmarks: Int = 0,
createdAt: DateTime = DateTime.now,
movedAt: DateTime = DateTime.now,
metadata: Metadata
) {
2013-03-22 10:36:09 -06:00
def situation = chess.situation
def board = chess.situation.board
def history = chess.situation.board.history
def variant = chess.situation.board.variant
def turns = chess.turns
def clock = chess.clock
def pgnMoves = chess.pgnMoves
2013-03-22 11:53:13 -06:00
val players = List(whitePlayer, blackPlayer)
def player(color: Color): Player = color match {
2014-02-17 02:12:19 -07:00
case White => whitePlayer
case Black => blackPlayer
2013-03-22 11:53:13 -06:00
}
def player(playerId: String): Option[Player] =
players find (_.id == playerId)
def player(user: User): Option[Player] =
players find (_ isUser user)
2014-02-17 02:12:19 -07:00
def player(c: Color.type => Color): Player = player(c(Color))
2013-03-22 11:53:13 -06:00
def isPlayerFullId(player: Player, fullId: String): Boolean =
(fullId.size == Game.fullIdSize) && player.id == (fullId drop 8)
def player: Player = player(turnColor)
2016-08-26 05:53:56 -06:00
def playerByUserId(userId: String): Option[Player] = players.find(_.userId contains userId)
def opponentByUserId(userId: String): Option[Player] = playerByUserId(userId) map opponent
2013-03-22 11:53:13 -06:00
def opponent(p: Player): Player = opponent(p.color)
def opponent(c: Color): Player = player(!c)
2016-01-27 21:36:39 -07:00
lazy val firstColor = Color(whitePlayer before blackPlayer)
2013-12-05 14:47:10 -07:00
def firstPlayer = player(firstColor)
def secondPlayer = player(!firstColor)
def turnColor = Color((turns & 1) == 0)
2013-03-22 11:53:13 -06:00
def turnOf(p: Player): Boolean = p == player
def turnOf(c: Color): Boolean = c == turnColor
def turnOf(u: User): Boolean = player(u) ?? turnOf
2013-03-22 11:53:13 -06:00
def playedTurns = turns - chess.startedAtTurn
2014-03-05 13:11:55 -07:00
def flagged = (status == Status.Outoftime).option(turnColor)
2013-03-22 11:53:13 -06:00
def fullIdOf(player: Player): Option[String] =
(players contains player) option s"$id${player.id}"
2013-03-22 11:53:13 -06:00
def fullIdOf(color: Color): String = s"$id${player(color).id}"
2013-03-22 11:53:13 -06:00
2013-12-05 12:40:11 -07:00
def tournamentId = metadata.tournamentId
2015-04-01 14:22:28 -06:00
def simulId = metadata.simulId
2013-03-22 11:53:13 -06:00
def isTournament = tournamentId.isDefined
2015-04-01 14:22:28 -06:00
def isSimul = simulId.isDefined
def isMandatory = isTournament || isSimul
2014-06-09 11:51:02 -06:00
def nonMandatory = !isMandatory
2013-03-22 11:53:13 -06:00
2015-04-03 17:44:02 -06:00
def hasChat = !isTournament && !isSimul && nonAi
2013-03-22 11:53:13 -06:00
// we can't rely on the clock,
// because if moretime was given,
// elapsed time is no longer representing the game duration
def durationSeconds: Option[Int] = (movedAt.getSeconds - createdAt.getSeconds) match {
case seconds if seconds > 60 * 60 * 12 => none // no way it lasted more than 12 hours, come on.
case seconds => seconds.toInt.some
}
2015-12-26 11:14:19 -07:00
2017-03-25 11:36:41 -06:00
def everyOther[A](l: List[A]): List[A] = l match {
case a :: b :: tail => a :: everyOther(tail)
case _ => l
}
2017-03-20 06:22:12 -06:00
def moveTimes(color: Color): Option[List[Centis]] = {
for {
clk <- clock
inc = clk.incrementOf(color)
2017-03-20 06:22:12 -06:00
history <- clockHistory
clocks = history(color)
2017-03-20 06:22:12 -06:00
} yield Centis(0) :: {
val pairs = clocks.iterator zip clocks.iterator.drop(1)
2017-03-31 16:19:56 -06:00
// 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 = finished && (history.size <= playedTurns) == (color != turnColor)
pairs map {
case (first, second) => {
val d = first - second
if (pairs.hasNext || !noLastInc) d + inc else d
} nonNeg
} toList
}
2017-03-20 06:22:12 -06:00
} orElse binaryMoveTimes.map { binary =>
2017-03-25 11:36:41 -06:00
// TODO: make movetime.read return List after writes are disabled.
2017-03-25 10:19:04 -06:00
val base = BinaryFormat.moveTime.read(binary, playedTurns)
val mts = if (color == startColor) base else base.drop(1)
2017-03-25 11:36:41 -06:00
everyOther(mts.toList)
2017-03-20 06:22:12 -06:00
}
def moveTimes: Option[Vector[Centis]] = for {
a <- moveTimes(startColor)
b <- moveTimes(!startColor)
} yield Sequence.interleave(a, b)
2017-03-23 04:51:03 -06:00
def bothClockStates: Option[Vector[Centis]] = clockHistory.map(_ bothClockStates startColor)
def pgnMoves(color: Color): PgnMoves = {
val pivot = if (color == startColor) 0 else 1
pgnMoves.zipWithIndex.collect {
case (e, i) if (i % 2) == pivot => e
}
}
2013-03-22 11:53:13 -06:00
def update(
game: ChessGame,
moveOrDrop: MoveOrDrop,
blur: Boolean = false,
moveMetrics: MoveMetrics = MoveMetrics()
): Progress = {
2017-01-14 13:07:16 -07:00
def copyPlayer(player: Player) =
2017-05-08 05:19:23 -06:00
if (blur && moveOrDrop.fold(_.color, _.color) == player.color)
player.copy(
blurs = player.blurs.add(playerMoves(player.color))
)
2017-01-14 13:07:16 -07:00
else player
2013-03-22 11:53:13 -06:00
val updated = copy(
whitePlayer = copyPlayer(whitePlayer),
blackPlayer = copyPlayer(blackPlayer),
chess = game,
binaryMoveTimes = (!isPgnImport && !chess.clock.isDefined).option {
2017-03-21 05:00:30 -06:00
BinaryFormat.moveTime.write {
binaryMoveTimes.?? { t =>
BinaryFormat.moveTime.read(t, playedTurns)
} :+ Centis(nowCentis - movedAt.getCentis).nonNeg
2017-03-21 05:00:30 -06:00
}
},
clockHistory = for {
clk <- game.clock
ch <- clockHistory
} yield ch.record(turnColor, clk),
status = game.situation.status | status,
movedAt = DateTime.now
)
2013-03-22 11:53:13 -06:00
2015-06-15 17:56:27 -06:00
val state = Event.State(
color = game.situation.color,
turns = game.turns,
status = (status != updated.status) option updated.status,
winner = game.situation.winner,
2015-06-15 17:56:27 -06:00
whiteOffersDraw = whitePlayer.isOfferingDraw,
blackOffersDraw = blackPlayer.isOfferingDraw
)
val clockEvent = updated.chess.clock map Event.Clock.apply orElse {
updated.playableCorrespondenceClock map Event.CorrespondenceClock.apply
2013-12-05 12:40:11 -07:00
}
2013-03-22 10:36:09 -06:00
val events = moveOrDrop.fold(
Event.Move(_, game.situation, state, clockEvent, updated.board.crazyData),
Event.Drop(_, game.situation, state, clockEvent, updated.board.crazyData)
) ::
2015-06-15 18:09:38 -06:00
{
// abstraction leak, I know.
(updated.board.variant.threeCheck && game.situation.check) ?? List(Event.CheckCount(
white = updated.history.checkCount.white,
black = updated.history.checkCount.black
2015-06-15 18:09:38 -06:00
))
}.toList
2013-03-22 10:36:09 -06:00
Progress(this, updated, events)
2013-03-22 11:53:13 -06:00
}
def lastMoveKeys: Option[String] = history.lastMove map {
2018-01-22 15:30:23 -07:00
case Uci.Drop(target, _) => s"$target$target"
case m: Uci.Move => m.keys
}
2014-02-17 02:12:19 -07:00
def updatePlayer(color: Color, f: Player => Player) = color.fold(
2013-10-03 04:18:40 -06:00
copy(whitePlayer = f(whitePlayer)),
copy(blackPlayer = f(blackPlayer))
)
2013-03-22 11:53:13 -06:00
2014-02-17 02:12:19 -07:00
def updatePlayers(f: Player => Player) = copy(
2013-03-22 11:53:13 -06:00
whitePlayer = f(whitePlayer),
blackPlayer = f(blackPlayer)
)
2013-03-22 11:53:13 -06:00
def start = started.fold(this, copy(
status = Status.Started,
mode = Mode(mode.rated && userIds.distinct.size == 2)
2013-03-22 11:53:13 -06:00
))
def correspondenceClock: Option[CorrespondenceClock] = daysPerTurn map { days =>
val increment = days * 24 * 60 * 60
val secondsLeft = (movedAt.getSeconds + increment - nowSeconds).toInt max 0
CorrespondenceClock(
increment = increment,
whiteTime = turnColor.fold(secondsLeft, increment),
blackTime = turnColor.fold(increment, secondsLeft)
)
}
def playableCorrespondenceClock: Option[CorrespondenceClock] =
playable ?? correspondenceClock
2013-03-22 11:53:13 -06:00
def speed = Speed(chess.clock.map(_.config))
2014-07-26 08:06:32 -06:00
def perfKey = PerfPicker.key(this)
def perfType = PerfType(perfKey)
2014-07-31 16:45:20 -06:00
2013-03-22 11:53:13 -06:00
def started = status >= Status.Started
def notStarted = !started
def aborted = status == Status.Aborted
2013-03-22 10:36:09 -06:00
2016-08-07 06:09:08 -06:00
def playedThenAborted = aborted && bothPlayersHaveMoved
2015-09-20 14:04:02 -06:00
def playable = status < Status.Aborted && !imported
2013-03-22 10:36:09 -06:00
def playableEvenImported = status < Status.Aborted
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def playableBy(p: Player): Boolean = playable && turnOf(p)
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def playableBy(c: Color): Boolean = playableBy(player(c))
2013-03-22 10:36:09 -06:00
2013-05-18 13:14:57 -06:00
def playableByAi: Boolean = playable && player.isAi
2015-12-23 04:02:46 -07:00
def mobilePushable = isCorrespondence && playable && nonAi
def alarmable = hasCorrespondenceClock && playable && nonAi
2013-03-22 11:53:13 -06:00
def continuable = status != Status.Mate && status != Status.Stalemate
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def aiLevel: Option[Int] = players find (_.isAi) flatMap (_.aiLevel)
2013-03-22 10:36:09 -06:00
2016-09-05 08:15:24 -06:00
def hasAi: Boolean = players.exists(_.isAi)
2013-03-22 11:53:13 -06:00
def nonAi = !hasAi
2013-03-22 10:36:09 -06:00
2016-09-05 08:15:24 -06:00
def aiPov: Option[Pov] = players.find(_.isAi).map(_.color) map pov
2014-02-17 02:12:19 -07:00
def mapPlayers(f: Player => Player) = copy(
2013-03-22 11:53:13 -06:00
whitePlayer = f(whitePlayer),
blackPlayer = f(blackPlayer)
)
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def playerCanOfferDraw(color: Color) =
started && playable &&
turns >= 2 &&
!player(color).isOfferingDraw &&
!(opponent(color).isAi) &&
!(playerHasOfferedDraw(color))
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def playerHasOfferedDraw(color: Color) =
player(color).lastDrawOffer ?? (_ >= turns - 20)
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def playerCanRematch(color: Color) =
!player(color).isOfferingRematch &&
finishedOrAborted &&
nonMandatory &&
2015-09-12 08:27:35 -06:00
!boosted
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def playerCanProposeTakeback(color: Color) =
2015-04-03 17:44:02 -06:00
started && playable && !isTournament && !isSimul &&
2013-03-22 11:53:13 -06:00
bothPlayersHaveMoved &&
2013-05-24 11:04:49 -06:00
!player(color).isProposingTakeback &&
2013-03-22 11:53:13 -06:00
!opponent(color).isProposingTakeback
2013-03-22 10:36:09 -06:00
2015-09-12 08:27:35 -06:00
def boosted = rated && finished && bothPlayersHaveMoved && playedTurns < 10
def moretimeable(color: Color) = playable && nonMandatory && {
clock.??(_ moretimeable color) || correspondenceClock.??(_ moretimeable color)
}
2013-03-22 10:36:09 -06:00
2014-12-02 03:16:25 -07:00
def abortable = status == Status.Started && playedTurns < 2 && nonMandatory
2013-03-22 10:36:09 -06:00
2016-12-05 09:53:22 -07:00
def berserkable = clock.??(_.config.berserkable) && status == Status.Started && playedTurns < 2
2013-03-22 10:36:09 -06:00
2015-08-18 04:47:18 -06:00
def goBerserk(color: Color) =
clock.ifTrue(berserkable && !player(color).berserk).map { c =>
val newClock = c goBerserk color
Progress(this, copy(
chess = chess.copy(clock = Some(newClock)),
clockHistory = clockHistory.map(history => {
if (history(color).isEmpty) history
else history.reset(color).record(color, newClock)
})
).updatePlayer(color, _.goBerserk)) ++
2017-07-21 16:53:08 -06:00
List(
Event.ClockInc(color, -c.config.berserkPenalty),
Event.Clock(newClock), // BC
Event.Berserk(color)
)
2015-08-18 04:47:18 -06:00
}
2013-03-22 11:53:13 -06:00
def resignable = playable && !abortable
2013-10-09 08:46:00 -06:00
def drawable = playable && !abortable
2013-03-22 10:36:09 -06:00
2017-07-21 16:53:08 -06:00
def finish(status: Status, winner: Option[Color]) = {
val newClock = clock map { _.stop }
Progress(
this,
copy(
status = status,
whitePlayer = whitePlayer.finish(winner contains White),
blackPlayer = blackPlayer.finish(winner contains Black),
chess = chess.copy(clock = newClock),
2017-07-21 16:53:08 -06:00
clockHistory = for {
clk <- clock
history <- clockHistory
} yield {
// 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 (!finished) history.record(turnColor, clk)
else history
}
),
// Events here for BC.
List(Event.End(winner)) ::: newClock.??(c => List(Event.Clock(c)))
)
}
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def rated = mode.rated
2014-05-01 06:08:54 -06:00
def casual = !rated
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def finished = status >= Status.Mate
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def finishedOrAborted = finished || aborted
2013-03-22 10:36:09 -06:00
def accountable = playedTurns >= 2 || isTournament
def replayable = isPgnImport || finished || (aborted && bothPlayersHaveMoved)
2014-02-02 05:07:00 -07:00
2016-09-04 11:07:21 -06:00
def analysable =
replayable && playedTurns > 4 &&
Game.analysableVariants(variant) &&
!Game.isOldHorde(this)
2014-02-27 17:18:22 -07:00
def ratingVariant =
if (isTournament && variant.fromPosition) Standard
else variant
def fromPosition = variant.fromPosition || source.??(Source.Position==)
def imported = source contains Source.Import
2014-02-27 17:18:22 -07:00
2016-12-01 03:59:09 -07:00
def fromPool = source contains Source.Pool
def fromLobby = source contains Source.Lobby
def fromFriend = source contains Source.Friend
2016-12-01 03:59:09 -07:00
2013-03-22 11:53:13 -06:00
def winner = players find (_.wins)
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def loser = winner map opponent
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def winnerColor: Option[Color] = winner map (_.color)
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def winnerUserId: Option[String] = winner flatMap (_.userId)
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def loserUserId: Option[String] = loser flatMap (_.userId)
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def wonBy(c: Color): Option[Boolean] = winnerColor map (_ == c)
2013-03-22 10:36:09 -06:00
2015-07-18 16:20:06 -06:00
def lostBy(c: Color): Option[Boolean] = winnerColor map (_ != c)
2015-07-21 10:05:44 -06:00
def drawn = finished && winner.isEmpty
2015-07-18 16:20:06 -06:00
def outoftime(withGrace: Boolean): Boolean =
if (isCorrespondence) outoftimeCorrespondence else outoftimeClock(withGrace)
private def outoftimeClock(withGrace: Boolean): Boolean = clock ?? { c =>
started && playable && (bothPlayersHaveMoved || isSimul) && {
(!c.isRunning && !c.isInit) || c.outOfTime(turnColor, withGrace)
}
}
private def outoftimeCorrespondence: Boolean =
playableCorrespondenceClock ?? { _ outoftime turnColor }
2014-11-30 06:03:09 -07:00
def isCorrespondence = speed == Speed.Correspondence
2015-10-06 11:46:17 -06:00
def isSwitchable = nonAi && (isCorrespondence || isSimul)
2015-09-22 12:31:31 -06:00
2013-03-22 11:53:13 -06:00
def hasClock = clock.isDefined
2013-03-22 10:36:09 -06:00
2015-01-15 08:49:14 -07:00
def hasCorrespondenceClock = daysPerTurn.isDefined
def isUnlimited = !hasClock && !hasCorrespondenceClock
2013-10-09 07:26:17 -06:00
def isClockRunning = clock ?? (_.isRunning)
2013-03-22 10:36:09 -06:00
def withClock(c: Clock) = Progress(this, copy(chess = chess.copy(clock = Some(c))))
2013-03-22 10:36:09 -06:00
def correspondenceGiveTime = Progress(this, copy(movedAt = DateTime.now))
def estimateClockTotalTime = clock.map(_.estimateTotalSeconds)
2015-07-18 16:20:06 -06:00
def estimateTotalTime = estimateClockTotalTime orElse
correspondenceClock.map(_.estimateTotalTime) getOrElse 1200
2013-03-22 10:36:09 -06:00
def timeForFirstMove: Centis = Centis ofSeconds {
import Speed._
val base = if (isTournament) speed match {
2017-10-26 15:04:15 -06:00
case UltraBullet => 11
case Bullet => 16
case Blitz => 21
2017-11-29 10:58:08 -07:00
case Rapid => 25
case _ => 30
2017-10-26 15:04:15 -06:00
}
else speed match {
case UltraBullet => 15
case Bullet => 20
case Blitz => 25
2017-11-29 10:58:08 -07:00
case Rapid => 30
2017-10-26 15:04:15 -06:00
case _ => 35
}
if (variant.chess960) (base * 2) atMost 90
else base
}
2017-10-22 16:45:53 -06:00
def expirable =
source.exists(Source.expirable.contains) && playable && !bothPlayersHaveMoved && nonAi && hasClock
def timeBeforeExpiration: Option[Centis] = expirable option {
Centis.ofMillis(movedAt.getMillis - nowMillis + timeForFirstMove.millis).nonNeg
}
2014-12-02 03:16:25 -07:00
def playerWhoDidNotMove: Option[Player] = playedTurns match {
case 0 => player(startColor).some
case 1 => player(!startColor).some
2014-02-17 02:12:19 -07:00
case _ => none
2013-03-22 11:53:13 -06:00
}
2013-03-22 10:36:09 -06:00
2014-12-02 03:16:25 -07:00
def onePlayerHasMoved = playedTurns > 0
def bothPlayersHaveMoved = playedTurns > 1
2013-03-22 10:36:09 -06:00
def startColor = Color(chess.startedAtTurn % 2 == 0)
def playerMoves(color: Color): Int =
if (color == startColor) (playedTurns + 1) / 2
else playedTurns / 2
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def playerHasMoved(color: Color) = playerMoves(color) > 0
2013-03-22 10:36:09 -06:00
2017-05-08 05:19:23 -06:00
def playerBlurPercent(color: Color): Int =
if (playedTurns > 5) (player(color).blurs.nb * 100) / playerMoves(color)
else 0
2013-03-22 10:36:09 -06:00
def isBeingPlayed = !isPgnImport && !finishedOrAborted
2013-08-01 08:44:38 -06:00
def olderThan(seconds: Int) = movedAt isBefore DateTime.now.minusSeconds(seconds)
2013-08-01 08:44:38 -06:00
2017-08-02 04:34:58 -06:00
def justCreated = createdAt isAfter DateTime.now.minusSeconds(1)
def unplayed = !bothPlayersHaveMoved && (createdAt isBefore Game.unplayedDate)
2013-03-22 10:36:09 -06:00
def abandoned = (status <= Status.Started) && {
movedAt isBefore hasAi.fold(Game.aiAbandonedDate, Game.abandonedDate)
}
2013-03-22 10:36:09 -06:00
2015-09-16 09:23:52 -06:00
def forecastable = started && playable && isCorrespondence && !hasAi
2015-09-15 12:32:57 -06:00
2013-03-22 11:53:13 -06:00
def hasBookmarks = bookmarks > 0
2013-03-22 10:36:09 -06:00
2014-02-12 12:24:44 -07:00
def showBookmarks = hasBookmarks ?? bookmarks.toString
2013-03-22 10:36:09 -06:00
2013-03-22 11:53:13 -06:00
def userIds = playerMaps(_.userId)
2013-03-22 10:36:09 -06:00
2013-12-17 15:20:18 -07:00
def userRatings = playerMaps(_.rating)
2013-03-22 10:36:09 -06:00
2013-12-17 15:20:18 -07:00
def averageUsersRating = userRatings match {
2014-02-17 02:12:19 -07:00
case a :: b :: Nil => Some((a + b) / 2)
case a :: Nil => Some((a + 1500) / 2)
case _ => None
2013-03-22 11:53:13 -06:00
}
2013-03-22 10:36:09 -06:00
def withTournamentId(id: String) = copy(metadata = metadata.copy(tournamentId = id.some))
2015-04-01 14:22:28 -06:00
def withSimulId(id: String) = copy(metadata = metadata.copy(simulId = id.some))
2013-03-22 10:36:09 -06:00
def withId(newId: String) = copy(id = newId)
2013-03-22 10:36:09 -06:00
2013-12-05 12:40:11 -07:00
def source = metadata.source
2013-03-22 10:36:09 -06:00
2013-12-05 12:40:11 -07:00
def pgnImport = metadata.pgnImport
2013-03-22 11:53:13 -06:00
def isPgnImport = pgnImport.isDefined
2013-03-22 10:36:09 -06:00
def resetTurns = copy(
chess = chess.copy(turns = 0, startedAtTurn = 0)
)
2016-02-25 03:03:09 -07:00
lazy val opening: Option[FullOpening.AtPly] =
if (fromPosition || !Variant.openingSensibleVariants(variant)) none
2016-02-23 22:40:50 -07:00
else FullOpeningDB search pgnMoves
2016-05-13 03:28:35 -06:00
def synthetic = id == Game.syntheticId
2016-02-15 20:29:14 -07:00
2017-01-13 05:52:25 -07:00
def isRecentTv = metadata.tvAt.??(DateTime.now.minusMinutes(30).isBefore)
private def playerMaps[A](f: Player => Option[A]): List[A] = players flatMap { f(_) }
2016-06-02 05:51:18 -06:00
def pov(c: Color) = Pov(this, c)
def whitePov = pov(White)
def blackPov = pov(Black)
def playerPov(p: Player) = pov(p.color)
def loserPov = loser map playerPov
2013-03-22 10:36:09 -06:00
}
object Game {
type ID = String
2016-10-30 17:21:48 -06:00
case class WithInitialFen(game: Game, fen: Option[FEN])
2016-05-13 03:28:35 -06:00
val syntheticId = "synthetic"
val maxPlayingRealtime = 100 // plus 200 correspondence games
2016-07-29 03:04:16 -06:00
val analysableVariants: Set[Variant] = Set(
chess.variant.Standard,
2016-10-31 13:54:42 -06:00
chess.variant.Crazyhouse,
chess.variant.Chess960,
chess.variant.KingOfTheHill,
2015-06-21 13:03:34 -06:00
chess.variant.ThreeCheck,
2016-11-15 05:43:49 -07:00
chess.variant.Antichess,
2016-08-13 09:36:34 -06:00
chess.variant.FromPosition,
chess.variant.Horde,
chess.variant.Atomic,
chess.variant.RacingKings
)
2014-08-13 02:51:15 -06:00
val unanalysableVariants: Set[Variant] = Variant.all.toSet -- analysableVariants
val variantsWhereWhiteIsBetter: Set[Variant] = Set(
chess.variant.ThreeCheck,
chess.variant.Atomic,
2015-03-09 08:22:54 -06:00
chess.variant.Horde,
2015-09-04 14:25:57 -06:00
chess.variant.RacingKings,
chess.variant.Antichess
)
2016-09-04 11:07:21 -06:00
val hordeWhitePawnsSince = new DateTime(2015, 4, 11, 10, 0)
def isOldHorde(game: Game) =
game.variant == chess.variant.Horde &&
game.createdAt.isBefore(Game.hordeWhitePawnsSince)
def allowRated(variant: Variant, clock: Clock.Config) =
variant.standard || clock.estimateTotalTime >= Centis(3000)
2013-03-22 10:36:09 -06:00
val gameIdSize = 8
val playerIdSize = 4
val fullIdSize = 12
val tokenSize = 4
val unplayedHours = 24
def unplayedDate = DateTime.now minusHours unplayedHours
2014-12-03 02:35:06 -07:00
val abandonedDays = 21
def abandonedDate = DateTime.now minusDays abandonedDays
2013-03-22 10:36:09 -06:00
val aiAbandonedHours = 6
def aiAbandonedDate = DateTime.now minusHours aiAbandonedHours
2013-03-22 10:36:09 -06:00
def takeGameId(fullId: String) = fullId take gameIdSize
2013-05-17 18:38:39 -06:00
def takePlayerId(fullId: String) = fullId drop gameIdSize
2013-03-22 10:36:09 -06:00
private[game] val emptyCheckCount = CheckCount(0, 0)
2013-05-07 17:44:26 -06:00
def make(
chess: ChessGame,
2013-05-07 17:44:26 -06:00
whitePlayer: Player,
blackPlayer: Player,
mode: Mode,
source: Source,
pgnImport: Option[PgnImport],
daysPerTurn: Option[Int] = None
): Game = {
var createdAt = DateTime.now
Game(
id = IdGenerator.game,
whitePlayer = whitePlayer,
blackPlayer = blackPlayer,
chess = chess,
pgnStorage = PgnStorage(chess.situation.board.variant, List(whitePlayer.userId, blackPlayer.userId).flatten),
status = Status.Created,
daysPerTurn = daysPerTurn,
mode = mode,
metadata = Metadata(
source = source.some,
pgnImport = pgnImport,
tournamentId = none,
simulId = none,
tvAt = none,
analysed = false
),
createdAt = createdAt,
movedAt = createdAt
)
}
2013-03-22 11:53:13 -06:00
2013-12-03 13:31:31 -07:00
object BSONFields {
2013-12-02 16:44:09 -07:00
val id = "_id"
2013-12-04 17:32:37 -07:00
val whitePlayer = "p0"
val blackPlayer = "p1"
val playerIds = "is"
2013-12-11 01:56:11 -07:00
val playerUids = "us"
val playingUids = "pl"
2013-12-02 16:44:09 -07:00
val binaryPieces = "ps"
val oldPgn = "pg"
val huffmanPgn = "hp"
2013-12-02 16:44:09 -07:00
val status = "s"
val turns = "t"
val startedAtTurn = "st"
2013-12-02 16:44:09 -07:00
val clock = "c"
val positionHashes = "ph"
2014-07-30 13:37:50 -06:00
val checkCount = "cc"
2018-01-22 15:30:23 -07:00
val castleLastMove = "cl"
2016-11-14 14:51:35 -07:00
val unmovedRooks = "ur"
2014-11-30 03:22:23 -07:00
val daysPerTurn = "cd"
val moveTimes = "mt"
2017-02-22 13:07:53 -07:00
val whiteClockHistory = "cw"
val blackClockHistory = "cb"
2013-12-02 16:44:09 -07:00
val rated = "ra"
val analysed = "an"
2013-12-02 16:44:09 -07:00
val variant = "v"
2016-01-15 04:28:54 -07:00
val crazyData = "chd"
2013-12-11 13:35:29 -07:00
val next = "ne"
2013-12-02 16:44:09 -07:00
val bookmarks = "bm"
val createdAt = "ca"
val movedAt = "ua" // ua = updatedAt (bc)
2013-12-05 12:40:11 -07:00
val source = "so"
val pgnImport = "pgni"
val tournamentId = "tid"
2015-04-01 14:22:28 -06:00
val simulId = "sid"
2013-12-05 12:40:11 -07:00
val tvAt = "tv"
val winnerColor = "w"
2013-12-09 12:29:44 -07:00
val winnerId = "wid"
2014-11-30 06:35:18 -07:00
val initialFen = "if"
val checkAt = "ck"
2013-12-04 12:08:31 -07:00
}
2013-03-22 10:36:09 -06:00
}
2018-01-22 15:42:22 -07:00
case class CastleLastMove(castles: Castles, lastMove: Option[Uci])
2018-01-22 15:30:23 -07:00
object CastleLastMove {
2018-01-22 15:42:22 -07:00
def init = CastleLastMove(Castles.all, None)
2013-03-22 10:36:09 -06:00
2013-12-02 16:44:09 -07:00
import reactivemongo.bson._
import lila.db.ByteArray.ByteArrayBSONHandler
2013-03-22 10:36:09 -06:00
2018-01-22 15:30:23 -07:00
private[game] implicit val castleLastMoveBSONHandler = new BSONHandler[BSONBinary, CastleLastMove] {
def read(bin: BSONBinary) = BinaryFormat.castleLastMove read {
2013-12-02 16:44:09 -07:00
ByteArrayBSONHandler read bin
}
2018-01-22 15:30:23 -07:00
def write(clmt: CastleLastMove) = ByteArrayBSONHandler write {
BinaryFormat.castleLastMove write clmt
2013-12-02 16:44:09 -07:00
}
}
2013-03-22 10:36:09 -06:00
}
2017-02-22 13:07:53 -07:00
case class ClockHistory(
white: Vector[Centis] = Vector.empty,
black: Vector[Centis] = Vector.empty
2017-02-22 13:07:53 -07:00
) {
def update(color: Color, f: Vector[Centis] => Vector[Centis]): ClockHistory =
color.fold(copy(white = f(white)), copy(black = f(black)))
def record(color: Color, clock: Clock): ClockHistory =
update(color, _ :+ clock.remainingTime(color))
def reset(color: Color) = update(color, _ => Vector.empty)
2017-02-22 13:07:53 -07:00
def apply(color: Color): Vector[Centis] = color.fold(white, black)
def last(color: Color) = apply(color).lastOption
def size = white.size + black.size
2017-03-27 10:13:21 -06:00
// first state is of the color that moved first.
2017-03-25 14:18:31 -06:00
def bothClockStates(firstMoveBy: Color): Vector[Centis] =
Sequence.interleave(
firstMoveBy.fold(white, black),
firstMoveBy.fold(black, white)
)
}