Skip to content

Commit 5cde80f

Browse files
committed
finish adding savegames
1 parent ad9c066 commit 5cde80f

File tree

3 files changed

+37
-6
lines changed

3 files changed

+37
-6
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,6 @@ dmypy.json
134134
.vscode/
135135

136136
RLTut_Python3.code-workspace
137+
138+
# saved games
139+
*.sav

input_handlers.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import os
34
from typing import Optional, TYPE_CHECKING, Callable, Tuple, Union
45

56
import tcod
@@ -87,17 +88,19 @@ def on_render(self, console: tcod.Console) -> None:
8788
def ev_quit(self, event: tcod.event.Quit) -> Optional[Action]:
8889
raise SystemExit()
8990

91+
9092
class PopupMessage(BaseEventHandler):
9193
"""Display a popup text window"""
94+
9295
def __init__(self, parent_handler: BaseEventHandler, text: str):
9396
self.parent = parent_handler
9497
self.text = text
9598

9699
def on_render(self, console: tcod.Console) -> None:
97100
"""Render the parent and dim the result then print the message on top"""
98101
self.parent.on_render(console)
99-
console.rgb["fg"] //=8
100-
console.rgb["bg"] //=8
102+
console.rgb["fg"] //= 8
103+
console.rgb["bg"] //= 8
101104

102105
console.print(
103106
console.width // 2,
@@ -112,6 +115,7 @@ def ev_keydown(self, event: tcod.event.KeyDown) -> Optional[BaseEventHandler]:
112115
"""any key returns to the parent handler"""
113116
return self.parent
114117

118+
115119
class EventHandler(BaseEventHandler):
116120
def __init__(self, engine: Engine):
117121
self.engine = engine
@@ -194,9 +198,18 @@ def ev_keydown(self, event: tcod.event.KeyDown) -> Optional[ActionOrHandler]:
194198

195199

196200
class GameOverEventHandler(EventHandler):
201+
def on_quit(self) -> None:
202+
"""Handle exiting a finished game"""
203+
if os.path.exists("savegame.sav"):
204+
os.remove("savegame.sav") # deletes the active save file
205+
raise exceptions.QuitWithoutSaving() # avoid saving a finished game
206+
207+
def ev_quit(self, event: tcod.event.Quit) -> None:
208+
self.on_quit()
209+
197210
def ev_keydown(self, event: tcod.event.KeyDown) -> None:
198211
if event.sym == tcod.event.K_ESCAPE:
199-
raise SystemExit()
212+
self.on_quit()
200213

201214

202215
CURSOR_Y_KEYS = {

setup_game.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
from __future__ import annotations
33

44
import copy
5-
from ctypes import alignment
5+
import lzma
6+
import pickle
7+
import traceback
68
from typing import Optional
79

810
import tcod
@@ -51,6 +53,14 @@ def new_game() -> Engine:
5153
return engine
5254

5355

56+
def load_game(filename: str) -> Engine:
57+
"""Load an Engine instance from a file"""
58+
with open(filename, "rb") as f:
59+
engine = pickle.loads(lzma.decompress(f.read()))
60+
assert isinstance(engine, Engine)
61+
return engine
62+
63+
5464
class MainMenu(input_handlers.BaseEventHandler):
5565
"""Handle the main menu rendering and input."""
5666

@@ -93,8 +103,13 @@ def ev_keydown(
93103
if event.sym in (tcod.event.K_q, tcod.event.K_ESCAPE):
94104
raise SystemExit()
95105
elif event.sym == tcod.event.K_c:
96-
# TODO: Load the game here
97-
pass
106+
try:
107+
return input_handlers.MainGameEventHandler(load_game("savegame.sav"))
108+
except FileNotFoundError:
109+
return input_handlers.PopupMessage(self, "No saved game to load.")
110+
except Exception as exc:
111+
traceback.print_exc() # print to stderr
112+
return input_handlers.PopupMessage(self, f"failed to load save:\n{exc}")
98113
elif event.sym == tcod.event.K_n:
99114
return input_handlers.MainGameEventHandler(new_game())
100115

0 commit comments

Comments
 (0)