-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathadvent.py
More file actions
1953 lines (1656 loc) · 57 KB
/
Copy pathadvent.py
File metadata and controls
1953 lines (1656 loc) · 57 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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# adventure module
#
# vim: et sw=2 ts=2 sts=2
# for Python3, use:
# import urllib.request as urllib2
import urllib2
import random
import string
import textwrap
import time
# "directions" are all the ways you can describe going some way;
# they are code-visible names for directions for adventure authors
direction_names = ["NORTH","SOUTH","EAST","WEST","UP","DOWN","RIGHT","LEFT",
"IN","OUT","FORWARD","BACK",
"NORTHWEST","NORTHEAST","SOUTHWEST","SOUTHEAST"]
direction_list = [ NORTH, SOUTH, EAST, WEST, UP, DOWN, RIGHT, LEFT,
IN, OUT, FORWARD, BACK,
NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST] = \
range(len(direction_names))
NOT_DIRECTION = None
# some old names, for backwards compatibility
(NORTH_WEST, NORTH_EAST, SOUTH_WEST, SOUTH_EAST) = \
(NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST)
directions = dir_by_name = dict(zip(direction_names, direction_list))
def define_direction (number, name):
if name in dir_by_name:
exit("%s is already defined as %d" % (name, dir_by_name[name]))
dir_by_name[name] = number
def lookup_dir (name):
return dir_by_name.get(name, NOT_DIRECTION)
# add lower-case versions of all names in direction_names
for name in direction_names:
define_direction(dir_by_name[name], name.lower())
# add common aliases:
# maybe the alias mechanism should be a more general
# (text-based?) mechanism that works for any command?!!!
common_aliases = [
(NORTH, "n"),
(SOUTH, "s"),
(EAST, "e"),
(WEST, "w"),
(UP, "u"),
(DOWN, "d"),
(FORWARD, "fd"),
(FORWARD, "fwd"),
(FORWARD, "f"),
(BACK, "bk"),
(BACK, "b"),
(NORTHWEST,"nw"),
(NORTHEAST,"ne"),
(SOUTHWEST,"sw"),
(SOUTHEAST, "se")
]
for (k,v) in common_aliases:
define_direction(k,v)
# define the pairs of opposite directions
opposite_by_dir = {}
def define_opposite_dirs (d1, d2):
for dir in (d1, d2):
opposite = opposite_by_dir.get(dir)
if opposite is not None:
exit("opposite for %s is already defined as %s" % (dir, opposite))
opposite_by_dir[d1] = d2
opposite_by_dir[d2] = d1
opposites = [(NORTH, SOUTH),
(EAST, WEST),
(UP, DOWN),
(LEFT, RIGHT),
(IN, OUT),
(FORWARD, BACK),
(NORTHWEST, SOUTHEAST),
(NORTHEAST, SOUTHWEST)]
for (d1,d2) in opposites:
define_opposite_dirs(d1,d2)
def opposite_direction (dir):
return opposite_by_dir[dir]
# registered games
registered_games = {}
FEEDBACK = 0
TITLE = 1
DESCRIPTION = 2
CONTENTS = 3
DEBUG = 4
class Colors:
'''
Colors class:
reset all colors with colors.reset
two subclasses fg for foreground and bg for background.
use as colors.subclass.colorname.
i.e. colors.fg.red or colors.bg.green
also, the generic bold, disable, underline, reverse, strikethrough,
and invisible work with the main class
i.e. colors.bold
'''
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
class FG:
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
class BG:
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'
articles = ['a', 'an', 'the']
# some prepositions to recognize indirect objects in prepositional phrases
prepositions = ['aboard', 'about', 'above', 'across', 'after', 'against', 'along'
'among', 'around', 'at', 'atop', 'before', 'behind', 'below', 'beneath',
'beside', 'besides', 'between', 'beyond', 'by', 'for', 'from', 'in', 'including'
'inside', 'into', 'on', 'onto', 'outside', 'over', 'past', 'than' 'through', 'to',
'toward', 'under', 'underneath', 'onto', 'upon', 'with', 'within']
# changes "lock" to "a lock", "apple" to "an apple", etc.
# note that no article should be added to proper names;
# For now we'll just assume
# anything starting with upper case is proper.
# Do not add an article to plural nouns.
def add_article (name):
# simple plural test
if len(name) > 1 and name[-1] == 's' and name[-2] != 's':
return name
# check if there is already an article on the string
if name.split()[0] in articles:
return name
consonants = "bcdfghjklmnpqrstvwxyz"
vowels = "aeiou"
if name and (name[0] in vowels):
article = "an "
elif name and (name[0] in consonants):
article = "a "
else:
article = ""
return "%s%s" % (article, name)
def normalize_input(text):
superfluous = articles + ['and']
rest = []
for word in text.split():
word = "".join(l for l in word if l not in string.punctuation)
if word not in superfluous:
rest.append(word)
return ' '.join(rest)
def proper_list_from_dict(d):
names = d.keys()
buf = []
name_count = len(names)
for (i,name) in enumerate(names):
if i != 0:
buf.append(", " if name_count > 2 else " ")
if i == name_count-1 and name_count > 1:
buf.append("and ")
buf.append(add_article(name))
return "".join(buf)
# Base is a place to put default inplementations of methods that everything
# in the game should support (eg save/restore, how to respond to verbs etc)
class Base(object):
def __init__(self, name):
self.game = None
self.name = name
self.verbs = {}
self.phrases = {}
self.vars = {}
def flag(self, f):
if f in self.vars:
return self.vars[f]
else:
return False
def set_flag(self, f):
self.vars[f] = True
def unset_flag(self, f):
if f in self.vars:
del self.vars[f]
def var(self, var):
if var in self.vars:
return self.vars[var]
else:
return None
def set_var(self, var, val):
self.vars[var] = val
def unset_var(self, var):
if var in self.vars:
del self.vars[var]
def add_verb(self, v):
self.verbs[' '.join(v.name.split())] = v
v.bind_to(self)
return v
def get_verb(self, verb):
c = ' '.join(verb.split())
if c in self.verbs:
return self.verbs[c]
else:
return None
def add_phrase(self, phrase, f, requirements = []):
if isinstance(f, BaseVerb):
f.bind_to(self)
self.phrases[' '.join(phrase.split())] = (f, set(requirements))
def get_phrase(self, phrase, things_present):
phrase = phrase.strip()
things_present = set(things_present)
if not phrase in self.phrases:
return None
p = self.phrases[phrase]
if things_present.issuperset(p[1]):
return p[0]
return None
def output(self, text, message_type = 0):
self.game.output(text, message_type)
class BaseVerb(Base):
def __init__(self, function, name):
Base.__init__(self, name)
self.function = function
self.bound_to = None
def bind_to(self, obj):
self.bound_to = obj
def act(self, actor, noun, words):
result = True
if not self.function(actor, noun, None):
result = False
# treat 'verb noun1 and noun2..' as 'verb noun1' then 'verb noun2'
# treat 'verb noun1, noun2...' as 'verb noun1' then 'verb noun2'
# if any of the nouns work on the verb consider the command successful,
# even if some of them don't
if words:
for noun in words:
if self.function(actor, noun, None):
result = True
return result
class Die(BaseVerb):
def __init__(self, string, name = ""):
BaseVerb.__init__(self, None, name)
self.string = string
def act(self, actor, noun, words):
self.bound_to.game.output("%s %s %s" % (actor.name.capitalize(),
actor.isare, self.string), FEEDBACK)
self.bound_to.game.output("%s %s dead." % (actor.name.capitalize(),
actor.isare), FEEDBACK)
actor.terminate()
return True
class Say(BaseVerb):
def __init__(self, string, name = ""):
BaseVerb.__init__(self, None, name)
self.string = string
def act(self, actor, noun, words):
self.bound_to.game.output(self.string, FEEDBACK)
return True
class SayOnNoun(Say):
def __init__(self, string, noun, name = ""):
Say.__init__(self, string, name)
self.noun = noun
def act(self, actor, noun, words):
if self.noun != noun:
return False
self.bound_to.game.output(self.string, FEEDBACK)
return True
class SayOnSelf(SayOnNoun):
def __init__(self, string, name = ""):
SayOnNoun.__init__(self, string, None, name)
# Verb is used for passing in an unbound global function to the constructor
class Verb(BaseVerb):
def __init__(self, function, name = ""):
BaseVerb.__init__(self, function, name)
# explicitly pass in self to the unbound function
def act(self, actor, noun, words):
return self.function(self.bound_to, actor, noun, words)
def list_prefix(a, b): # is a a prefix of b
if not a:
return True
if not b:
return False
if a[0] != b[0]:
return False
return list_prefix(a[1:], b[1:])
def get_noun(words, things):
if words[0] in articles:
if len(words) > 1:
done = False
for t in things:
n = t.name.split()
if list_prefix(n, words[1:]):
noun = t.name
words = words[len(n)+1:]
done = True
break
if not done:
noun = words[1]
words = words[2:]
else:
done = False
for t in things:
n = t.name.split()
if list_prefix(n, words):
noun = t.name
words = words[len(n):]
done = True
break
if not done:
noun = words[0]
words = words[1:]
return (noun, words)
# A class to hold utility methods useful during game development, but
# not needed for normal game play. Import the advent_devtools module
# to get the full version of the tools.
class DevToolsBase(object):
def __init__(self):
self.game = None
def set_game(self, game):
self.game = game
def debug_output(self, text, level):
return
def start(self):
return
global _devtools
_devtools = DevToolsBase()
def register_devtools(devtools):
global _devtools
_devtools = devtools
# The Game: container for hero, locations, robots, animals etc.
class Game(Base):
def __init__(self, name="bwx-adventure"):
Base.__init__(self, name)
self.objects = {}
self.fresh_location = False
self.player = None
self.current_actor = None
self.location_list = []
self.robots = {}
self.animals = {}
global _devtools
self.devtools = _devtools
self.devtools.set_game(self)
self.http_output = False
self.http_text = ""
self.done = False
def set_name(self, name):
self.name = name
# add a bidirectional connection between points A and B
def add_connection(self, connection):
connection.game = self
if isinstance(connection.way_ab, (list, tuple)):
for way in connection.way_ab:
connection.point_a.add_exit(connection, way)
else:
connection.point_a.add_exit(connection, connection.way_ab)
# this is messy, need a better way to do this
reverse_connection = Connection(connection.name,
connection.point_b,
connection.point_a,
connection.way_ba,
connection.way_ab)
reverse_connection.game = self
if isinstance(connection.way_ba, (list, tuple)):
for way in connection.way_ba:
connection.point_b.add_exit(reverse_connection, way)
else:
connection.point_b.add_exit(reverse_connection, connection.way_ba)
return connection
def new_connection(self, *args):
return self.add_connection(Connection(*args))
def connect(self, place_a, place_b, way_ab, way_ba=None):
"""An easier-to use version of new_connection. It generates a
connection name automatically from the two location names and also
allows the second direction argument to be omitted. If the second
direction is omitted, it defaults to the opposite of the first
direction."""
name = place_a.name + "_to_" + place_b.name
return self.new_connection(name, place_a, place_b, way_ab, way_ba)
# add another location to the game
def add_location(self, location):
location.game = self
self.location_list.append(location)
return location
def new_location(self, *args):
return self.add_location(Location(*args))
# add an actor to the game
def add_actor(self, actor):
actor.game = self
if isinstance(actor, Player):
self.player = actor
if isinstance(actor, Animal):
self.animals[actor.name] = actor
if isinstance(actor, Robot):
self.robots[actor.name] = actor
return actor
def new_player(self, location):
self.player = Player()
self.add_actor(self.player)
self.player.set_location(location)
return self.player
def if_flag(self, flag, s_true, s_false, location = None):
return lambda loc: (s_false, s_true)[flag in (location or loc).vars]
def if_var(self, v, value, s_true, s_false, location = None):
return lambda loc: (s_false, s_true)[v in (location or loc).vars and (location or loc).vars[v] == value]
def output(self, text, message_type = 0):
if message_type != DEBUG:
self.current_actor.set_next_script_response(text)
self.print_output(text, message_type)
def style_text(self, text, message_type):
if False: # trinket.io
return text
if self.http_output:
if (message_type == FEEDBACK):
text = "<font color='red'>" + text + '</font>'
if (message_type == TITLE):
text = "<font color='blue'>" + text + '</font>'
if (message_type == DESCRIPTION):
pass
if (message_type == CONTENTS):
text = "<font color='green'>" + text + '</font>'
if (message_type == DEBUG):
text = "<font color='orange'>" + text + '</font>'
return text
if (message_type == FEEDBACK):
text = Colors.FG.pink + text + Colors.reset
if (message_type == TITLE):
text = Colors.FG.yellow + Colors.BG.blue + "\n" + text + Colors.reset
if (message_type == DESCRIPTION):
text = Colors.reset + text
if (message_type == CONTENTS):
text = Colors.FG.green + text + Colors.reset
if (message_type == DEBUG):
text = Colors.bold + Colors.FG.black + Colors.BG.orange + "\n" + text + Colors.reset
return text
# overload this for HTTP output
def print_output(self, text, message_type = 0):
if self.http_output:
self.http_text += self.style_text(text, message_type) + "\n"
else:
print self.style_text(text, message_type)
# checks to see if the inventory in the items list is in the user's inventory
def inventory_contains(self, items):
if set(items).issubset(set(self.player.inventory.values())):
return True
return False
def entering_location(self, location):
if (self.player.location == location and self.fresh_location):
return True
return False
def say(self, s):
return lambda game: game.output(s)
@staticmethod
def register(name, fn):
global registered_games
registered_games[name] = fn
@staticmethod
def get_registered_games():
global registered_games
return registered_games
def run_init(self, update_func = None):
# reset this every loop so we don't trigger things more than once
self.fresh_location = False
self.update_func = update_func
self.current_actor = self.player
self.devtools.start()
def init_scripts(self):
actor = self.current_actor
script_name = self.var('script_name')
if script_name != None:
self.devtools.debug_output("script_name: " + script_name, 3)
actor.act_load_file(actor, script_name, None)
if self.flag('check'):
actor.act_check_script(actor, script_name, None)
else:
actor.act_run_script(actor, script_name, None)
recording_name = self.var('start_recording')
if recording_name != None:
self.devtools.debug_output("recording_name: " + recording_name, 3)
actor.act_start_recording(actor, recording_name, None)
def run_room(self):
actor = self.current_actor
if actor == self.player or actor.flag('verbose'):
# if the actor moved, describe the room
if actor.check_if_moved():
self.output(actor.location.title(actor), TITLE)
# cache this as we need to know it for the query to entering_location()
self.fresh_location = actor.location.first_time
where = actor.location.describe(actor, actor.flag('verbose'))
if where:
self.output("")
self.output(where)
self.output("")
# See if the animals want to do anything
for animal in self.animals.values():
# first check that it is not dead
if animal.health >= 0:
animal.act_autonomously(actor.location)
def run_step(self, cmd = None):
self.http_text = ""
actor = self.current_actor
# has the developer supplied an update function?
if self.update_func:
self.update_func() # call the update function
# check if we're currently running a script
user_input = actor.get_next_script_command();
if user_input == None:
if cmd != None:
user_input = cmd
else:
# get input from the user
try:
self.output("") # add a blank line
user_input = raw_input("> ")
except EOFError:
return False
# see if the command is for a robot
if ':' in user_input:
robot_name, command = user_input.split(':')
try:
actor = self.robots[robot_name]
except KeyError:
self.output("I don't know anybot named %s" % robot_name, FEEDBACK)
return True
else:
actor = self.player
command = user_input
self.current_actor = actor
# now we're done with punctuation and other superfluous words like articles
command = normalize_input(command)
# see if we want to quit
if command == 'q' or command == 'quit':
return False
# give the input to the actor in case it's recording a script
if not actor.set_next_script_command(command):
return True
words = command.split()
if not words:
return True
# following the Infocom convention commands are decomposed into
# VERB(verb), OBJECT(noun), INDIRECT_OBJECT(indirect).
# For example: "hit zombie with hammer" = HIT(verb) ZOMBIE(noun) WITH HAMMER(indirect).
# handle 'tell XXX ... "
target_name = ""
if words[0].lower() == 'tell' and len(words) > 2:
(target_name, words) = get_noun(words[1:], actor.location.actors.values())
things = actor.inventory.values() + \
actor.location.contents.values() + \
actor.location.exits.values() + \
list(actor.location.actors.values()) + \
[actor.location] + \
[actor]
for c in actor.location.contents.values():
if isinstance(c, Container) and c.is_open:
things += c.contents.values()
potential_verbs = []
for t in things:
potential_verbs += t.verbs.keys()
# extract the VERB
verb = None
potential_verbs.sort(key=lambda key : -len(key))
for v in potential_verbs:
vv = v.split()
if list_prefix(vv, words):
verb = v
words = words[len(vv):]
if not verb:
verb = words[0]
words = words[1:]
# extract the OBJECT
noun = None
if words:
(noun, words) = get_noun(words, things)
# extract INDIRECT (object) in phrase of the form VERB OBJECT PREPOSITION INDIRECT
indirect = None
if len(words) > 1 and words[0].lower() in prepositions:
(indirect, words) = get_noun(words[1:], things)
# first check phrases
for thing in things:
f = thing.get_phrase(command, things)
if f:
if isinstance(f, BaseVerb):
if f.act(actor, noun, words):
return True
else:
f(self, thing)
return True
# if we have an explicit target of the VERB, do that.
# e.g. "tell cat eat foo" -> cat.eat(cat, 'food', [])
if target_name:
for a in actor.location.actors.values():
if a.name != target_name:
continue
v = a.get_verb(verb)
if v:
if v.act(a, noun, words):
return True
self.output("Huh? %s %s?" % (target_name, verb), FEEDBACK)
return True
# if we have an INDIRECT object, try it's handle first
# e.g. "hit cat with hammer" -> hammer.hit(actor, 'cat', [])
if indirect:
# try inventory and room contents
things = actor.inventory.values() + actor.location.contents.values()
for thing in things:
if indirect == thing.name:
v = thing.get_verb(verb)
if v:
if v.act(actor, noun, words):
return True
for a in actor.location.actors.values():
if indirect == a.name:
v = a.get_verb(verb)
if v:
if v.act(a, noun, words):
return True
# if we have a NOUN, try it's handler next
if noun:
for thing in things:
if noun == thing.name:
v = thing.get_verb(verb)
if v:
if v.act(actor, None, words):
return True
for a in actor.location.actors.values():
if noun == a.name:
v = a.get_verb(verb)
if v:
if v.act(a, None, words):
return True
# location specific VERB
v = actor.location.get_verb(verb)
if v:
if v.act(actor, noun, words):
return True
# handle directional moves of the actor
if not noun:
if verb in directions:
actor.act_go1(actor, verb, None)
return True
# general actor VERB
v = actor.get_verb(verb)
if v:
if v.act(actor, noun, words):
return True
# not understood
self.output("Huh?", FEEDBACK)
return True
def run(self , update_func = None):
self.run_init(update_func)
self.run_room() # just set the stage before we do any scripting
self.init_scripts() # now we can set up scripts
while True:
if self.done:
return
self.run_room()
if self.player.health < 0:
self.output ("Better luck next time!")
break
if not self.run_step():
break
self.output("\ngoodbye!\n", FEEDBACK)
class Object(Base):
# name: short name of this thing
# description: full description
# fixed: is it stuck or can it be taken
def __init__(self, name, desc, fixed=False):
Base.__init__(self, name)
self.description = desc
self.fixed = fixed
def describe(self, observer):
if isinstance(self.description, str):
return self.description
else:
return self.description(self)
class Consumable(Object):
def __init__(self, name, desc, verb, replacement = None):
Object.__init__(self, name, desc)
self.verb = verb
verb.bind_to(self)
self.consume_term = "consume"
self.replacement = replacement
def consume(self, actor, noun, words):
if not actor.location.replace_object(actor, self.name, self.replacement):
return False
self.output("%s %s%s %s." % (actor.name.capitalize(), self.consume_term,
actor.verborverbs, self.description))
self.verb.act(actor, noun, words)
return True
class Food(Consumable):
def __init__(self, name, desc, verb, replacement = None):
Consumable.__init__(self, name, desc, verb, replacement)
self.consume_term = "eat"
class Drink(Consumable):
def __init__(self, name, desc, verb, replacement = None):
Consumable.__init__(self, name, desc, verb, replacement)
self.consume_term = "drink"
class Lockable(Base):
def __init__(self, name):
Base.__init__(self, name)
self.requirements = {}
def make_requirement(self, thing):
self.requirements[thing.name] = thing
self.lock()
def lock(self):
self.set_flag('locked')
def unlock(self):
self.unset_flag('locked')
def is_locked(self):
return self.flag('locked')
def try_unlock(self, actor):
# first see if the actor is whitelisted
if isinstance(self, Location) and actor.allowed_locs:
if not self in actor.allowed_locs:
return False
# now check if we're locked
if not self.flag('locked'):
return True
# check if there are any implicit requirements for this object
if len(self.requirements) == 0:
self.output("It's locked!")
return False
# check to see if the requirements are in the inventory
if set(self.requirements).issubset(set(actor.inventory)):
self.output("You use the %s, the %s unlocks" % \
(proper_list_from_dict(self.requirements),
self.name), FEEDBACK)
self.unlock()
return True
self.output("It's locked! You will need %s." % \
proper_list_from_dict(self.requirements), FEEDBACK)
return False
class Container(Lockable):
def __init__(self, name, description):
Lockable.__init__(self, name)
self.description = description
self.first_time = True
self.contents = {}
self.close()
def add_object(self, obj):
self.contents[obj.name] = obj
obj.game = self.game
return obj
def new_object(self, name, desc, fixed=False):
return self.add_object(Object(name, desc, fixed))
def describe(self, observer, force=False):
desc = "" # start with a blank string
# add the description
if self.first_time or force:
desc += self.description
self.first_time = False
else:
desc += add_article(self.name)
if not self.is_open():
desc += " The %s is closed." % self.name
else:
desc += " The %s is open." % self.name
# it's open so describe the contents
desc += self.describe_contents()
return desc
def describe_contents(self):
desc = ""
if not self.contents:
return desc
# try to make a readable list of the things
contents_description = proper_list_from_dict(self.contents)
# is it just one thing?
if len(self.contents) == 1:
desc += self.game.style_text("\nThere is %s in the %s." % \
(contents_description, self.name), CONTENTS)
else:
desc += self.game.style_text("\nThere are a few things in the %s: %s." % \
(self.name, contents_description), CONTENTS)
return desc
def open(self, actor):
if self.is_open():
self.output("The %s is already open." % self.name)
return True
if not self.try_unlock(actor):
return False
self.output("The %s opens." % self.name, FEEDBACK)
self.output(self.describe_contents(), CONTENTS)
self.unset_flag('closed')
def close(self):
self.set_flag('closed')
def is_open(self):
return not self.flag('closed')
# A "location" is a place in the game.
class Location(Lockable):
# name: short name of this location
# description: full description
# contents: things that are in a location
# exits: ways to get out of a location
# first_time: is it the first time here?
# actors: other actors in the location
def __init__(self, name, description, inonat="in"):
Lockable.__init__(self, name)
self.description = description
self.inonat = inonat
self.contents = {}
self.exits = {}
self.first_time = True
self.actors = {}
def title(self, actor):
preamble = ""
if (actor != self.game.player):
preamble = "%s %s %s the " % (actor.name.capitalize(), actor.isare, self.inonat)
return " --=( %s%s )=-- " % (preamble, self.name)
def add_object(self, obj):
self.contents[obj.name] = obj
obj.game = self.game
return obj
def add_actor(self, actor):
actor.set_location(self)
return actor
def new_object(self, name, desc, fixed=False):
return self.add_object(Object(name, desc, fixed))
def description_str(self, d):
if isinstance(d, (list, tuple)):
desc = ""
for dd in d:
desc += self.description_str(dd)
return desc
else:
if isinstance(d, str):
return self.game.style_text(d, DESCRIPTION)
else:
return self.description_str(d(self))
def describe(self, observer, force=False):