-
Notifications
You must be signed in to change notification settings - Fork 14
PGN Parser
Corentin Giaufer Saubert edited this page Dec 27, 2024
·
1 revision
// Read PGN content
gameText := `[Event "World Championship"]
1. e4 e5 2. Nf3 Nc6`
// Tokenize and parse
scanned := &GameScanned{Raw: gameText}
tokens, _ := TokenizeGame(scanned)
parser := NewParser(tokens)
game, err := parser.Parse()// Access game metadata
event := game.GetTagPair("Event")
white := game.GetTagPair("White")
black := game.GetTagPair("Black")// Get main line moves
moves := game.Moves()
for _, move := range moves {
fmt.Printf("Move: %v\n", move)
}[Event "Example Game"]
1. e4 {Strong move} e5 2. Nf3! Nc6 {Counter-attack}
// Comments are available through the Move struct
for _, move := range game.Moves() {
if move.comments != "" {
fmt.Printf("Move %s has comment: %s\n", move, move.comments)
}
}[Event "Example Game"]
1. e4 e5 (1...c5 2. Nf3) 2. Nf3
// Access variations for a move
for _, move := range game.Moves() {
variations := game.Variations(move)
for _, var := range variations {
fmt.Printf("Alternative to %s: %s\n", move, var)
}
}// Check game outcome
switch game.Outcome() {
case WhiteWon:
fmt.Println("White won")
case BlackWon:
fmt.Println("Black won")
case Draw:
fmt.Println("Game drawn")
}-
Error Handling
game, err := parser.Parse() if err != nil { // Handle malformed PGN or illegal moves }
-
Move Validation
- All moves are validated against legal moves
- Invalid moves cause parse errors
- Check FEN tag for non-standard start positions
-
Memory Management
- Process large files game by game
- Don't store unnecessary game trees
- Clear resources when done
// Game with custom starting position
pgn := `[FEN "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 0 1"]
1. Bc4 Bc5`
// Parse and validate
tokens, _ := TokenizeGame(&GameScanned{Raw: pgn})
parser := NewParser(tokens)
game, _ := parser.Parse()// Move through the game
game.GoForward() // Next move
game.GoBack() // Previous move
// Check position
if game.IsAtEnd() {
fmt.Println("Reached end of line")
}- Standard moves (e4, Nf3)
- Comments {text}
- NAGs (!?, !, !!)
- Variations (...)
- Results (1-0, 0-1, 1/2-1/2)
- Tag Pairs [Key "Value"]
- Special moves (O-O, O-O-O)