[python] king's square at checkmate

Viewer

copydownloadembedprintName: king's square at checkmate
  1. import chess.pgn
  2. import pandas as pd
  3. import time
  4.  
  5. # king position at checkmate
  6.  
  7. def parse_checkmate_squares(filepath):
  8.     pgns = open(filepath)
  9.     # checkmate_indices = []
  10.     checkmate_games = []
  11.     checkmate_squares = []
  12.     checkmated_color = []
  13.     checkmate_lists = [checkmate_games, checkmate_squares, checkmated_color]
  14.  
  15.     i = 0
  16.     while i < 1000000:
  17.         gm = chess.pgn.read_game(pgns)
  18.         try:
  19.             if '#' in gm.end().san():
  20.                 checkmated_color.append(gm.end().turn())
  21.                 checkmate_games.append(gm.headers['Site'])
  22.                 checkmate_squares.append(list(gm.end().board().pieces(chess.KING, checkmated_color[-1]))[0])
  23.         except AttributeError# some cases, like abandons, where no moves are ever played which causes errors
  24.             continue
  25.         i += 1
  26.  
  27.     color_map = {True:'White', False:'Black'}
  28.     col_names = ['game', 'square', 'color']
  29.     df = pd.DataFrame(checkmate_lists)
  30.     df = df.transpose()
  31.     df.columns = col_names
  32.     df['color'] = df['color'].map(color_map)
  33.     pgns.close()
  34.     return df
  35.  
  36. start_time = time.time()
  37. filepath = #pgns from lichess
  38. df = parse_checkmate_squares(filepath)
  39. print("--- %s seconds ---" % (time.time() - start_time))
  40.  
  41. df.to_csv('checkmate_squares.csv')

Editor

You can edit this paste and save as new:


File Description
  • king's square at checkmate
  • Paste Code
  • 03 Jan-2021
  • 1.28 Kb
You can Share it: