refactor: NCS-22 NCS-23 reworked modules and tests (#17)
Build & Test (NowChessSystems) TeamCity build finished

Reviewed-on: #17
This commit was merged in pull request #17.
This commit is contained in:
2026-04-06 09:07:39 +02:00
parent 51ffd7aac9
commit 8f56a82104
98 changed files with 3752 additions and 5940 deletions
+63
View File
@@ -0,0 +1,63 @@
plugins {
id("scala")
id("org.scoverage") version "8.1"
}
group = "de.nowchess"
version = "1.0-SNAPSHOT"
@Suppress("UNCHECKED_CAST")
val versions = rootProject.extra["VERSIONS"] as Map<String, String>
repositories {
mavenCentral()
}
scala {
scalaVersion = versions["SCALA3"]!!
}
scoverage {
scoverageVersion.set(versions["SCOVERAGE"]!!)
}
tasks.withType<ScalaCompile> {
scalaCompileOptions.additionalParameters = listOf("-encoding", "UTF-8")
}
dependencies {
implementation("org.scala-lang:scala3-compiler_3") {
version {
strictly(versions["SCALA3"]!!)
}
}
implementation("org.scala-lang:scala3-library_3") {
version {
strictly(versions["SCALA3"]!!)
}
}
implementation(project(":modules:api"))
implementation(project(":modules:rule"))
testImplementation(platform("org.junit:junit-bom:5.13.4"))
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("org.scalatest:scalatest_3:${versions["SCALATEST"]!!}")
testImplementation("co.helmethair:scalatest-junit-runner:${versions["SCALATEST_JUNIT"]!!}")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test {
useJUnitPlatform {
includeEngines("scalatest")
testLogging {
events("skipped", "failed")
}
}
finalizedBy(tasks.reportScoverage)
}
tasks.reportScoverage {
dependsOn(tasks.test)
}
@@ -0,0 +1,7 @@
package de.nowchess.io
import de.nowchess.api.game.GameContext
trait GameContextExport:
def exportGameContext(context: GameContext): String
@@ -0,0 +1,7 @@
package de.nowchess.io
import de.nowchess.api.game.GameContext
trait GameContextImport:
def importGameContext(input: String): Either[String, GameContext]
@@ -0,0 +1,64 @@
package de.nowchess.io.fen
import de.nowchess.api.board.*
import de.nowchess.api.game.GameContext
import de.nowchess.io.GameContextExport
object FenExporter extends GameContextExport:
/** Convert a Board to FEN piece-placement string (rank 8 to rank 1, separated by '/'). */
def boardToFen(board: Board): String =
Rank.values.reverse
.map(rank => buildRankString(board, rank))
.mkString("/")
/** Build the FEN representation for a single rank. */
private def buildRankString(board: Board, rank: Rank): String =
val rankSquares = File.values.map(file => Square(file, rank))
val rankChars = scala.collection.mutable.ListBuffer[Char]()
var emptyCount = 0
for square <- rankSquares do
board.pieceAt(square) match
case Some(piece) =>
if emptyCount > 0 then
rankChars += emptyCount.toString.charAt(0)
emptyCount = 0
rankChars += pieceToFenChar(piece)
case None =>
emptyCount += 1
if emptyCount > 0 then rankChars += emptyCount.toString.charAt(0)
rankChars.mkString
/** Convert a GameContext to a complete FEN string. */
def gameContextToFen(context: GameContext): String =
val piecePlacement = boardToFen(context.board)
val activeColor = if context.turn == Color.White then "w" else "b"
val castling = castlingString(context.castlingRights)
val enPassant = context.enPassantSquare.map(_.toString).getOrElse("-")
val fullMoveNumber = 1 + (context.moves.length / 2)
s"$piecePlacement $activeColor $castling $enPassant ${context.halfMoveClock} $fullMoveNumber"
def exportGameContext(context: GameContext): String = gameContextToFen(context)
/** Convert castling rights to FEN notation. */
private def castlingString(rights: CastlingRights): String =
val wk = if rights.whiteKingSide then "K" else ""
val wq = if rights.whiteQueenSide then "Q" else ""
val bk = if rights.blackKingSide then "k" else ""
val bq = if rights.blackQueenSide then "q" else ""
val result = s"$wk$wq$bk$bq"
if result.isEmpty then "-" else result
/** Convert a Piece to its FEN character (uppercase = White, lowercase = Black). */
private def pieceToFenChar(piece: Piece): Char =
val base = piece.pieceType match
case PieceType.Pawn => 'p'
case PieceType.Knight => 'n'
case PieceType.Bishop => 'b'
case PieceType.Rook => 'r'
case PieceType.Queen => 'q'
case PieceType.King => 'k'
if piece.color == Color.White then base.toUpper else base
@@ -0,0 +1,111 @@
package de.nowchess.io.fen
import de.nowchess.api.board.*
import de.nowchess.api.game.GameContext
import de.nowchess.io.GameContextImport
object FenParser extends GameContextImport:
/** Parse a complete FEN string into a GameContext.
* Returns Left with error message if the format is invalid. */
def parseFen(fen: String): Either[String, GameContext] =
val parts = fen.trim.split("\\s+")
if parts.length != 6 then
Left(s"Invalid FEN: expected 6 space-separated fields, got ${parts.length}")
else
for
board <- parseBoard(parts(0)).toRight("Invalid FEN: invalid board position")
activeColor <- parseColor(parts(1)).toRight("Invalid FEN: invalid active color (expected 'w' or 'b')")
castlingRights <- parseCastling(parts(2)).toRight("Invalid FEN: invalid castling rights")
enPassant <- parseEnPassant(parts(3)).toRight("Invalid FEN: invalid en passant square")
halfMoveClock <- parts(4).toIntOption.toRight("Invalid FEN: invalid half-move clock (expected integer)")
fullMoveNumber <- parts(5).toIntOption.toRight("Invalid FEN: invalid full move number (expected integer)")
_ <- Either.cond(halfMoveClock >= 0 && fullMoveNumber >= 1, (), "Invalid FEN: invalid move counts")
yield GameContext(
board = board,
turn = activeColor,
castlingRights = castlingRights,
enPassantSquare = enPassant,
halfMoveClock = halfMoveClock,
moves = List.empty
)
def importGameContext(input: String): Either[String, GameContext] =
parseFen(input)
/** Parse active color ("w" or "b"). */
private def parseColor(s: String): Option[Color] =
if s == "w" then Some(Color.White)
else if s == "b" then Some(Color.Black)
else None
/** Parse castling rights string (e.g. "KQkq", "K", "-") into unified castling rights. */
private def parseCastling(s: String): Option[CastlingRights] =
if s == "-" then
Some(CastlingRights.None)
else if s.length <= 4 && s.forall(c => "KQkq".contains(c)) then
Some(CastlingRights(
whiteKingSide = s.contains('K'),
whiteQueenSide = s.contains('Q'),
blackKingSide = s.contains('k'),
blackQueenSide = s.contains('q')
))
else
None
/** Parse en passant target square ("-" for none, or algebraic like "e3"). */
private def parseEnPassant(s: String): Option[Option[Square]] =
if s == "-" then Some(None)
else Square.fromAlgebraic(s).map(Some(_))
/** Parses a FEN piece-placement string (rank 8 to rank 1, separated by '/') into a Board.
* Returns None if the format is invalid. */
def parseBoard(fen: String): Option[Board] =
val rankStrings = fen.split("/", -1)
if rankStrings.length != 8 then None
else
// Parse each rank, collecting all (Square, Piece) pairs or failing on the first error
val parsedRanks: Option[List[List[(Square, Piece)]]] =
rankStrings.zipWithIndex.foldLeft(Option(List.empty[List[(Square, Piece)]])):
case (None, _) => None
case (Some(acc), (rankStr, rankIdx)) =>
val rank = Rank.values(7 - rankIdx) // ranks go 8→1, so reverse
parsePieceRank(rankStr, rank).map(squares => acc :+ squares)
parsedRanks.map(ranks => Board(ranks.flatten.toMap))
/** Parse a single rank string (e.g. "rnbqkbnr" or "p3p3") into a list of (Square, Piece) pairs.
* Returns None if the rank string contains invalid characters or the wrong number of files. */
private def parsePieceRank(rankStr: String, rank: Rank): Option[List[(Square, Piece)]] =
var fileIdx = 0
val squares = scala.collection.mutable.ListBuffer[(Square, Piece)]()
var failed = false
for c <- rankStr if !failed do
if fileIdx > 7 then
failed = true
else if c.isDigit then
fileIdx += c.asDigit
else
charToPiece(c) match
case None => failed = true
case Some(piece) =>
val file = File.values(fileIdx)
squares += (Square(file, rank) -> piece)
fileIdx += 1
if failed || fileIdx != 8 then None
else Some(squares.toList)
/** Convert a FEN piece character to a Piece. Uppercase = White, lowercase = Black. */
private def charToPiece(c: Char): Option[Piece] =
val color = if Character.isUpperCase(c) then Color.White else Color.Black
val pieceTypeOpt = c.toLower match
case 'p' => Some(PieceType.Pawn)
case 'n' => Some(PieceType.Knight)
case 'b' => Some(PieceType.Bishop)
case 'r' => Some(PieceType.Rook)
case 'q' => Some(PieceType.Queen)
case 'k' => Some(PieceType.King)
case _ => None
pieceTypeOpt.map(pt => Piece(color, pt))
@@ -0,0 +1,80 @@
package de.nowchess.io.pgn
import de.nowchess.api.board.*
import de.nowchess.api.move.{Move, MoveType, PromotionPiece}
import de.nowchess.api.game.GameContext
import de.nowchess.io.GameContextExport
import de.nowchess.rules.sets.DefaultRules
object PgnExporter extends GameContextExport:
/** Export a GameContext to PGN format. */
def exportGameContext(context: GameContext): String =
val headers = Map(
"Event" -> "?",
"White" -> "?",
"Black" -> "?",
"Result" -> "*"
)
exportGame(headers, context.moves)
/** Export a game with headers and moves to PGN format. */
def exportGame(headers: Map[String, String], moves: List[Move]): String =
val headerLines = headers.map { case (key, value) =>
s"""[$key "$value"]"""
}.mkString("\n")
val moveText = if moves.isEmpty then ""
else
var ctx = GameContext.initial
val sanMoves = moves.map { move =>
val algebraic = moveToAlgebraic(move, ctx.board)
ctx = DefaultRules.applyMove(ctx, move)
algebraic
}
val groupedMoves = sanMoves.zipWithIndex.groupBy(_._2 / 2)
val moveLines = for (moveNumber, movePairs) <- groupedMoves.toList.sortBy(_._1) yield
val moveNum = moveNumber + 1
val whiteMoveStr = movePairs.find(_._2 % 2 == 0).map(_._1).getOrElse("")
val blackMoveStr = movePairs.find(_._2 % 2 == 1).map(_._1).getOrElse("")
if blackMoveStr.isEmpty then s"$moveNum. $whiteMoveStr"
else s"$moveNum. $whiteMoveStr $blackMoveStr"
val termination = headers.getOrElse("Result", "*")
moveLines.mkString(" ") + s" $termination"
if headerLines.isEmpty then moveText
else if moveText.isEmpty then headerLines
else s"$headerLines\n\n$moveText"
/** Convert a Move to Standard Algebraic Notation using the board state before the move. */
private def moveToAlgebraic(move: Move, boardBefore: Board): String =
move.moveType match
case MoveType.CastleKingside => "O-O"
case MoveType.CastleQueenside => "O-O-O"
case MoveType.EnPassant => s"${move.from.file.toString.toLowerCase}x${move.to}"
case MoveType.Promotion(pp) =>
val promSuffix = pp match
case PromotionPiece.Queen => "=Q"
case PromotionPiece.Rook => "=R"
case PromotionPiece.Bishop => "=B"
case PromotionPiece.Knight => "=N"
val isCapture = boardBefore.pieceAt(move.to).isDefined
if isCapture then s"${move.from.file.toString.toLowerCase}x${move.to}$promSuffix"
else s"${move.to}$promSuffix"
case MoveType.Normal(isCapture) =>
val dest = move.to.toString
val capStr = if isCapture then "x" else ""
boardBefore.pieceAt(move.from).map(_.pieceType).getOrElse(PieceType.Pawn) match
case PieceType.Pawn =>
if isCapture then s"${move.from.file.toString.toLowerCase}x$dest"
else dest
case PieceType.Knight => s"N$capStr$dest"
case PieceType.Bishop => s"B$capStr$dest"
case PieceType.Rook => s"R$capStr$dest"
case PieceType.Queen => s"Q$capStr$dest"
case PieceType.King => s"K$capStr$dest"
@@ -0,0 +1,184 @@
package de.nowchess.io.pgn
import de.nowchess.api.board.*
import de.nowchess.api.move.{Move, MoveType, PromotionPiece}
import de.nowchess.api.game.GameContext
import de.nowchess.io.GameContextImport
import de.nowchess.rules.sets.DefaultRules
/** A parsed PGN game containing headers and the resolved move list. */
case class PgnGame(
headers: Map[String, String],
moves: List[Move]
)
object PgnParser extends GameContextImport:
/** Strictly validate a PGN text.
* Returns Right(PgnGame) if every move token is a legal move in the evolving position.
* Returns Left(error message) on the first illegal or impossible move, or any unrecognised token. */
def validatePgn(pgn: String): Either[String, PgnGame] =
val lines = pgn.split("\n").map(_.trim)
val (headerLines, rest) = lines.span(_.startsWith("["))
val headers = parseHeaders(headerLines)
val moveText = rest.mkString(" ")
validateMovesText(moveText).map(moves => PgnGame(headers, moves))
/** Import a PGN text into a GameContext by validating and replaying all moves.
* Returns Right(GameContext) with all moves applied and .moves populated.
* Returns Left(error message) if validation fails or move replay encounters an issue. */
def importGameContext(input: String): Either[String, GameContext] =
validatePgn(input).flatMap { game =>
Right(game.moves.foldLeft(GameContext.initial)(DefaultRules.applyMove))
}
/** Parse a complete PGN text into a PgnGame with headers and moves.
* Always succeeds (returns Some); malformed tokens are silently skipped. */
def parsePgn(pgn: String): Option[PgnGame] =
val lines = pgn.split("\n").map(_.trim)
val (headerLines, rest) = lines.span(_.startsWith("["))
val headers = parseHeaders(headerLines)
val moveText = rest.mkString(" ")
val moves = parseMovesText(moveText)
Some(PgnGame(headers, moves))
/** Parse PGN header lines of the form [Key "Value"]. */
private def parseHeaders(lines: Array[String]): Map[String, String] =
val pattern = """^\[(\w+)\s+"([^"]*)"\s*]$""".r
lines.flatMap(line => pattern.findFirstMatchIn(line).map(m => m.group(1) -> m.group(2))).toMap
/** Parse the move-text section (e.g. "1. e4 e5 2. Nf3") into resolved Moves. */
private def parseMovesText(moveText: String): List[Move] =
val tokens = moveText.split("\\s+").filter(_.nonEmpty)
val (_, _, moves) = tokens.foldLeft(
(GameContext.initial, Color.White, List.empty[Move])
):
case (state @ (ctx, color, acc), token) =>
if isMoveNumberOrResult(token) then state
else
parseAlgebraicMove(token, ctx, color) match
case None => state
case Some(move) =>
val nextCtx = DefaultRules.applyMove(ctx, move)
(nextCtx, color.opposite, acc :+ move)
moves
/** True for move-number tokens ("1.", "12.") and PGN result tokens. */
private def isMoveNumberOrResult(token: String): Boolean =
token.matches("""\d+\.""") ||
token == "*" ||
token == "1-0" ||
token == "0-1" ||
token == "1/2-1/2"
/** Parse a single algebraic notation token into a Move, given the current game context. */
def parseAlgebraicMove(notation: String, ctx: GameContext, color: Color): Option[Move] =
notation match
case "O-O" | "O-O+" | "O-O#" =>
val rank = if color == Color.White then Rank.R1 else Rank.R8
val move = Move(Square(File.E, rank), Square(File.G, rank), MoveType.CastleKingside)
Option.when(DefaultRules.legalMoves(ctx, Square(File.E, rank)).contains(move))(move)
case "O-O-O" | "O-O-O+" | "O-O-O#" =>
val rank = if color == Color.White then Rank.R1 else Rank.R8
val move = Move(Square(File.E, rank), Square(File.C, rank), MoveType.CastleQueenside)
Option.when(DefaultRules.legalMoves(ctx, Square(File.E, rank)).contains(move))(move)
case _ =>
parseRegularMove(notation, ctx, color)
/** Parse regular algebraic notation (pawn moves, piece moves, captures, disambiguation). */
private def parseRegularMove(notation: String, ctx: GameContext, color: Color): Option[Move] =
val clean = notation
.replace("+", "")
.replace("#", "")
.replace("x", "")
.replaceAll("=[NBRQ]$", "")
if clean.length < 2 then None
else
val destStr = clean.takeRight(2)
Square.fromAlgebraic(destStr).flatMap: toSquare =>
val disambig = clean.dropRight(2)
val requiredPieceType: Option[PieceType] =
if disambig.nonEmpty && disambig.head.isUpper then charToPieceType(disambig.head)
else if clean.head.isUpper then charToPieceType(clean.head)
else Some(PieceType.Pawn)
val hint =
if disambig.nonEmpty && disambig.head.isUpper then disambig.tail
else disambig
val promotion = extractPromotion(notation)
// Get all legal moves for this color that reach toSquare
val allLegal = DefaultRules.allLegalMoves(ctx)
val candidates = allLegal.filter { move =>
move.to == toSquare &&
ctx.board.pieceAt(move.from).exists(p =>
p.color == color &&
requiredPieceType.forall(_ == p.pieceType)
) &&
(hint.isEmpty || matchesHint(move.from, hint)) &&
promotionMatches(move, promotion)
}
candidates.headOption
/** True if `sq` matches a disambiguation hint (file letter, rank digit, or both). */
private def matchesHint(sq: Square, hint: String): Boolean =
hint.forall(c =>
if c >= 'a' && c <= 'h' then sq.file.toString.equalsIgnoreCase(c.toString)
else if c >= '1' && c <= '8' then sq.rank.ordinal == (c - '1')
else true
)
private def promotionMatches(move: Move, promotion: Option[PromotionPiece]): Boolean =
promotion match
case None => move.moveType match
case MoveType.Normal(_) | MoveType.EnPassant | MoveType.CastleKingside | MoveType.CastleQueenside => true
case _ => false
case Some(pp) => move.moveType == MoveType.Promotion(pp)
/** Extract a promotion piece from a notation string containing =Q/=R/=B/=N. */
private[pgn] def extractPromotion(notation: String): Option[PromotionPiece] =
val promotionPattern = """=([A-Z])""".r
promotionPattern.findFirstMatchIn(notation).flatMap { m =>
m.group(1) match
case "Q" => Some(PromotionPiece.Queen)
case "R" => Some(PromotionPiece.Rook)
case "B" => Some(PromotionPiece.Bishop)
case "N" => Some(PromotionPiece.Knight)
case _ => None
}
/** Convert a piece-letter character to a PieceType. */
private def charToPieceType(c: Char): Option[PieceType] =
c match
case 'N' => Some(PieceType.Knight)
case 'B' => Some(PieceType.Bishop)
case 'R' => Some(PieceType.Rook)
case 'Q' => Some(PieceType.Queen)
case 'K' => Some(PieceType.King)
case _ => None
// ── Strict validation helpers ─────────────────────────────────────────────
/** Walk all move tokens, failing immediately on any unresolvable or illegal move. */
private def validateMovesText(moveText: String): Either[String, List[Move]] =
val tokens = moveText.split("\\s+").filter(_.nonEmpty)
tokens.foldLeft(Right((GameContext.initial, Color.White, List.empty[Move])): Either[String, (GameContext, Color, List[Move])]) {
case (acc, token) =>
acc.flatMap { case (ctx, color, moves) =>
if isMoveNumberOrResult(token) then Right((ctx, color, moves))
else
parseAlgebraicMove(token, ctx, color) match
case None => Left(s"Illegal or impossible move: '$token'")
case Some(move) =>
val nextCtx = DefaultRules.applyMove(ctx, move)
Right((nextCtx, color.opposite, moves :+ move))
}
}.map(_._3)
@@ -0,0 +1,104 @@
package de.nowchess.io.fen
import de.nowchess.api.board.*
import de.nowchess.api.game.GameContext
import de.nowchess.api.move.Move
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
class FenExporterTest extends AnyFunSuite with Matchers:
private def context(
piecePlacement: String,
turn: Color,
castlingRights: CastlingRights,
enPassantSquare: Option[Square],
halfMoveClock: Int,
moveCount: Int
): GameContext =
val board = FenParser.parseBoard(piecePlacement).getOrElse(
fail(s"Invalid test board FEN: $piecePlacement")
)
val dummyMove = Move(Square(File.A, Rank.R2), Square(File.A, Rank.R3))
GameContext(
board = board,
turn = turn,
castlingRights = castlingRights,
enPassantSquare = enPassantSquare,
halfMoveClock = halfMoveClock,
moves = List.fill(moveCount)(dummyMove)
)
test("exportGameContextToFen handles initial and typical developed position"):
FenExporter.gameContextToFen(GameContext.initial) shouldBe
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
val gameContext = context(
piecePlacement = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR",
turn = Color.Black,
castlingRights = CastlingRights.All,
enPassantSquare = Some(Square(File.E, Rank.R3)),
halfMoveClock = 0,
moveCount = 0
)
FenExporter.gameContextToFen(gameContext) shouldBe
"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1"
test("export handles castling rights variants and en-passant with counters"):
val noCastling = context(
piecePlacement = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",
turn = Color.White,
castlingRights = CastlingRights.None,
enPassantSquare = None,
halfMoveClock = 0,
moveCount = 0
)
FenExporter.gameContextToFen(noCastling) shouldBe
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1"
val partialCastling = context(
piecePlacement = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",
turn = Color.White,
castlingRights = CastlingRights(
whiteKingSide = true,
whiteQueenSide = false,
blackKingSide = false,
blackQueenSide = true
),
enPassantSquare = None,
halfMoveClock = 5,
moveCount = 4
)
FenExporter.gameContextToFen(partialCastling) shouldBe
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w Kq - 5 3"
val withEnPassant = context(
piecePlacement = "rnbqkbnr/pp1ppppp/8/2pP4/8/8/PPPP1PPP/RNBQKBNR",
turn = Color.White,
castlingRights = CastlingRights.All,
enPassantSquare = Some(Square(File.C, Rank.R6)),
halfMoveClock = 2,
moveCount = 4
)
FenExporter.gameContextToFen(withEnPassant) shouldBe
"rnbqkbnr/pp1ppppp/8/2pP4/8/8/PPPP1PPP/RNBQKBNR w KQkq c6 2 3"
test("halfMoveClock round-trips through FEN export and import"):
val gameContext = GameContext(
board = Board.initial,
turn = Color.White,
castlingRights = CastlingRights.All,
enPassantSquare = None,
halfMoveClock = 42,
moves = List.empty
)
val fen = FenExporter.gameContextToFen(gameContext)
FenParser.parseFen(fen) match
case Right(ctx) => ctx.halfMoveClock shouldBe 42
case Left(err) => fail(s"FEN parsing failed: $err")
test("exportGameContext forwards to gameContextToFen"):
val ctx = GameContext.initial
FenExporter.exportGameContext(ctx) shouldBe FenExporter.gameContextToFen(ctx)
@@ -0,0 +1,55 @@
package de.nowchess.io.fen
import de.nowchess.api.board.*
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
class FenParserTest extends AnyFunSuite with Matchers:
test("parseBoard parses canonical positions and supports round-trip"):
val initial = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"
val empty = "8/8/8/8/8/8/8/8"
val partial = "8/8/4k3/8/4K3/8/8/8"
FenParser.parseBoard(initial).map(_.pieceAt(Square(File.E, Rank.R2))) shouldBe Some(Some(Piece.WhitePawn))
FenParser.parseBoard(initial).map(_.pieceAt(Square(File.E, Rank.R8))) shouldBe Some(Some(Piece.BlackKing))
FenParser.parseBoard(empty).map(_.pieces.size) shouldBe Some(0)
FenParser.parseBoard(partial).map(_.pieceAt(Square(File.E, Rank.R6))) shouldBe Some(Some(Piece.BlackKing))
FenParser.parseBoard(initial).map(FenExporter.boardToFen) shouldBe Some(initial)
FenParser.parseBoard(empty).map(FenExporter.boardToFen) shouldBe Some(empty)
test("parseFen parses full state for common valid inputs"):
FenParser.parseFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").fold(_ => fail(), ctx =>
ctx.turn shouldBe Color.White
ctx.castlingRights.whiteKingSide shouldBe true
ctx.enPassantSquare shouldBe None
ctx.halfMoveClock shouldBe 0
)
FenParser.parseFen("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1").fold(_ => fail(), ctx =>
ctx.turn shouldBe Color.Black
ctx.enPassantSquare shouldBe Some(Square(File.E, Rank.R3))
)
FenParser.parseFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1").fold(_ => fail(), ctx =>
ctx.castlingRights.whiteKingSide shouldBe false
ctx.castlingRights.blackQueenSide shouldBe false
)
test("parseFen rejects invalid color and castling tokens"):
FenParser.parseFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR x KQkq - 0 1").isLeft shouldBe true
FenParser.parseFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w XYZ - 0 1").isLeft shouldBe true
test("importGameContext returns Right for valid and Left for invalid FEN"):
val fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
FenParser.importGameContext(fen).isRight shouldBe true
FenParser.importGameContext("invalid fen string").isLeft shouldBe true
test("parseBoard rejects malformed board shapes and invalid piece symbols"):
FenParser.parseBoard("8/8/8/8/8/8/8") shouldBe None
FenParser.parseBoard("9/8/8/8/8/8/8/8") shouldBe None
FenParser.parseBoard("8p/8/8/8/8/8/8/8") shouldBe None
FenParser.parseBoard("7/8/8/8/8/8/8/8") shouldBe None
FenParser.parseBoard("8/8/8/8/8/8/8/7X") shouldBe None
@@ -0,0 +1,108 @@
package de.nowchess.io.pgn
import de.nowchess.api.board.*
import de.nowchess.api.game.GameContext
import de.nowchess.api.move.{Move, MoveType, PromotionPiece}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
class PgnExporterTest extends AnyFunSuite with Matchers:
test("exportGame renders headers and basic move text"):
val headers = Map("Event" -> "Test", "White" -> "A", "Black" -> "B")
val emptyPgn = PgnExporter.exportGame(headers, List.empty)
emptyPgn.contains("[Event \"Test\"]") shouldBe true
emptyPgn.contains("[White \"A\"]") shouldBe true
emptyPgn.contains("[Black \"B\"]") shouldBe true
val moves = List(Move(Square(File.E, Rank.R2), Square(File.E, Rank.R4), MoveType.Normal()))
PgnExporter.exportGame(headers, moves).contains("1. e4") shouldBe true
test("exportGame renders castling grouping and result markers"):
PgnExporter.exportGame(Map("Event" -> "Test"), List(Move(Square(File.E, Rank.R1), Square(File.G, Rank.R1), MoveType.CastleKingside))) should include("O-O")
PgnExporter.exportGame(Map("Event" -> "Test"), List(Move(Square(File.E, Rank.R1), Square(File.C, Rank.R1), MoveType.CastleQueenside))) should include("O-O-O")
val seq = List(
Move(Square(File.E, Rank.R2), Square(File.E, Rank.R4), MoveType.Normal()),
Move(Square(File.C, Rank.R7), Square(File.C, Rank.R5), MoveType.Normal()),
Move(Square(File.G, Rank.R1), Square(File.F, Rank.R3), MoveType.Normal())
)
val grouped = PgnExporter.exportGame(Map("Result" -> "1-0"), seq)
grouped should include("1. e4 c5")
grouped should include("2. Nf3")
val oneMove = List(Move(Square(File.E, Rank.R2), Square(File.E, Rank.R4), MoveType.Normal()))
PgnExporter.exportGame(Map.empty, oneMove) shouldBe "1. e4 *"
PgnExporter.exportGame(Map("Result" -> "1/2-1/2"), oneMove) should endWith("1/2-1/2")
test("exportGame handles promotion suffixes and normal move formatting"):
List(
PromotionPiece.Queen -> "=Q",
PromotionPiece.Rook -> "=R",
PromotionPiece.Bishop -> "=B",
PromotionPiece.Knight -> "=N"
).foreach { (piece, suffix) =>
val move = Move(Square(File.E, Rank.R7), Square(File.E, Rank.R8), MoveType.Promotion(piece))
PgnExporter.exportGame(Map.empty, List(move)) should include(s"e8$suffix")
}
val normal = PgnExporter.exportGame(Map.empty, List(Move(Square(File.E, Rank.R2), Square(File.E, Rank.R4), MoveType.Normal())))
normal should include("e4")
normal should not include "="
test("exportGameContext preserves moves and default headers"):
val moves = List(
Move(Square(File.E, Rank.R2), Square(File.E, Rank.R4), MoveType.Normal()),
Move(Square(File.E, Rank.R7), Square(File.E, Rank.R5), MoveType.Normal())
)
val withMoves = PgnExporter.exportGameContext(GameContext.initial.copy(moves = moves))
withMoves.contains("e4") shouldBe true
withMoves.contains("e5") shouldBe true
val empty = PgnExporter.exportGameContext(GameContext.initial)
empty.contains("[Event") shouldBe true
empty.contains("*") shouldBe true
private def sq(alg: String): Square =
Square.fromAlgebraic(alg).getOrElse(fail(s"Invalid square in test: $alg"))
test("exportGame emits notation for all normal piece types and captures"):
val moves = List(
Move(sq("e2"), sq("e4")),
Move(sq("a7"), sq("a6")),
Move(sq("g1"), sq("f3")),
Move(sq("b7"), sq("b6")),
Move(sq("f1"), sq("b5"), MoveType.Normal(true)),
Move(sq("g8"), sq("f6")),
Move(sq("a1"), sq("a8"), MoveType.Normal(true)),
Move(sq("c7"), sq("c6")),
Move(sq("d1"), sq("d7"), MoveType.Normal(true)),
Move(sq("d8"), sq("d7"), MoveType.Normal(true)),
Move(sq("e1"), sq("e2"), MoveType.Normal(true))
)
val pgn = PgnExporter.exportGame(Map("Result" -> "*"), moves)
pgn should include("e4")
pgn should include("Nf3")
pgn should include("Bxb5")
pgn should include("Rxa8")
pgn should include("Qxd7")
pgn should include("Kxe2")
test("exportGame emits en-passant and promotion capture notation"):
val enPassant = Move(sq("e2"), sq("d3"), MoveType.EnPassant)
val promotionCapture = Move(sq("e7"), sq("f8"), MoveType.Promotion(PromotionPiece.Queen))
val pawnCapture = Move(sq("e2"), sq("d3"), MoveType.Normal(isCapture = true))
val promotionQuietSetup = Move(sq("e8"), sq("e7"))
val promotionQuiet = Move(sq("e2"), sq("e8"), MoveType.Promotion(PromotionPiece.Queen))
val pgn = PgnExporter.exportGame(Map.empty, List(enPassant, promotionCapture))
val pawnCapturePgn = PgnExporter.exportGame(Map.empty, List(pawnCapture))
val quietPromotionPgn = PgnExporter.exportGame(Map.empty, List(promotionQuietSetup, promotionQuiet))
pgn should include("exd3")
pgn should include("exf8=Q")
pawnCapturePgn should include("exd3")
quietPromotionPgn should include("e8=Q")
@@ -0,0 +1,131 @@
package de.nowchess.io.pgn
import de.nowchess.api.board.*
import de.nowchess.api.move.{MoveType, PromotionPiece}
import de.nowchess.api.game.GameContext
import de.nowchess.io.fen.FenParser
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
class PgnParserTest extends AnyFunSuite with Matchers:
test("parsePgn handles headers standard sequences captures castling and skipped tokens"):
val headerOnly = """[Event "Test Game"]
[White "Alice"]
[Black "Bob"]
[Result "1-0"]"""
val onlyHeaders = PgnParser.parsePgn(headerOnly)
onlyHeaders.isDefined shouldBe true
onlyHeaders.get.headers("Event") shouldBe "Test Game"
onlyHeaders.get.headers("White") shouldBe "Alice"
val simple = PgnParser.parsePgn("""[Event "Test"]
1. e4 e5 2. Nf3 Nc6""")
simple.map(_.moves.length) shouldBe Some(4)
val capture = PgnParser.parsePgn("""[Event "Test"]
1. Nf3 e5 2. Nxe5""")
capture.map(_.moves.length) shouldBe Some(3)
capture.get.moves(2).to shouldBe Square(File.E, Rank.R5)
val whiteKs = PgnParser.parsePgn("""[Event "Test"]
1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O""").get.moves.last
whiteKs.moveType shouldBe MoveType.CastleKingside
whiteKs.from shouldBe Square(File.E, Rank.R1)
whiteKs.to shouldBe Square(File.G, Rank.R1)
val whiteQs = PgnParser.parsePgn("""[Event "Test"]
1. d4 d5 2. Nc3 Nc6 3. Bf4 Bf5 4. Qd2 Qd7 5. O-O-O""").get.moves.last
whiteQs.moveType shouldBe MoveType.CastleQueenside
whiteQs.from shouldBe Square(File.E, Rank.R1)
whiteQs.to shouldBe Square(File.C, Rank.R1)
val blackKs = PgnParser.parsePgn("""[Event "Test"]
1. e4 e5 2. Nf3 Nf6 3. Bc4 Be7 4. O-O O-O""").get.moves.last
blackKs.moveType shouldBe MoveType.CastleKingside
blackKs.from shouldBe Square(File.E, Rank.R8)
val blackQs = PgnParser.parsePgn("""[Event "Test"]
1. d4 d5 2. Nc3 Nc6 3. Bf4 Bf5 4. Qd2 Qd7 5. O-O-O O-O-O""").get.moves.last
blackQs.moveType shouldBe MoveType.CastleQueenside
blackQs.from shouldBe Square(File.E, Rank.R8)
blackQs.to shouldBe Square(File.C, Rank.R8)
PgnParser.parsePgn("""[Event "Test"]
1. e4 e5 1-0""").map(_.moves.length) shouldBe Some(2)
PgnParser.parsePgn("""[Event "Test"]
1. e4 INVALID e5""").map(_.moves.length) shouldBe Some(2)
test("parseAlgebraicMove resolves pawn knight king and disambiguation cases"):
val board = Board.initial
PgnParser.parseAlgebraicMove("e4", GameContext.initial.withBoard(board), Color.White).get.to shouldBe Square(File.E, Rank.R4)
PgnParser.parseAlgebraicMove("Nf3", GameContext.initial.withBoard(board), Color.White).get.to shouldBe Square(File.F, Rank.R3)
val rookPieces: Map[Square, Piece] = Map(
Square(File.A, Rank.R1) -> Piece(Color.White, PieceType.Rook),
Square(File.H, Rank.R1) -> Piece(Color.White, PieceType.Rook),
Square(File.E, Rank.R1) -> Piece(Color.White, PieceType.King),
Square(File.E, Rank.R8) -> Piece(Color.Black, PieceType.King)
)
val rankPieces: Map[Square, Piece] = Map(
Square(File.A, Rank.R1) -> Piece(Color.White, PieceType.Rook),
Square(File.A, Rank.R4) -> Piece(Color.White, PieceType.Rook),
Square(File.E, Rank.R1) -> Piece(Color.White, PieceType.King),
Square(File.E, Rank.R8) -> Piece(Color.Black, PieceType.King)
)
PgnParser.parseAlgebraicMove("Rad1", GameContext.initial.withBoard(Board(rookPieces)), Color.White).get.from shouldBe Square(File.A, Rank.R1)
PgnParser.parseAlgebraicMove("R1a3", GameContext.initial.withBoard(Board(rankPieces)), Color.White).get.from shouldBe Square(File.A, Rank.R1)
val kingBoard = FenParser.parseBoard("4k3/8/8/8/8/8/8/4K3").get
val king = PgnParser.parseAlgebraicMove("Ke2", GameContext.initial.withBoard(kingBoard), Color.White)
king.isDefined shouldBe true
king.get.from shouldBe Square(File.E, Rank.R1)
king.get.to shouldBe Square(File.E, Rank.R2)
test("parseAlgebraicMove handles all promotion targets"):
val board = FenParser.parseBoard("8/4P3/4k3/8/8/8/8/8").get
PgnParser.parseAlgebraicMove("e7e8=Q", GameContext.initial.withBoard(board), Color.White).get.moveType shouldBe MoveType.Promotion(PromotionPiece.Queen)
PgnParser.parseAlgebraicMove("e7e8=R", GameContext.initial.withBoard(board), Color.White).get.moveType shouldBe MoveType.Promotion(PromotionPiece.Rook)
PgnParser.parseAlgebraicMove("e7e8=B", GameContext.initial.withBoard(board), Color.White).get.moveType shouldBe MoveType.Promotion(PromotionPiece.Bishop)
PgnParser.parseAlgebraicMove("e7e8=N", GameContext.initial.withBoard(board), Color.White).get.moveType shouldBe MoveType.Promotion(PromotionPiece.Knight)
test("importGameContext accepts valid and empty PGN"):
val pgn = """[Event "Test"]
1. e4 e5"""
PgnParser.importGameContext(pgn).isRight shouldBe true
PgnParser.importGameContext("").isRight shouldBe true
test("parser edge cases: uppercase token hint chars and promotion mismatch handling"):
PgnParser.parseAlgebraicMove("E5", GameContext.initial, Color.White) shouldBe None
PgnParser.parseAlgebraicMove("N?f3", GameContext.initial, Color.White).get.to shouldBe Square(File.F, Rank.R3)
PgnParser.extractPromotion("e7e8=X") shouldBe None
val board = FenParser.parseBoard("8/4P3/4k3/8/8/8/8/8").get
PgnParser.parseAlgebraicMove("e8", GameContext.initial.withBoard(board), Color.White) shouldBe None
test("parseAlgebraicMove rejects too-short notation and invalid piece letters"):
val initial = GameContext.initial
PgnParser.parseAlgebraicMove("e", initial, Color.White) shouldBe None
PgnParser.parseAlgebraicMove("Xe5", initial, Color.White) shouldBe None
test("parseAlgebraicMove rejects notation with invalid promotion piece"):
val board = FenParser.parseBoard("8/4P3/4k3/8/8/8/8/8").getOrElse(fail("valid board expected"))
val context = GameContext.initial.withBoard(board)
PgnParser.parseAlgebraicMove("e7e8=X", context, Color.White) shouldBe None
test("parsePgn silently skips unknown tokens"):
val parsed = PgnParser.parsePgn("1. e4 ??? e5")
parsed.map(_.moves.size) shouldBe Some(2)
@@ -0,0 +1,58 @@
package de.nowchess.io.pgn
import de.nowchess.api.board.*
import de.nowchess.api.move.MoveType
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
class PgnValidatorTest extends AnyFunSuite with Matchers:
test("validatePgn accepts valid games including castling and result tokens"):
val pgn =
"""[Event "Test"]
1. e4 e5 2. Nf3 Nc6
"""
val valid = PgnParser.validatePgn(pgn)
valid.isRight shouldBe true
valid.toOption.get.moves.length shouldBe 4
valid.toOption.get.moves.head.from shouldBe Square(File.E, Rank.R2)
val withResult = PgnParser.validatePgn("""[Event "Test"]
1. e4 e5 1-0
""")
withResult.map(_.moves.length) shouldBe Right(2)
val kCastle = PgnParser.validatePgn("""[Event "Test"]
1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O
""")
kCastle.map(_.moves.last.moveType) shouldBe Right(MoveType.CastleKingside)
val qCastle = PgnParser.validatePgn("""[Event "Test"]
1. d4 d5 2. Nc3 Nc6 3. Bf4 Bf5 4. Qd2 Qd7 5. O-O-O
""")
qCastle.map(_.moves.last.moveType) shouldBe Right(MoveType.CastleQueenside)
test("validatePgn rejects impossible illegal and garbage tokens"):
PgnParser.validatePgn("""[Event "Test"]
1. Qd4
""").isLeft shouldBe true
PgnParser.validatePgn("""[Event "Test"]
1. O-O
""").isLeft shouldBe true
PgnParser.validatePgn("""[Event "Test"]
1. e4 GARBAGE e5
""").isLeft shouldBe true
test("validatePgn accepts empty move text and minimal valid header"):
PgnParser.validatePgn("[Event \"Test\"]\n[White \"A\"]\n[Black \"B\"]\n").map(_.moves) shouldBe Right(List.empty)
PgnParser.validatePgn("[Event \"T\"]\n\n1. e4").isRight shouldBe true