Skip to content

Commit

Permalink
dgt json has conflicting clock times, in move list and clock object
Browse files Browse the repository at this point in the history
use the clock object when that happens.
It might be wrong in fewer occasions, but who knows.
  • Loading branch information
ornicar committed Dec 31, 2024
1 parent 28168d7 commit 5114303
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions modules/relay/src/main/DgtJson.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package lila.relay

import play.api.libs.json.*
import scalalib.model.Seconds
import chess.{ Centis, Outcome }
import chess.{ Centis, Outcome, ByColor }
import chess.format.pgn.{ PgnStr, SanStr, Move, Tag, Tags }

private object DgtJson:
Expand Down Expand Up @@ -46,7 +46,11 @@ private object DgtJson:

case class ClockJson(white: Option[Seconds], black: Option[Seconds], time: Long):
def referenceTime: Instant = millisToInstant(time)
def byColor = ByColor(white, black)

/** This is DGT so it's all sorts of wrong. When the clock time is set in both the move `Rxd1 3010` and in
* `clock.white`, then the latter should be used. Most of the time.
*/
case class GameJson(
moves: List[String],
result: Option[String],
Expand All @@ -71,8 +75,10 @@ private object DgtJson:
).flatten
)
def toPgn(roundTags: Tags): PgnStr =
val mergedTags = clockTags ++ mergeRoundTags(roundTags)
val strMoves = moves.map(parseMove).map(_.render).mkString(" ")
val mergedTags = clockTags ++ mergeRoundTags(roundTags)
val parsedMoves = moves.map(parseMove)
val fixedMoves = clock.foldLeft(parsedMoves)(replaceLastMoveTimesWithClock)
val strMoves = fixedMoves.map(_.render).mkString(" ")
PgnStr(s"$mergedTags\n\n$strMoves")

/* - dxe4 63
Expand All @@ -89,7 +95,15 @@ private object DgtJson:
case Array("", emt) => (none, emt.toIntOption)
case Array(clk, emt) => (clk.toIntOption, emt.toIntOption)
case _ => (none, none)
Move(san = SanStr(~parts.headOption), secondsLeft = clk, moveTime = emt)
Move(san = SanStr(~parts.headOption), timeLeft = Seconds.from(clk), moveTime = Seconds.from(emt))

private def replaceLastMoveTimesWithClock(moves: List[Move], clock: ClockJson): List[Move] =
val lastMoveIndex = moves.size - 1
def change(move: Move, sec: Option[Seconds]) = sec.fold(move)(s => move.copy(timeLeft = s.some))
moves.mapWithIndex: (move, i) =>
if i >= lastMoveIndex - 1
then change(move, clock.byColor(Color.fromWhite(i % 2 == 0)))
else move

given Reads[PairingPlayer] = Json.reads
given Reads[RoundJsonPairing] = Json.reads
Expand Down

0 comments on commit 5114303

Please sign in to comment.