-
Notifications
You must be signed in to change notification settings - Fork 0
/
scottdumb.py
executable file
·352 lines (282 loc) · 11.8 KB
/
scottdumb.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
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
#!/usr/bin/python3
from gi.repository import GLib
from gi.repository import Gdk
from gi.repository import Gtk
from game import Game
from extraction import ExtractedFile
from wordytextview import WordyTextView
from execution import DelayRequest
from contextlib import contextmanager
from sys import argv
from random import seed
import gi
gi.require_version('Gtk', '3.0')
def make_filter(name, pattern):
"""Builds a GTK file-filter conveniently."""
f = Gtk.FileFilter()
f.set_name(name)
f.add_pattern(pattern)
return f
@contextmanager
def filechooser(window, title, action):
dlg = Gtk.FileChooserDialog(title="Game", action=action,
transient_for=window)
try:
yield dlg
finally:
dlg.destroy()
@contextmanager
def error_alert(window, text):
dlg = Gtk.MessageDialog(
transient_for=self,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.CANCEL,
text=text)
try:
yield dlg
finally:
dlg.destroy()
def get_game_path():
with filechooser(None, "Game", Gtk.FileChooserAction.OPEN) as dlg:
dlg.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
dlg.add_button(Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
dlg.set_default_response(Gtk.ResponseType.OK)
dlg.add_filter(make_filter("Games", "*.dat"))
dlg.add_filter(make_filter("All Files", "*"))
if (dlg.run() == Gtk.ResponseType.OK):
return dlg.get_filename()
else:
return None
class GuiGame(Game):
"""This game subclass uses file chooser dialogs to prompt for save or load file names."""
def __init__(self, extracted_game, window):
Game.__init__(self, extracted_game)
self.window = window
def get_save_game_path(self):
with filechooser(self.window, "Save Game", Gtk.FileChooserAction.SAVE) as dlg:
dlg.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
dlg.add_button(Gtk.STOCK_SAVE, Gtk.ResponseType.OK)
dlg.set_default_response(Gtk.ResponseType.OK)
dlg.add_filter(make_filter("Saved Games", "*.sav"))
dlg.add_filter(make_filter("All Files", "*"))
if (dlg.run() == Gtk.ResponseType.OK):
return dlg.get_filename()
else:
return None
def get_load_game_path(self):
with filechooser(self.window, "Load Game", Gtk.FileChooserAction.OPEN) as dlg:
dlg.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
dlg.add_button(Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
dlg.set_default_response(Gtk.ResponseType.OK)
dlg.add_filter(make_filter("Saved Games", "*.sav"))
dlg.add_filter(make_filter("All Files", "*"))
if (dlg.run() == Gtk.ResponseType.OK):
return dlg.get_filename()
else:
return None
class GameWindow(Gtk.Window):
"""
This window displays the game output in two sections; a top section shows
the room description, and the lower shows the transcript as you go. An text
entry area allows command input, and a header bar lets you load and save your game.
"""
def __init__(self, game_file):
Gtk.Window.__init__(self)
with open(game_file, "r") as f:
self.game = GuiGame(ExtractedFile(f), self)
self.header_bar = Gtk.HeaderBar()
self.header_bar.set_title("Scott Dumb")
self.header_bar.set_show_close_button(True)
self.load_button = Gtk.Button(label="_Load", use_underline=True)
self.load_button.connect("clicked", self.on_load_game)
self.header_bar.pack_start(self.load_button)
self.save_button = Gtk.Button(label="_Save", use_underline=True)
self.save_button.connect("clicked", self.on_save_game)
self.header_bar.pack_end(self.save_button)
self.set_titlebar(self.header_bar)
self.room_view = WordyTextView(self.game, self.queue_command)
self.room_view.connect(
"size-allocate", self.on_room_view_size_allocate)
self.script_view = WordyTextView(self.game, self.queue_command)
self.inventory_view = WordyTextView(
self.game, self.queue_command, width_request=300)
vBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
vBox.pack_start(self.room_view, False, False, 0)
vBox.pack_start(Gtk.Separator(), False, False, 0)
self.command_box = Gtk.Box(
orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
command_label = Gtk.Label(label=">")
command_label.set_margin_start(5)
self.command_entry = Gtk.Entry()
self.command_entry.connect("activate", self.on_command_activate)
score_button = Gtk.Button(label="_Score", use_underline=True)
score_button.connect("clicked", self.on_score)
score_button.set_margin_end(5)
self.command_box.pack_end(score_button, False, False, 0)
self.command_box.pack_start(command_label, False, False, 0)
self.command_box.pack_end(self.command_entry, True, True, 0)
vBox.pack_end(self.command_box, False, False, 5)
self.scroller = Gtk.ScrolledWindow()
self.scroller.set_policy(Gtk.PolicyType.NEVER,
Gtk.PolicyType.AUTOMATIC)
self.scroller.add(self.script_view)
hBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
hBox.pack_start(self.scroller, True, True, 0)
hBox.pack_start(Gtk.Separator(), False, False, 0)
hBox.pack_start(self.inventory_view, False, False, 0)
vBox.pack_end(hBox, True, True, 0)
self.add(vBox)
self.set_default_size(900, 500)
self.running_iter = self.before_turn()
self.pending_command = None
self.run_next_command()
def flush_output(self):
"""
Displays any pending output. Each output is displayed in its own
text-view, so this will implicitly place a line break after the output.
"""
words = self.game.extract_output()
if len(words) > 0:
self.script_view.append_line()
self.script_view.append_words(words)
self.scroll_to_bottom()
def scroll_to_bottom(self):
"""Scrolls the output window as far down as possible."""
def do_scroll():
adj = self.scroller.get_vadjustment()
adj.set_value(adj.get_upper())
do_scroll()
# Scrolling may fail because the wigdets are not laid out yet;
# so this will try to do it again a little later.
GLib.idle_add(do_scroll)
def update_room_view(self):
"""
Generate the room description text afresh and displays it. The previous
room description is removed.
"""
game = self.game
if game.wants_room_update or game.needs_room_update:
words = game.player_room.get_look_words()
self.room_view.clear()
self.room_view.append_words(words)
game.needs_room_update = False
game.wants_room_update = False
self.command_box.set_sensitive(not game.game_over)
self.update_inventory_view()
def update_inventory_view(self):
words = self.game.get_inventory_words()
self.inventory_view.clear()
self.inventory_view.append_words(words)
def before_turn(self):
"""
Performs game logic that should happen before user commands are accepted.
This flushes output and updates the room view.
"""
game = self.game
if not game.game_over:
yield from game.perform_occurances()
self.command_entry.grab_focus()
self.flush_output()
self.update_room_view()
def on_room_view_size_allocate(self, allocation, data):
self.scroll_to_bottom()
def on_load_game(self, data):
"""Handles the load game button."""
game = self.game
if game.load_game():
self.pending_command = None
self.running_iter = None
game.extract_output()
self.script_view.clear()
game.output_line("Game loaded.")
self.flush_output()
self.update_room_view()
self.command_entry.grab_focus()
def on_save_game(self, data):
if self.running_iter is not None:
with error_alert(selk, "You cannot save now.") as dlg:
dlg.format_secondary_text(
"You cannot save the game while game actions are happening.")
return
"""Handles the save game button."""
self.game.save_game()
# Command handling
def queue_command(self, cmd):
"""Runs a command. A command may not complete immediately,
and if so it will be running after this returns. If called while
another command is running, this will queue the new command to run
after the old completes."""
if self.running_iter is None:
self.running_iter = self.command_iter(cmd)
self.run_next_command()
else:
self.pending_command = cmd
self.command_entry.set_text(cmd)
def cancel_commands(self):
"""This terminates all running and pending command
activity. This interrupts a running command, if any,
and is done before loading save."""
self.running_iter = None
self.pending_command = None
def command_iter(self, cmd):
"""This handles a user command; it parses it and
echos it to the output, then starts it executing.
This returns an iterator that must be consumed to complete
to command, and may return requests to be handled;
see run_next_command()."""
game = self.game
try:
self.command_entry.set_text("")
verb, noun = game.parse_command(cmd)
game.output_line("> " + cmd)
self.flush_output()
yield from game.perform_command(verb, noun)
except Exception as e:
game.output(str(e))
self.flush_output()
yield from self.before_turn()
def run_next_command(self):
"""Executes the next step of running_iter, or
if that runs out, it starts pending_command and does
the first stop of that.
This loops and runs as much as possible of the commands,
but if a delay occurs it queues intself to run again after
the delay. In this way the UI can be responsive while a pause
opcode is running."""
if self.running_iter is not None:
try:
while True:
request = next(self.running_iter)
if isinstance(request, DelayRequest):
GLib.timeout_add(request.milliseconds,
self.run_next_command)
break
except StopIteration:
self.running_iter = None
if self.pending_command is not None and self.pending_command == self.command_entry.get_text():
cmd = self.pending_command
self.pending_command = None
self.queue_command(cmd)
except Exception as e:
game.output(str(e))
self.flush_output()
self.update_room_view()
False # do not repeat
def on_command_activate(self, data):
"""Handles a user-entered command when the user hits enter."""
if not self.game.game_over:
cmd = self.command_entry.get_text()
self.queue_command(cmd)
def on_score(self, data):
"""Generates the score command"""
if not self.game.game_over:
self.queue_command("SCORE")
seed()
if len(argv) >= 2:
game_path = argv[1]
else:
game_path = get_game_path()
win = GameWindow(game_path)
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()