Extract Lichess game URLs from a PGN download for games where Black played the Pirc Defence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
# Copyright (C) 2021 Sebastian Pipping <sebastian@pipping.org> | |
# Licensed under the Apache 2.0 License | |
# Version 2021-08-19 00:51 UTC+2 | |
import argparse | |
from typing import List | |
import chess | |
import chess.pgn # https://python-chess.readthedocs.io/en/latest/pgn.html | |
def is_turn(board, for_white: bool) -> bool: | |
return board.turn == for_white | |
def matches_opening(opening_moves: List[str], game_moves: List[chess.Move], for_white: bool) -> bool: | |
for i, expected_uci in enumerate(opening_moves): | |
move_index = 2 * i + int(not for_white) | |
try: | |
if game_moves[move_index] != chess.Move.from_uci(expected_uci): | |
return False | |
except IndexError: | |
return False | |
return True | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('pgn_file', metavar='PGN_FILE') | |
config = parser.parse_args() | |
default_board = chess.Board() | |
moves_pirc_defence = [ | |
'd7d6', | |
'g8f6', | |
'g7g6', | |
] | |
with open(config.pgn_file) as f: | |
while True: | |
game = chess.pgn.read_game(f) | |
if game is None: | |
break | |
url = game.headers['Site'] | |
board = game.board() | |
if board != default_board or not is_turn(board, for_white=True): | |
continue | |
moves = list(game.mainline_moves()) | |
if matches_opening(moves_pirc_defence, moves, for_white=False): | |
print(f'{url}/black#6') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment