Search code examples
pythonloopsiteratorgeneratorchess

Is there a way to iterate over PyChess's read_game module?


Good afternoon all!

I have a pipeline built that takes PGN files saved locally (files that contain chess game moves, 1.Nf3, 2.c3 3. ...) and converts them to a bitboard format.

The issue I'm finding is that while PyChess contains a module that can read PGN files:

first_game = chess.pgn.read_game(pgn)

This acts like a generator where I have to recall the module everytime I want to get the next game in the PGN file.

I have around 50 PGN files saved, and each of them have a variable amount of games (anywhere between 1000-10000).

I was hoping for an efficient way to cycle through each PGN without having to resort to some Try-Except block for range(0,10000).

I looked through PyChess's documentation and didn't seem to find anything. With that said, I definitely could've missed something.

Does anyone with experience in this space have any thoughts?


Solution

  • hi i have the same issue and did this:

    pgn = open("Data/game_name.pgn")
    games = []
    while True:
        game= chess.pgn.read_game(pgn)
        if game is not None:
            games.append(game)
        else: 
            break
    

    then you can iterate through every game in the list "games".