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

747 lines
22 KiB
Scala
Raw Normal View History

2013-03-22 10:36:09 -06:00
package lila.game
import scala.concurrent.duration._
2017-03-23 04:51:03 -06:00
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 }
2016-01-15 04:28:54 -07:00
import chess.variant.{ Variant, Crazyhouse }
2017-01-15 05:26:08 -07:00
import chess.{ History => ChessHistory, CheckCount, Castles, Board, MoveOrDrop, Pos, Game => ChessGame, Clock, Status, Color, Mode, PositionHash, UnmovedRooks }
2013-12-05 12:40:11 -07:00
import org.joda.time.DateTime
2013-09-30 15:10:42 -06:00
2017-03-25 14:18:31 -06:00
import lila.common.{ Centis, 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,
2013-12-01 05:01:17 -07:00
binaryPieces: ByteArray,
binaryPgn: ByteArray,
2013-03-22 10:36:09 -06:00
status: Status,
2014-03-05 13:11:55 -07:00
turns: Int, // = ply
startedAtTurn: Int,
2013-03-22 10:36:09 -06:00
clock: Option[Clock],
castleLastMoveTime: CastleLastMoveTime,
2016-11-14 14:51:35 -07:00
unmovedRooks: UnmovedRooks,
2014-11-30 03:22:23 -07:00
daysPerTurn: Option[Int],
2013-12-05 12:40:11 -07:00
positionHashes: PositionHash = Array(),
2014-07-30 13:37:50 -06:00
checkCount: CheckCount = CheckCount(0, 0),
binaryMoveTimes: Option[ByteArray] = None,
clockHistory: Option[ClockHistory] = Option(ClockHistory()),
2013-03-22 10:36:09 -06:00
mode: Mode = Mode.default,
variant: Variant = Variant.default,
2016-01-15 04:28:54 -07:00
crazyData: Option[Crazyhouse.Data] = None,
2013-03-22 10:36:09 -06:00
next: Option[String] = None,
bookmarks: Int = 0,
createdAt: DateTime = DateTime.now,
updatedAt: Option[DateTime] = None,
metadata: Metadata
) {
2013-03-22 10:36:09 -06:00
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)
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(0 == turns % 2)
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
2014-03-05 13:11:55 -07:00
def playedTurns = turns - startedAtTurn
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
def lastMoveDateTime: Option[DateTime] = castleLastMoveTime.lastMoveTime map { lmt =>
createdAt plus (lmt * 100l)
} orElse updatedAt
2014-11-30 03:22:23 -07:00
2015-01-15 08:49:14 -07:00
def updatedAtOrCreatedAt = updatedAt | createdAt
def durationSeconds =
(updatedAtOrCreatedAt.getSeconds - createdAt.getSeconds).toInt atMost {
clock.fold(Int.MaxValue) { c =>
2016-12-15 09:37:51 -07:00
((c.elapsedTime(White) + c.elapsedTime(Black) + c.increment * turns) * 1.1).toInt
}
}
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 = Centis(clk.increment * 100)
history <- clockHistory
clockTimes = history.get(color)
} yield Centis(0) :: {
val pairs = clockTimes.iterator zip clockTimes.iterator.drop(1)
pairs map {
case (first, second) => {
val d = first - second
(pairs.hasNext || !finished || color != turnColor).fold(d + inc, d) atLeast 0
}
} 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]] = {
2017-03-23 04:51:03 -06:00
for {
a <- moveTimes(startColor)
b <- moveTimes(!startColor)
} yield Sequence.interleave(a, b)
}
2017-03-23 04:51:03 -06:00
def bothClockStates = clockHistory.map(_ bothClockStates startColor)
lazy val pgnMoves: PgnMoves = BinaryFormat.pgn read binaryPgn
2014-08-02 09:47:49 -06:00
def openingPgnMoves(nb: Int): PgnMoves = BinaryFormat.pgn.read(binaryPgn, nb)
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
lazy val toChess: ChessGame = {
val pieces = BinaryFormat.piece.read(binaryPieces, variant)
2013-03-22 11:53:13 -06:00
ChessGame(
2016-01-15 04:28:54 -07:00
board = Board(pieces, toChessHistory, variant, crazyData),
2013-03-22 11:53:13 -06:00
player = Color(0 == turns % 2),
clock = clock,
turns = turns,
startedAtTurn = startedAtTurn,
pgnMoves = pgnMoves
)
2013-03-22 11:53:13 -06:00
}
lazy val toChessHistory = ChessHistory(
lastMove = castleLastMoveTime.lastMove map {
2016-10-30 17:21:48 -06:00
case (orig, dest) => Uci.Move(orig, dest)
},
castles = castleLastMoveTime.castles,
2014-07-30 13:37:50 -06:00
positionHashes = positionHashes,
checkCount = checkCount,
unmovedRooks = unmovedRooks
)
2013-03-22 11:53:13 -06:00
def update(
game: ChessGame,
moveOrDrop: MoveOrDrop,
blur: Boolean = false,
lag: Option[FiniteDuration] = None
): Progress = {
2013-03-22 11:53:13 -06:00
val (history, situation) = (game.board.history, game.situation)
2017-01-14 13:07:16 -07:00
def copyPlayer(player: Player) =
if (blur) player.copy(
blurs = math.min(
playerMoves(player.color),
player.blurs + (moveOrDrop.fold(_.color, _.color) == player.color).fold(1, 0)
)
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),
2014-10-22 16:27:26 -06:00
binaryPieces = BinaryFormat.piece write game.board.pieces,
binaryPgn = BinaryFormat.pgn write game.pgnMoves,
2013-03-22 11:53:13 -06:00
turns = game.turns,
2013-12-05 12:40:11 -07:00
positionHashes = history.positionHashes,
2014-07-30 13:37:50 -06:00
checkCount = history.checkCount,
2016-01-15 08:40:23 -07:00
crazyData = situation.board.crazyData,
castleLastMoveTime = CastleLastMoveTime(
castles = history.castles,
lastMove = history.lastMove.map(_.origDest),
lastMoveTime = Some(((nowMillis - createdAt.getMillis) / 100).toInt),
check = situation.checkSquare
),
2016-11-15 01:11:18 -07:00
unmovedRooks = game.board.unmovedRooks,
binaryMoveTimes = (!isPgnImport && !clock.isDefined).option {
2017-03-21 05:00:30 -06:00
BinaryFormat.moveTime.write {
binaryMoveTimes.?? { t =>
BinaryFormat.moveTime.read(t, playedTurns)
} :+ lastMoveDateTime.?? { lmdt =>
Centis(nowCentis - lmdt.getCentis - lag.??(_.toCentis.value)) atLeast 0
2017-03-21 05:00:30 -06:00
}
}
},
clockHistory = for {
clk <- game.clock
history <- clockHistory
} yield history.record(turnColor, clk),
2013-03-22 11:53:13 -06:00
status = situation.status | status,
clock = game.clock
)
2013-03-22 11:53:13 -06:00
2015-06-15 17:56:27 -06:00
val state = Event.State(
color = situation.color,
turns = game.turns,
status = (status != updated.status) option updated.status,
winner = situation.winner,
2015-06-15 17:56:27 -06:00
whiteOffersDraw = whitePlayer.isOfferingDraw,
blackOffersDraw = blackPlayer.isOfferingDraw
)
2014-11-30 03:22:23 -07:00
val clockEvent = updated.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(_, situation, state, clockEvent, updated.crazyData),
Event.Drop(_, situation, state, clockEvent, updated.crazyData)
) ::
2015-06-15 18:09:38 -06:00
{
// abstraction leak, I know.
(updated.variant.threeCheck && situation.check) ?? List(Event.CheckCount(
white = updated.checkCount.white,
black = updated.checkCount.black
))
}.toList
2013-03-22 10:36:09 -06:00
Progress(this, updated, events)
2013-03-22 11:53:13 -06:00
}
def check = castleLastMoveTime.check
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,
2013-12-20 06:13:38 -07:00
mode = Mode(mode.rated && userIds.distinct.size == 2),
2013-03-22 11:53:13 -06:00
updatedAt = DateTime.now.some
))
def correspondenceClock: Option[CorrespondenceClock] = daysPerTurn map { days =>
val increment = days * 24 * 60 * 60
val secondsLeft = lastMoveDateTime.fold(increment) { lmd =>
(lmd.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
2016-12-05 09:53:22 -07:00
def speed = chess.Speed(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
2015-04-02 09:27:29 -06:00
def moretimeable(color: Color) =
playable && nonMandatory && clock.??(_ 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 =>
2015-10-25 20:32:15 -06:00
val newClock = c berserk color
Progress(this, copy(
clock = Some(newClock),
clockHistory = clockHistory.map(history => {
if (history.get(color).isEmpty) history
else history.reset(color).record(color, newClock)
})
).updatePlayer(color, _.goBerserk)) ++
List(Event.Clock(newClock), 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
2013-03-22 11:53:13 -06:00
def finish(status: Status, winner: Option[Color]) = Progress(
this,
copy(
status = status,
2016-08-26 05:53:56 -06:00
whitePlayer = whitePlayer.finish(winner contains White),
blackPlayer = blackPlayer.finish(winner contains Black),
clock = clock map (_.stop),
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
}
2013-03-22 11:53:13 -06:00
),
2015-06-16 03:33:49 -06:00
List(Event.End(winner)) ::: clock.??(c => List(Event.Clock(c)))
2013-03-22 11:53:13 -06:00
)
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 == chess.variant.FromPosition) chess.variant.Standard
else variant
def fromPosition = variant == chess.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
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(playerLag: Color => Int): Boolean =
outoftimeClock(playerLag) || outoftimeCorrespondence
private def outoftimeClock(playerLag: Color => Int): Boolean = clock ?? { c =>
started && playable && (bothPlayersHaveMoved || isSimul) && {
(!c.isRunning && !c.isInit) || c.outoftimeWithGrace(player.color, playerLag(player.color))
}
}
private def outoftimeCorrespondence: Boolean =
playableCorrespondenceClock ?? { _ outoftime player.color }
2014-11-30 06:03:09 -07:00
def isCorrespondence = speed == chess.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
2013-03-22 11:53:13 -06:00
def withClock(c: Clock) = Progress(this, copy(clock = Some(c)))
2013-03-22 10:36:09 -06:00
2015-07-18 16:20:06 -06:00
def estimateClockTotalTime = clock.map(_.estimateTotalTime)
def estimateTotalTime = estimateClockTotalTime orElse
correspondenceClock.map(_.estimateTotalTime) getOrElse 1200
2013-03-22 10:36:09 -06:00
2014-12-02 03:16:25 -07:00
def playerWhoDidNotMove: Option[Player] = playedTurns match {
2014-02-17 02:12:19 -07:00
case 0 => player(White).some
case 1 => player(Black).some
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(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
2014-12-02 03:16:25 -07:00
def playerBlurPercent(color: Color): Int = (playedTurns > 5).fold(
2013-03-22 11:53:13 -06:00
(player(color).blurs * 100) / playerMoves(color),
0
)
2013-03-22 10:36:09 -06:00
def isBeingPlayed = !isPgnImport && !finishedOrAborted
2013-08-01 08:44:38 -06:00
2015-03-31 17:52:46 -06:00
def olderThan(seconds: Int) = (updatedAt | createdAt) isBefore DateTime.now.minusSeconds(seconds)
2013-08-01 08:44:38 -06:00
def unplayed = !bothPlayersHaveMoved && (createdAt isBefore Game.unplayedDate)
2013-03-22 10:36:09 -06:00
def abandoned = (status <= Status.Started) && {
updatedAtOrCreatedAt 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
2014-12-02 03:16:25 -07:00
def resetTurns = 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)
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"
2016-07-29 03:04:16 -06:00
val maxPlayingRealtime = 125 // plus 200 correspondence games
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-19 04:38:40 -06:00
val visualisableVariants: Set[Variant] = Set(
chess.variant.Standard,
chess.variant.Chess960
)
2016-09-19 04:38:40 -06:00
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)
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
2013-05-07 17:44:26 -06:00
def make(
game: ChessGame,
whitePlayer: Player,
blackPlayer: Player,
mode: Mode,
variant: Variant,
source: Source,
pgnImport: Option[PgnImport],
daysPerTurn: Option[Int] = None
): Game = Game(
2013-05-07 17:44:26 -06:00
id = IdGenerator.game,
2013-12-01 02:01:20 -07:00
whitePlayer = whitePlayer,
blackPlayer = blackPlayer,
2016-11-14 14:51:35 -07:00
binaryPieces =
if (game.isStandardInit) BinaryFormat.piece.standard
else BinaryFormat.piece write game.board.pieces,
binaryPgn = ByteArray.empty,
2013-05-07 17:44:26 -06:00
status = Status.Created,
turns = game.turns,
startedAtTurn = game.startedAtTurn,
2013-05-07 17:44:26 -06:00
clock = game.clock,
2015-09-18 06:17:30 -06:00
castleLastMoveTime = CastleLastMoveTime.init.copy(castles = game.board.history.castles),
2016-11-15 01:11:18 -07:00
unmovedRooks = game.board.unmovedRooks,
2014-11-30 03:22:23 -07:00
daysPerTurn = daysPerTurn,
2013-05-07 17:44:26 -06:00
mode = mode,
variant = variant,
crazyData = (variant == Crazyhouse) option Crazyhouse.Data.init,
2013-05-07 17:44:26 -06:00
metadata = Metadata(
2013-08-02 03:09:13 -06:00
source = source.some,
pgnImport = pgnImport,
tournamentId = none,
2015-04-01 14:22:28 -06:00
simulId = none,
2014-08-02 09:47:49 -06:00
tvAt = none,
analysed = false
),
createdAt = DateTime.now
)
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 binaryPgn = "pg"
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"
2013-12-02 16:44:09 -07:00
val castleLastMoveTime = "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 updatedAt = "ua"
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
}
case class CastleLastMoveTime(
castles: Castles,
lastMove: Option[(Pos, Pos)],
lastMoveTime: Option[Int], // tenths of seconds since game creation
check: Option[Pos]
) {
def lastMoveString = lastMove map { case (a, b) => s"$a$b" }
}
object CastleLastMoveTime {
def init = CastleLastMoveTime(Castles.all, None, None, 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
2016-01-15 04:28:54 -07:00
private[game] implicit val castleLastMoveTimeBSONHandler = new BSONHandler[BSONBinary, CastleLastMoveTime] {
2013-12-02 16:44:09 -07:00
def read(bin: BSONBinary) = BinaryFormat.castleLastMoveTime read {
ByteArrayBSONHandler read bin
}
def write(clmt: CastleLastMoveTime) = ByteArrayBSONHandler write {
BinaryFormat.castleLastMoveTime write clmt
}
}
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, _ :+ Centis(clock.remainingCentis(color)))
def reset(color: Color) = update(color, _ => Vector.empty)
2017-02-22 13:07:53 -07:00
def get(color: Color): Vector[Centis] = color.fold(white, black)
2017-03-27 10:13:21 -06:00
def last(color: Color) = get(color).lastOption
// 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)
)
}