Skip to content

Commit

Permalink
Merge pull request #488 from lenguyenthanh/improve-replay-game-move-w…
Browse files Browse the repository at this point in the history
…hile-valid

Traverse sans only once in gameMoveWhileValid
  • Loading branch information
lenguyenthanh authored Oct 14, 2023
2 parents 6941555 + 687091b commit 5c42998
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions src/main/scala/Replay.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,34 @@ 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((init, emptyGames)):
case ((head, games), str) =>
Parser
.sanOnly(str)
.flatMap: san =>
san(head.situation)
.map: move =>
val newGame = move.applyGame(head)
(newGame, (newGame, Uci.WithSan(move.toUci, str)) :: games)
.leftMap(err => (init, games, err.some))
.map(gs => (init, gs._2, 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 (game, gs, err) => (game, gs.reverse, err)

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

0 comments on commit 5c42998

Please sign in to comment.