Skip to content

Instantly share code, notes, and snippets.

@hartwork
Created August 18, 2021 22:54
Show Gist options
  • Save hartwork/d20033dde5192738ec1e14fae722972a to your computer and use it in GitHub Desktop.
Save hartwork/d20033dde5192738ec1e14fae722972a to your computer and use it in GitHub Desktop.
Extract Lichess game URLs from a PGN download for games where Black played the Pirc Defence
#! /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