Last active
May 28, 2018 07:43
-
-
Save ajoyoommen/bdc63350edda9178333030885becd508 to your computer and use it in GitHub Desktop.
Plots the games won, lost and drawn by a player in different game formats. Save PGN files from chess.com into a folder `pgn/`. Requires `matplotlib`.
This file contains hidden or 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
from datetime import datetime | |
import os | |
import re | |
import sys | |
import matplotlib.pyplot as plt | |
USER = "ajoy" | |
DIRNAME = 'pgn/' | |
def fetch_games(): | |
texts = [] | |
for f in os.listdir(DIRNAME): | |
with open(DIRNAME + f) as pgn: | |
text = pgn.read() | |
texts.append(text) | |
return "\n".join(texts) | |
def parse(text): | |
game = {} | |
games = [] | |
lines = text.split('\n') | |
for line in lines: | |
m = re.match(r'\[(\w+) "(.*)"\]', line) | |
if not m: | |
continue | |
key = m.group(1).lower() | |
if key == 'event': | |
if game: | |
games.append(game) | |
game = {} | |
game[key] = m.group(2) | |
return games | |
def get_player(): | |
return USER | |
def process(games): | |
player = get_player() | |
types = [] | |
for game in games: | |
# Find the player's score | |
result = game['result'].split('-') | |
if result[0] in '01': | |
score = int(result[0]) | |
else: | |
score = 0.5 | |
if game['black'] == player: | |
score = abs(score - 1) | |
game['score'] = score | |
# Calculate integer score | |
if score == 0: | |
game['iscore'] = -1 | |
elif score == 0.5: | |
game['iscore'] = 0 | |
else: | |
game['iscore'] = 1 | |
# Parse the date on the game | |
game['date'] = datetime.strptime(game['date'], '%Y.%m.%d') | |
# Append the game type | |
types.append(game['timecontrol']) | |
# Sort games by date | |
games.sort(key=lambda game:game['date']) | |
return games, list(set(types)) | |
def plot_games(): | |
text = fetch_games() | |
games, types = process(parse(text)) | |
data = {} | |
for t in types: | |
score = 0 | |
scores = [] | |
# data[t] = [g['score'] for g in games if g['timecontrol'] == t] | |
for g in games: | |
if g['timecontrol'] != t: | |
continue | |
score += g['iscore'] | |
scores.append(score) | |
data[t] = scores | |
for t, scores in data.items(): | |
if len(scores) < 10: | |
continue | |
plt.plot(scores, label=t) | |
plt.legend(loc='upper left') | |
plt.xlabel('Games played') | |
plt.ylabel('Score') | |
plt.show() | |
if __name__ == '__main__': | |
plot_games() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment