Parse algebraic notation as input

This commit is contained in:
ekzyis 2024-09-26 18:36:03 +02:00
parent bf481bc452
commit d7645edea9
2 changed files with 24 additions and 0 deletions

View File

@ -7,6 +7,7 @@ import (
"image/png" "image/png"
"log" "log"
"os" "os"
"regexp"
"strings" "strings"
"golang.org/x/image/font" "golang.org/x/image/font"
@ -253,6 +254,7 @@ func (b *Board) AlgebraicNotation() string {
func (b *Board) Parse(pgn string) error { func (b *Board) Parse(pgn string) error {
var ( var (
moves = strings.Split(strings.Trim(pgn, " "), " ") moves = strings.Split(strings.Trim(pgn, " "), " ")
re = regexp.MustCompile(`[0-9]+\.`)
err error err error
) )
@ -261,6 +263,10 @@ func (b *Board) Parse(pgn string) error {
if move == "" { if move == "" {
continue continue
} }
// parse algebraic notation with numbers
move = re.ReplaceAllString(move, "")
if err = b.Move(move); err != nil { if err = b.Move(move); err != nil {
return err return err
} }

View File

@ -511,6 +511,24 @@ func TestBoardCastle(t *testing.T) {
assertNoPiece(t, b, "e1") 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) { func assertParse(t *testing.T, b *chess.Board, moves string) {
assert.NoError(t, b.Parse(moves)) assert.NoError(t, b.Parse(moves))
} }