Skip to content

Commit

Permalink
Traverse sans only once in gameMoveWhileValid
Browse files Browse the repository at this point in the history
Also add gameMoveWhileValidReverse because in some case we need
games in reverse order, for example: https://github.com/lichess-org/lila/blob/27f1db88d269c17a04ccdbdfa67ed9cda6bd4514/modules/study/src/main/ServerEval.scala#L147
  • Loading branch information
lenguyenthanh committed Oct 7, 2023
1 parent 6941555 commit 28f015e
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions src/main/scala/Replay.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,33 @@ object Replay:
)
)

def gameMoveWhileValid(
def gameMoveWhileValidReverse(
sans: Seq[SanStr],
initialFen: Fen.Epd,
variant: Variant
): (Game, List[(Game, Uci.WithSan)], Option[ErrorStr]) =
val init = makeGame(variant, initialFen.some)
val emptyGames = List.empty[(Game, Uci.WithSan)]
(for
moves <- Parser.moves(sans).leftMap(err => (init, emptyGames, err.some))
games <- moves.value
.zip(sans)
.foldM(emptyGames):
case (games, (san, sanStr)) =>
val game = games.headOption.fold(init)(_._1)
san(game.situation)
.leftMap(err => (init, games, err.some))
.map(m => (m.applyGame(game), Uci.WithSan(m.toUci, sanStr)) :: games)
yield (init, games.reverse, none)).merge
sans
.foldM(emptyGames):
case (games, str) =>
Parser
.sanOnly(str)
.flatMap: san =>
val game: Game = games.headOption.fold(init)(_._1)
san(game.situation)
.map(m => (m.applyGame(game), Uci.WithSan(m.toUci, str)) :: games)
.leftMap(err => (init, games, err.some))
.map(gs => (init, gs, none))
.merge

def gameMoveWhileValid(
sans: Seq[SanStr],
initialFen: Fen.Epd,
variant: Variant
): (Game, List[(Game, Uci.WithSan)], Option[ErrorStr]) =
gameMoveWhileValidReverse(sans, initialFen, variant) match
case (g, gs, err) => (g, gs.reverse, err)

private def computeSituations[M](
sit: Situation,
Expand Down

0 comments on commit 28f015e

Please sign in to comment.