Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions fixtures/pgns/multi_frompos_games.pgn
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
[Event "Slav Defense"]
[Site ""]
[Date "2025.07.12"]
[Round "1"]
[White ""]
[Black ""]
[Result "*"]
[UTCDate "2025.07.12"]
[UTCTime "15:51:00"]
[Variant "Standard"]
[ECO "D10"]

1. d4 d5 2. c4 c6 { [%eval 0.21] } *


[Event "Slav Defense: Three Knights Variation"]
[Site ""]
[Date "2025.07.12"]
[Round "1"]
[White ""]
[Black ""]
[Result "*"]
[UTCDate "2025.07.12"]
[UTCTime "15:51:00"]
[Variant "Standard"]
[ECO "D15"]
[FEN "rnbqkbnr/pp2pppp/2p5/3p4/2PP4/8/PP2PPPP/RNBQKBNR w KQkq - 0 3"]
[SetUp "1"]

3. Nf3 (3. Nc3 Nf6 4. Nf3) 3... Nf6 4. Nc3 { [%eval 0.16] } *


[Event "Slav Defense: Chebanenko Variation"]
[Site ""]
[Date "2025.07.12"]
[Round "1"]
[White ""]
[Black ""]
[Result "*"]
[UTCDate "2025.07.12"]
[UTCTime "15:51:01"]
[Variant "Standard"]
[ECO "D15"]
[FEN "rnbqkb1r/pp2pppp/2p2n2/3p4/2PP4/2N2N2/PP2PPPP/R1BQKB1R b KQkq - 3 4"]
[SetUp "1"]

4... a6 { [%eval 0.19] } *


[Event "Slav Defense: Chebanenko Variation, 5. cxd5"]
[Site ""]
[Date "2025.07.12"]
[Round "1"]
[White ""]
[Black ""]
[Result "*"]
[UTCDate "2025.07.12"]
[UTCTime "15:51:01"]
[Variant "Standard"]
[ECO "D15"]
[FEN "rnbqkb1r/1p2pppp/p1p2n2/3p4/2PP4/2N2N2/PP2PPPP/R1BQKB1R w KQkq - 0 5"]
[SetUp "1"]

5. cxd5 (5. e3 e6 6. cxd5 cxd5) 5... cxd5 6. e3 e6 { [%eval 0.11] } *


17 changes: 17 additions & 0 deletions fixtures/pgns/single_frompos.pgn
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[Event "Slav Defense: Chebanenko Variation, 5. cxd5"]
[Site ""]
[Date "2025.07.12"]
[Round "1"]
[White ""]
[Black ""]
[Result "*"]
[UTCDate "2025.07.12"]
[UTCTime "15:51:01"]
[Variant "Standard"]
[ECO "D15"]
[FEN "rnbqkb1r/1p2pppp/p1p2n2/3p4/2PP4/2N2N2/PP2PPPP/R1BQKB1R w KQkq - 0 5"]
[SetUp "1"]

5. cxd5 (5. e3 e6 6. cxd5 cxd5) 5... cxd5 6. e3 e6 { [%eval 0.11] } *


21 changes: 14 additions & 7 deletions game.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,9 @@ func (g *Game) String() string {
// and that its first child is the first actual move.
needTrailingSpace := false
if g.rootMove != nil && len(g.rootMove.children) > 0 {
needTrailingSpace = !writeMoves(g.rootMove, 1, true, &sb, false, false)
needTrailingSpace = !writeMoves(g.rootMove,
g.rootMove.Position().moveCount,
g.rootMove.Position().Turn() == White, &sb, false, false, true)
}

// Append the game result.
Expand Down Expand Up @@ -429,11 +431,13 @@ func cmpTags(a, b sortableTagPair) int {
// sb - pointer to a strings.Builder where the formatted move notation is appended.
// subVariation - true if the current call is within a sub-variation, affecting formatting details.
// closedVariation - true if the prior call closed a sub-variation, affecting formatting details.
// isRoot - true if the current move is the root move of a game, affecting formatting details.
//
// The function recurses through the move tree, writing the main line first and then processing any additional variations,
// ensuring that the output adheres to standard PGN conventions. Future enhancements may include support for all NAG values.
// the function returns whether or not a trailing space was added to the output
func writeMoves(node *Move, moveNum int, isWhite bool, sb *strings.Builder, subVariation, closedVariation bool) bool {
func writeMoves(node *Move, moveNum int, isWhite bool, sb *strings.Builder,
subVariation, closedVariation, isRoot bool) bool {
trailingSpace := false

// If no moves remain, stop.
Expand All @@ -453,7 +457,7 @@ func writeMoves(node *Move, moveNum int, isWhite bool, sb *strings.Builder, subV
currentMove = node.children[0]
}

writeMoveNumber(moveNum, isWhite, subVariation, closedVariation, sb)
writeMoveNumber(moveNum, isWhite, subVariation, closedVariation, isRoot, sb)

// Encode the move using your AlgebraicNotation.
writeMoveEncoding(node, currentMove, subVariation, sb)
Expand Down Expand Up @@ -484,19 +488,22 @@ func writeMoves(node *Move, moveNum int, isWhite bool, sb *strings.Builder, subV
nextMoveNum = moveNum + 1
nextIsWhite = true
}
writeMoves(currentMove, nextMoveNum, nextIsWhite, sb, false, closedVar)
writeMoves(currentMove, nextMoveNum, nextIsWhite, sb, false, closedVar,
false)
}

return trailingSpace
}

func writeMoveNumber(moveNum int, isWhite bool, subVariation, closedVariation bool, sb *strings.Builder) {
func writeMoveNumber(moveNum int, isWhite bool, subVariation, closedVariation,
isRoot bool, sb *strings.Builder) {

if closedVariation {
sb.WriteString(" ")
}
if isWhite {
sb.WriteString(fmt.Sprintf("%d. ", moveNum))
} else if subVariation || closedVariation {
} else if subVariation || closedVariation || isRoot {
sb.WriteString(fmt.Sprintf("%d... ", moveNum))
}
}
Expand Down Expand Up @@ -538,7 +545,7 @@ func writeVariations(node *Move, moveNum int, isWhite bool, sb *strings.Builder)

variation := node.children[i]
sb.WriteString("(")
writeMoves(variation, moveNum, isWhite, sb, true, false)
writeMoves(variation, moveNum, isWhite, sb, true, false, false)
sb.WriteString(")")
}
}
Expand Down
4 changes: 3 additions & 1 deletion lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const (
CommentStart // {
CommentEnd // }
COMMENT // The comment text
RESULT // 1-0, 0-1, 1/2-1/2
RESULT // 1-0, 0-1, 1/2-1/2, *
CAPTURE // 'x' in moves
FILE // a-h in moves when used as disambiguation
RANK // 1-8 in moves when used as disambiguation
Expand Down Expand Up @@ -533,6 +533,8 @@ func (l *Lexer) NextToken() Token {
case 'x':
l.readChar()
return Token{Type: CAPTURE, Value: "x"}
case '*':
fallthrough
case '-':
return l.readResult()
case '$', '!', '?':
Expand Down
55 changes: 55 additions & 0 deletions lexer_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package chess

import (
"os"
"testing"
)

Expand Down Expand Up @@ -1014,3 +1015,57 @@ func validateTokens(t *testing.T, tokens []Token) {
}
}
}

func TestSingleFromPosPGN(t *testing.T) {
// Read fixture
data, err := os.ReadFile("fixtures/pgns/single_frompos.pgn")
if err != nil {
t.Fatalf("Failed to read fixture: %v", err)
}

lexer := NewLexer(string(data))

expected := []struct {
typ TokenType
value string
}{
// Tags
{TagStart, "["}, {TagKey, "Event"}, {TagValue, "Slav Defense: Chebanenko Variation, 5. cxd5"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "Site"}, {TagValue, ""}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "Date"}, {TagValue, "2025.07.12"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "Round"}, {TagValue, "1"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "White"}, {TagValue, ""}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "Black"}, {TagValue, ""}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "Result"}, {TagValue, "*"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "UTCDate"}, {TagValue, "2025.07.12"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "UTCTime"}, {TagValue, "15:51:01"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "Variant"}, {TagValue, "Standard"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "ECO"}, {TagValue, "D15"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "FEN"}, {TagValue, "rnbqkb1r/1p2pppp/p1p2n2/3p4/2PP4/2N2N2/PP2PPPP/R1BQKB1R w KQkq - 0 5"}, {TagEnd, "]"},
{TagStart, "["}, {TagKey, "SetUp"}, {TagValue, "1"}, {TagEnd, "]"},
// Moves
{MoveNumber, "5"}, {DOT, "."},
{FILE, "c"}, {CAPTURE, "x"}, {SQUARE, "d5"},
{VariationStart, "("},
{MoveNumber, "5"}, {DOT, "."}, {SQUARE, "e3"}, {SQUARE, "e6"},
{MoveNumber, "6"}, {DOT, "."}, {FILE, "c"}, {CAPTURE, "x"}, {SQUARE, "d5"},
{FILE, "c"}, {CAPTURE, "x"}, {SQUARE, "d5"},
{VariationEnd, ")"},
{MoveNumber, "5"}, {ELLIPSIS, "..."}, {FILE, "c"}, {CAPTURE, "x"}, {SQUARE, "d5"},
{MoveNumber, "6"}, {DOT, "."}, {SQUARE, "e3"}, {SQUARE, "e6"},
{CommentStart, "{"}, {CommandStart, "[%"}, {CommandName, "eval"}, {CommandParam, "0.11"}, {CommandEnd, "]"}, {CommentEnd, "}"},
{RESULT, "*"},
}

for i, exp := range expected {
tok := lexer.NextToken()
if tok.Type != exp.typ || tok.Value != exp.value {
t.Errorf("Token %d: expected {%v, %q}, got {%v, %q}",
i, exp.typ, exp.value, tok.Type, tok.Value)
}
}
// final EOF
if tok := lexer.NextToken(); tok.Type != EOF {
t.Errorf("Expected EOF, got %v", tok.Type)
}
}
8 changes: 6 additions & 2 deletions move.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,12 @@ func (m *Move) Children() []*Move {
}

func (m *Move) Number() int {
//return m.MoveNumber()
return int(m.number)
ret := int(m.number)
if ret == 0 { // 0 indicates the 'dummy' rootMove
ret = 1
}

return ret

}

Expand Down
4 changes: 2 additions & 2 deletions pgn.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,10 +602,10 @@ func (p *Parser) parseVariation(parentMoveNumber uint64, parentPly int) error {
p.game.pos = newPos
}
} else {
p.game.pos = StartingPosition()
p.game.pos = p.game.rootMove.position.copy()
}
} else {
p.game.pos = StartingPosition()
p.game.pos = p.game.rootMove.position.copy()
}

p.currentMove = variationParent
Expand Down
16 changes: 15 additions & 1 deletion scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ func validateExpand(t *testing.T, scanner *Scanner, expectedLastLines []string)
for scanner.HasNext() {
game, err := scanner.ParseNext()
if err != nil {
t.Fatalf("fail to parse game: %s", err.Error())
t.Fatalf("fail to parse game %v: %s", count+1, err.Error())
}

if game == nil {
Expand Down Expand Up @@ -291,3 +291,17 @@ func TestScannerNoExpand(t *testing.T) {
scanner := NewScanner(reader)
validateExpand(t, scanner, expectedLastLines)
}

func TestScannerMultiFromPosNoExpand(t *testing.T) {
expectedLastLines := []string{
"1. d4 d5 2. c4 c6 { [%eval 0.21] } *",
"3. Nf3 (3. Nc3 Nf6 4. Nf3) 3... Nf6 4. Nc3 { [%eval 0.16] } *",
"4... a6 { [%eval 0.19] } *",
"5. cxd5 (5. e3 e6 6. cxd5 cxd5) 5... cxd5 6. e3 e6 { [%eval 0.11] } *",
}

pgn := mustParsePGN("fixtures/pgns/multi_frompos_games.pgn")
reader := strings.NewReader(pgn)
scanner := NewScanner(reader)
validateExpand(t, scanner, expectedLastLines)
}
Loading