-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathpgn.py
142 lines (124 loc) · 4.76 KB
/
pgn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from datetime import datetime
from six import StringIO
def _node(g, spec):
parts = spec.split('.')
for p in parts:
if p not in g:
return None
g = g[p]
return str(g)
def _cap(s):
if len(s) == 0:
return s
return s[0].upper() + s[1:]
def from_game(game, headers=None):
"""Converts a JSON game to a PGN string.
:game: The game object.
:headers: An optional dictionary with custom PGN headers.
>>> game = lichess.api.game('Qa7FJNk2', with_moves=1)
>>> pgn = lichess.pgn.from_game(game)
>>> print(pgn)
[Event "Casual rapid game"]
...
"""
if headers is None:
headers = {}
else:
headers = dict(headers)
g = game
if 'moves' not in g:
raise ValueError('The provided game doesn\'t have any moves. Maybe you forgot to set with_moves=1 on the API call?')
result = '1/2-1/2' if _node(g, 'status') == 'draw' else '1-0' if _node(g, 'winner') == 'white' else '0-1' if _node(g, 'winner') == 'black' else '*'
h = []
h.append(("Event", "%s %s game" % ("Rated" if g["rated"] else "Casual", g["speed"])))
h.append(('Site', 'https://lichess.org/%s' % g['id']))
h.append(('Date', datetime.fromtimestamp(int(g['createdAt']) / 1000.0).strftime('%Y.%m.%d')))
h.append(('Round', '?'))
h.append(('White', _node(g, 'players.white.userId') or '?'))
h.append(('Black', _node(g, 'players.black.userId') or '?'))
h.append(('Result', result))
h.append(('WhiteElo', _node(g, 'players.white.rating') or '?'))
h.append(('BlackElo', _node(g, 'players.black.rating') or '?'))
h.append(('ECO', _node(g, 'opening.eco')))
h.append(('Opening', _node(g, 'opening.name')))
if g['variant'] == 'fromPosition':
h.append(('FEN', g['initialFen']))
elif g['variant'] != 'standard':
h.append(('Variant', _cap(g['variant'])))
if g['speed'] != 'correspondence':
h.append(('TimeControl', _node(g, 'clock.initial') + '+' + _node(g, 'clock.increment')))
moves = g['moves']
pgn = ''
for i in h:
key = i[0]
value = headers.pop(key, i[1])
if value is not None:
pgn += '[{} "{}"]\n'.format(key, value)
pgn += '\n'
ply = 0
for m in moves.split(' '):
if ply % 2 == 0:
pgn += str(int(ply / 2 + 1)) + '. '
pgn += m + ' '
ply += 1
pgn += result
pgn += '\n'
return pgn
def io_from_game(game, headers=None):
"""Like :data:`~lichess.pgn.from_game`, except it wraps the result in :data:`StringIO`.
This allows easy integration with the `python-chess <https://github.com/niklasf/python-chess>`_ library.
But if this is all you need, see the :mod:`lichess.format` module for an easier way.
:game: The game object.
:headers: An optional dictionary with custom PGN headers.
>>> import lichess.api
>>> import lichess.pgn
>>> import chess.pgn
>>>
>>> api_game = lichess.api.game('Qa7FJNk2', with_moves=1)
>>> game = chess.pgn.read_game(lichess.pgn.io_from_game(api_game))
>>> print(game.end().board())
. . k . R b r .
. p p r . N p .
p . . . . . . p
. . . . . . . .
. . . p . . . .
P . . P . . . P
. P P . . P P .
. . K R . . . .
"""
return StringIO(from_game(game, headers))
def _validate_games(games):
if isinstance(games, dict) and 'currentPageResults' in games:
raise ValueError('The games argument must be a list. You provided a paginator. Use [\'currentPageResults\'] to get the games list, or use an API method that returns a generator.')
def from_games(games, headers=None):
"""Converts an enumerable of JSON games to a PGN string.
:games: The enumerable of game objects.
:headers: An optional dictionary with (shared) custom PGN headers.
>>> import itertools
>>>
>>> games = lichess.api.user_games('cyanfish', with_moves=1)
>>> pgn = lichess.pgn.from_games(itertools.islice(games, 5))
>>> print(pgn.count('\\n'))
66
"""
_validate_games(games)
return '\n'.join((from_game(g, headers) for g in games))
def save_games(games, path, headers=None):
"""Saves an enumerable of JSON games to a PGN file.
:games: The enumerable of game objects.
:path: The path of the .pgn file to save.
:headers: An optional dictionary with (shared) custom PGN headers.
>>> import itertools
>>>
>>> games = lichess.api.user_games('cyanfish', with_moves=1)
>>> lichess.pgn.save_games(itertools.islice(games, 5), 'mylast5games.pgn')
"""
_validate_games(games)
with open(path, 'wb') as fout:
first = True
for g in games:
if first:
first = False
else:
fout.write('\n'.encode('utf-8'))
fout.write(from_game(g, headers).encode('utf-8'))