From d7645edea9b9e7ce888769e87d1247293bb2d55d Mon Sep 17 00:00:00 2001 From: ekzyis Date: Thu, 26 Sep 2024 18:36:03 +0200 Subject: [PATCH] Parse algebraic notation as input --- chess/board.go | 6 ++++++ chess/board_test.go | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/chess/board.go b/chess/board.go index 901729a..8ad232e 100644 --- a/chess/board.go +++ b/chess/board.go @@ -7,6 +7,7 @@ import ( "image/png" "log" "os" + "regexp" "strings" "golang.org/x/image/font" @@ -253,6 +254,7 @@ func (b *Board) AlgebraicNotation() string { func (b *Board) Parse(pgn string) error { var ( moves = strings.Split(strings.Trim(pgn, " "), " ") + re = regexp.MustCompile(`[0-9]+\.`) err error ) @@ -261,6 +263,10 @@ func (b *Board) Parse(pgn string) error { if move == "" { continue } + + // parse algebraic notation with numbers + move = re.ReplaceAllString(move, "") + if err = b.Move(move); err != nil { return err } diff --git a/chess/board_test.go b/chess/board_test.go index e2f219c..01af420 100644 --- a/chess/board_test.go +++ b/chess/board_test.go @@ -511,6 +511,24 @@ func TestBoardCastle(t *testing.T) { assertNoPiece(t, b, "e1") } +func TestBoardParseAlgebraicNotation(t *testing.T) { + t.Parallel() + + b := chess.NewBoard() + + assertParse(t, b, "1.d4 d5 2.c4 e6") + + assertPiece(t, b, "d4", chess.Pawn, chess.Light) + assertPiece(t, b, "d5", chess.Pawn, chess.Dark) + assertPiece(t, b, "c4", chess.Pawn, chess.Light) + assertPiece(t, b, "e6", chess.Pawn, chess.Dark) + + assertNoPiece(t, b, "d2") + assertNoPiece(t, b, "d7") + assertNoPiece(t, b, "c2") + assertNoPiece(t, b, "e7") +} + func assertParse(t *testing.T, b *chess.Board, moves string) { assert.NoError(t, b.Parse(moves)) }