Repository navigation
Expand file tree
/
Copy pathsave_load.py
More file actions
397 lines (335 loc) · 15.3 KB
/
Copy pathsave_load.py
File metadata and controls
397 lines (335 loc) · 15.3 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""Saving and loading games (and their selection menus).
Split out of chessMain.py. Depends on shared state, app, the PGN list helper
and the menu helpers -- never on chessMain.
"""
import sys
from datetime import datetime
import pygame as p
import pygame_menu
import pygame_menu.font
from pygame_menu.locals import ALIGN_CENTER, ALIGN_LEFT
from app_context import app
from state import playParameters, positionParameters, small_font_theme
import BoardScreen as BS
import pgngamelist
from GameState import GameState
from menu_helpers import addChoosePGNFile, make_updater, make_selector_updater
import game_loop_common as glc
# PGN headers carried around in playParameters. Date/Round are kept apart from
# the rest because they are not editable in the Save dialog: they are simply
# preserved from a loaded game, or defaulted for a brand-new one.
_HEADER_KEYS = ["White", "Black", "Event", "Site", "Result"]
def header_from_playparameters(params):
header = []
for key in _HEADER_KEYS:
val = params.get(key.lower(), "")
if val:
header.extend([key, val])
# Date/Round of a LOADED game are preserved: re-saving it after adding
# comments or variations is still the same game played on the same day, so
# restamping it with today's date would be wrong. Only a game with no date
# of its own (a new one) gets today / "*".
header.extend(["Date", params.get("date") or datetime.today().strftime("%Y.%m.%d")])
header.extend(["Round", params.get("round") or "*"])
return header
def playparameters_from_game(game) -> None:
"""Inverse of header_from_playparameters: copy a loaded game's PGN headers
into playParameters, so the Save dialog proposes THAT game's White / Black /
Event / Site / Result instead of whatever was there from the previous save.
Without this, saving a loaded game silently rewrites its headers with the
leftover values (setHeader in save_menu overwrites them wholesale).
Date/Round come along too, so re-saving an analysed game keeps its original
date instead of being restamped with today's.
"""
for key in _HEADER_KEYS + ["Date", "Round"]:
value = game.headers.get(key, "")
# "?" is python-chess's placeholder for an absent header -- treat it as
# empty so the dialog does not propose a literal "?" as the player name.
# Dates are "????.??.??" when unknown; partial ones ("2024.??.??") are
# kept as they are, they still carry the year the game was played.
if value in ("?", "????.??.??", None):
value = ""
playParameters[key.lower()] = value
def clear_loaded_game_date() -> None:
"""Forget the Date/Round adopted from a loaded game, so a NEW game gets
today's date instead of inheriting the date of the last game analysed.
Players/Event/Site are left alone: they are menu preferences (persisted in
state._PERSIST_SPEC), so a game played now legitimately keeps them."""
playParameters["date"] = ""
playParameters["round"] = ""
def clear_loaded_game_headers(event: str = "", site: str = "") -> None:
"""Full reset of the PGN headers adopted from a loaded game, for when the
new game has nothing to do with it (setting up a position from scratch):
players and result are blanked too, not just the date. `event`/`site` seed
those two (e.g. "Position setup")."""
clear_loaded_game_date()
playParameters["white"] = ""
playParameters["black"] = ""
playParameters["result"] = ""
playParameters["event"] = event
playParameters["site"] = site
def save_game(gs:GameState):
'''
Saves the current game state to a file.
The file name is taken from the positionParameters["filename"] variable.
'''
if positionParameters["filename"] is None:
text = "Please select a PGN file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2 )
return
# Honor the folder chosen by the user in the file selector (e.g. endgames/);
# if none was registered we fall back to pgn/.
folder = positionParameters.get("filename_folder") or None
gamelist = pgngamelist.PgnGameList(positionParameters["filename"], folder=folder)
positionParameters["gameid"] = gamelist.save_game(gs, positionParameters["gameid"])
app.main_background()
BS.drawEndGameText(app.screen, None, "Game saved")
BS.update()
app.delay(2)
def load_game(gs:GameState) -> bool:
'''
Loads a game from a selected PGN file allowing the user to choose which game to load.
Returns True if a game was actually loaded, False when the user cancelled (or
no PGN file was chosen).
'''
if positionParameters["filename"] is None:
text = "Please select a PGN file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2 )
return False
# Honor the folder chosen in the file selector (e.g. openings/ or endgames/);
# without it the list would always be read from pgn/ and look empty for a
# file picked elsewhere (mirror of save_game).
folder = positionParameters.get("filename_folder") or None
gameList = pgngamelist.PgnGameList(positionParameters["filename"], folder=folder)
total_games = len(gameList.games)
games_per_page = 20
current_page = 0
total_pages = (total_games + games_per_page - 1) // games_per_page
menu_running = True
surface = app.screen
# The picked index is tracked locally: positionParameters["gameid"] may still
# hold the game loaded/saved earlier, so testing it after the loop would treat
# a Cancel as "load that old game again".
picked = None
def load_game_wrapper(N):
nonlocal menu_running, picked
picked = N
menu_running = False
def cancel_load():
nonlocal menu_running
menu_running = False
def next_page():
nonlocal current_page
if current_page < total_pages-1:
current_page += 1
refresh_menu()
def prev_page():
nonlocal current_page
if current_page > 0:
current_page -= 1
refresh_menu()
def first_page():
nonlocal current_page
current_page = 0
refresh_menu()
def last_page():
nonlocal current_page
current_page = total_pages-1
refresh_menu()
# The game rows are a TABLE, not a list of sentences: a monospaced font plus
# left alignment makes the padded columns (#, White, Black, moves, result)
# actually line up. With the proportional default font the padding spaces are
# narrower than the letters and the columns drift.
game_list_theme = small_font_theme.copy()
game_list_theme.widget_font = pygame_menu.font.FONT_FIRACODE
game_list_theme.widget_font_size = 16
game_list_theme.widget_alignment = ALIGN_LEFT
game_list_theme.widget_margin = (0, 0)
_load_menu = pygame_menu.Menu('Select Game', app.W, app.H,
theme=game_list_theme)
frame_width = 4 * 80 + 3 * 10 # 4 buttons of 80px + 3 margins of 10px
frame_height = 50
# Column widths, in characters (monospaced font -> characters == alignment).
_W_NUM, _W_NAME, _W_MOVES = 4, 22, 5
def _clip(s: str, n: int) -> str:
"""Left-justify `s` in `n` chars, truncating long names with an ellipsis
so one very long player name cannot push the later columns out of line."""
s = s or "?"
return s.ljust(n) if len(s) <= n else s[:n - 1] + "…"
def refresh_menu():
_load_menu.clear()
start = current_page * games_per_page
end = min(start + games_per_page, total_games)
header = "%s %s %s %s %s" % (
"".ljust(_W_NUM), _clip("White", _W_NAME), _clip("Black", _W_NAME),
"moves".rjust(_W_MOVES), "result")
_load_menu.add.label(header, font_color=(200, 200, 200), align=ALIGN_LEFT)
for i in range(start, end):
game = gameList.games[i]
white = game.headers.get("White", "?")
black = game.headers.get("Black", "?")
result = game.headers.get("Result", "?")
nMoves = len(list(game.mainline_moves()))
label = "%s %s %s %s %s" % (
("%d." % (i + 1)).ljust(_W_NUM),
_clip(white, _W_NAME),
_clip(black, _W_NAME),
str(nMoves).rjust(_W_MOVES),
result,
)
_load_menu.add.button(label, load_game_wrapper, i, align=ALIGN_LEFT)
if total_games > games_per_page:
_load_menu.add.vertical_margin(10)
nav_buttons = []
#if current_page > 0:
nav_buttons.append(_load_menu.add.button('|<', first_page))
nav_buttons.append(_load_menu.add.button('<<', prev_page))
#if current_page < total_pages :
nav_buttons.append(_load_menu.add.button('>>', next_page))
nav_buttons.append(_load_menu.add.button('>|', last_page))
if nav_buttons:
nav_frame = _load_menu.add.frame_h(frame_width, frame_height, align=ALIGN_CENTER)
for b in nav_buttons:
nav_frame.pack(b, margin=(10, 0)) # horizontal margin between buttons
_load_menu.add.vertical_margin(20)
_load_menu.add.button('Cancel', cancel_load)
refresh_menu()
while menu_running:
events = p.event.get()
for ev in events:
if ev.type == p.QUIT:
p.quit()
sys.exit()
surface.fill((0, 0, 0))
_load_menu.update(events)
_load_menu.draw(surface)
p.display.flip()
if picked is None:
return False # Cancel: leave the current game alone
if not gameList.load_game(gs, picked):
return False # index gone stale (file changed under us)
positionParameters["gameid"] = picked
# Adopt the loaded game's headers as the current ones (see the note there).
playparameters_from_game(gameList.games[picked])
#gs.goToLastMove()
app.main_background()
BS.drawEndGameText(app.screen, None, "Game selected")
BS.update()
app.delay(2)
return True
def load_menu(GS:GameState) -> bool:
"""Returns True if a game was actually loaded (False on Cancel), so the
caller can reset its unsaved-edits baseline only when something changed."""
menu_running = True
loaded = False
surface = app.screen
def load_game_wrapper():
nonlocal menu_running, loaded
menu_running = False
# Cancelling the game picker must not count as a load either.
loaded = load_game(GS)
def cancel_load():
nonlocal menu_running
menu_running = False
_load_menu = pygame_menu.Menu('Load Game', app.W, app.H, theme=pygame_menu.themes.THEME_BLUE)
addChoosePGNFile(_load_menu)
_load_menu.add.button('Load', load_game_wrapper)
_load_menu.add.button('Cancel', cancel_load)
while menu_running:
events = p.event.get()
for ev in events:
if ev.type == p.QUIT:
glc.quit_app() # guards unsaved PGN edits before exiting
surface.fill((0, 0, 0))
_load_menu.update(events)
_load_menu.draw(surface)
p.display.flip()
return loaded
def save_menu(GS:GameState) -> bool:
"""Returns True if the game was actually saved (False on Cancel), so the
caller can mark the PGN clean only when a save really happened."""
menu_running = True
saved = False
surface = app.screen
# (file, folder): two PGNs with the same name in different folders are
# different targets, so comparing the name alone would miss the change.
prev_pgn = (positionParameters["filename"],
positionParameters.get("filename_folder"))
# A game is "loaded" (hence replaceable) only if some gameid is set. None is
# the single "nothing loaded" sentinel (see state.positionParameters).
loaded_gameid = positionParameters.get("gameid")
was_loaded = loaded_gameid is not None
# Replace the loaded game, or append a new one? Only meaningful when a game
# was loaded; default to replacing it (the usual case is adding variations
# to the game you just opened).
save_as_new = [False]
def set_save_as_new(selection, _index):
# pygame-menu hands over the whole entry: (label, value).
save_as_new[0] = selection[0][1]
def save_game_wrapper():
nonlocal menu_running, saved
GS.setHeader(header_from_playparameters(playParameters))
current_pgn = (positionParameters["filename"],
positionParameters.get("filename_folder"))
# Saving into a different PGN than the loaded one is always a new game:
# the loaded index means nothing in the destination file.
if prev_pgn != current_pgn or not was_loaded or save_as_new[0]:
positionParameters["gameid"] = None
save_game(GS)
saved = True
menu_running = False
def cancel_save():
nonlocal menu_running
menu_running = False
_save_menu = pygame_menu.Menu('Save Game', app.W, app.H,
theme=pygame_menu.themes.THEME_BLUE)
# create=True: the file dialog lets you type a NEW file name (e.g. to start a
# new opening file), not only pick an existing PGN.
addChoosePGNFile(_save_menu, title="Choose or create PGN file", create=True)
_save_menu.add.text_input('White:', default=playParameters["white"] or "", onchange=make_updater("white",str,playParameters))
_save_menu.add.text_input('Black:', default=playParameters["black"] or "", onchange=make_updater("black",str,playParameters))
_save_menu.add.text_input('Event:', default=playParameters["event"] or "", onchange=make_updater("event",str,playParameters))
_save_menu.add.text_input('Site:', default=playParameters["site"] or "", onchange=make_updater("site",str,playParameters))
# Result is one of the 4 standard PGN values, chosen from a selector (it was a
# free text-input but "Result: lol" does not conform to the format and
# confuses downstream PGN parsers).
_result_options = [
("* (in progress / unknown)", "*"),
("1-0 (White wins)", "1-0"),
("0-1 (Black wins)", "0-1"),
("1/2-1/2 (draw)", "1/2-1/2"),
]
_result_current = playParameters.get("result") or "*"
_result_idx = next(
(i for i, (_, v) in enumerate(_result_options) if v == _result_current),
0,
)
_save_menu.add.selector('Result: ', _result_options,
default=_result_idx,
onchange=make_selector_updater("result", playParameters))
if was_loaded:
_save_menu.add.selector(
'Save as: ',
[("Replace loaded game #%d" % (loaded_gameid + 1), False),
("New game (append)", True)],
default=0,
onchange=set_save_as_new,
)
_save_menu.add.button('Save', save_game_wrapper)
_save_menu.add.button('Cancel', cancel_save)
while menu_running:
events = p.event.get()
for ev in events:
if ev.type == p.QUIT:
glc.quit_app() # guards unsaved PGN edits before exiting
surface.fill((0, 0, 0))
_save_menu.update(events)
_save_menu.draw(surface)
p.display.flip()
return saved