Skip to content

PGN Parser

Corentin Giaufer Saubert edited this page Dec 27, 2024 · 1 revision

PGN Parser Quick Guide

Basic Usage

Parsing a Complete Game

// 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()

Reading Game Tags

// Access game metadata
event := game.GetTagPair("Event")
white := game.GetTagPair("White")
black := game.GetTagPair("Black")

Accessing Moves

// Get main line moves
moves := game.Moves()
for _, move := range moves {
    fmt.Printf("Move: %v\n", move)
}

Handling Common Elements

Comments and Annotations

[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)
    }
}

Variations

[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)
    }
}

Results

// Check game outcome
switch game.Outcome() {
case WhiteWon:
    fmt.Println("White won")
case BlackWon:
    fmt.Println("Black won")
case Draw:
    fmt.Println("Game drawn")
}

Best Practices

  1. Error Handling

    game, err := parser.Parse()
    if err != nil {
        // Handle malformed PGN or illegal moves
    }
  2. Move Validation

    • All moves are validated against legal moves
    • Invalid moves cause parse errors
    • Check FEN tag for non-standard start positions
  3. Memory Management

    • Process large files game by game
    • Don't store unnecessary game trees
    • Clear resources when done

Common Operations

Starting from Custom Position

// 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()

Navigating Game Tree

// Move through the game
game.GoForward()  // Next move
game.GoBack()     // Previous move

// Check position
if game.IsAtEnd() {
    fmt.Println("Reached end of line")
}

Supported PGN Elements

  • 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)

Clone this wiki locally