-
Notifications
You must be signed in to change notification settings - Fork 2
/
adventure-14.2.py
772 lines (570 loc) · 19.1 KB
/
adventure-14.2.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
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
"""
Text-based adventure game
https://alissa-huskey.github.io/python-class/exercises/adventure.html
+--------------------------------------------------------+
| |
| ========= |
| World Map |
| ========= |
| |
| |
| market |
| | |
| home -- town square -- woods -- hill |
| | | |
| bakery cave |
| |
+--------------------------------------------------------+
Part 14: Dragons
"""
import textwrap
from console import fg, fx
from console.progress import ProgressBar
from console.screen import sc
from console.utils import clear_line
WIDTH = 45
MARGIN = 2
DEBUG = True
MAX_HEALTH = 100
BAR = ProgressBar(
total=(MAX_HEALTH + 0.1),
width=(WIDTH - len("Health") - len("100%")),
clear_left=False,
)
# ## Game World Data #########################################################
PLAYER = {
"place": "home",
"inventory": {"gems": 50},
"health": MAX_HEALTH,
}
PLACES = {
"home": {
"key": "home",
"name": "Your Cottage",
"east": "town-square",
"description": "A cozy stone cottage with a desk and a neatly made bed.",
"items": ["desk", "book"],
},
"town-square": {
"key": "town-square",
"name": "The Town Square",
"west": "home",
"east": "woods",
"north": "market",
"description": (
"A large open space surrounded by buildings with a burbling "
"fountain in the center."
),
},
"market": {
"key": "market",
"name": "The Market",
"south": "town-square",
"items": ["elixir", "dagger"],
"can": ["shop", "buy"],
"description": (
"A tidy store with shelves full of goods to buy. A wooden hand "
"painted menu hangs on the wall."
),
},
"woods": {
"key": "woods",
"name": "The Woods",
"east": "hill",
"west": "town-square",
"description": (
"A dirt road meanders under a canopy of autumn leaves in brilliant "
"hues of gold and crimson.",
"You hear a stream burbling somewhere out of sight. Leaves crunch "
"under your feet on the sun dappled forest floor.",
"You see an ancient moss-covered hollow tree, its gnarled and twisted "
"branches looming over you. On the opposite side, a fallen log juts "
"partway into the road.",
),
"items": [],
},
"hill": {
"key": "hill",
"name": "A grassy hill",
"west": "woods",
"south": "cave",
"description": (
"A winding path leads up the slope of a grassy hill. The air is "
"warm here.",
"At the top of the hill, you see that the path continues to the "
"down to the south. In that direction you can make out a cave by "
"the shore of a lake."
),
"items": [],
},
"cave": {
"key": "cave",
"name": "A cave",
"north": "hill",
"description": (
"Your footsteps echo as you step into the vast cavern.",
"Shafts of sunlight slice through the gloom, playing against the "
"landscape of glittering treasure.",
"Resting atop a mound of gold, a collosal dragon rests curled up snugly. "
"Its three enormous heads snore softly, each in turn.",
),
"items": [],
"can": ["pet"],
},
}
ITEMS = {
"elixir": {
"key": "elixir",
"name": "healing elixir",
"description": "a magical elixir that will heal what ails ya",
"price": -10,
},
"dagger": {
"key": "dagger",
"name": "a dagger",
"description": "a 14 inch dagger with a double-edged blade",
"price": -25,
},
"desk": {
"key": "desk",
"name": "a desk",
"description": (
"A wooden desk with a large leather-bound book open on "
"its surface."
),
},
"book": {
"key": "book",
"can_take": True,
"name": "a book",
"description": (
"A hefty leather-bound tome open to an interesting passage."
),
"title": (
"The book is open to a page that reads:"
),
"message": (
"At the edge of the woods is a cave that is home to a three "
"headed dragon, each with a different temperament. ",
"Legend says that if you happen upon the dragon sleeping, the "
"brave may pet one of its three heads. ",
"Choose the right head and you will be rewarded with great "
"fortunes. ",
"But beware, choose poorly and it will surely mean your doom!",
),
},
"gems": {
"key": "gems",
"name": "gems",
"description": (
"A pile of sparkling gems."
),
},
}
# ## Message functions #######################################################
def header(title):
"""Print a header"""
print()
write(fx.bold(title))
print()
def wrap(text, indent=1):
"""Print wrapped and indented text."""
# calculate the indentation
margin = (MARGIN * " ") * indent
# if a string was passed, turn it into a single item tuple
if isinstance(text, str):
text = (text,)
# make an empty list for the wrapped blocks
blocks = []
# iterate over items
for stanza in text:
# wrap the text
paragraph = textwrap.fill(
stanza,
WIDTH,
initial_indent=margin,
subsequent_indent=margin,
)
blocks.append(paragraph)
# print the wrapped text
print(*blocks, sep="\n\n")
def write(text, indent=1):
"""Print an indented line of game text."""
print(MARGIN * " ", text, sep="")
def error(message):
"""Print an error message."""
print(f"{fg.red('! Error')} {message}\n")
def debug(message):
"""Print a debug message if in debug mode."""
if not DEBUG:
return
print(fg.lightblack(f"# {message}"))
def abort(message):
"""Print a fatal error message then exit the game."""
error(message)
exit(1)
def health_bar():
"""Print a progress bar showing player health"""
print()
write(f"Health {BAR(PLAYER['health'])}")
def prompt():
"""Display the input prompt and return the user input string."""
# fix asciinema screencast rendering
# go up a line then clear it
print(sc.move_up(1), clear_line(), sep="", end="")
return input(fg.cyan("> ")).strip()
# ## Data functions ##########################################################
def get_place(key=None):
"""Return the place information from the PLACES dictionary, either
associated with key, or if none is passed, where the user is
currently at. """
# get the current player's place if key is not passed
if not key:
key = PLAYER["place"]
# get the place info
place = PLACES.get(key)
# this should never happen if we write the code correctly
# but just in case there is no key in PLACES matching
# the new name, print an error
if not place:
abort(f"Woops! The information about {key!r} seems to be missing.")
return place
def get_item(key):
"""Return item information from ITEMS dictionary associated with key. If no
item is found, print an error message and return None."""
item = ITEMS.get(key)
if not item:
abort(f"Woops! The information about {key!r} seems to be missing.")
return item
def health_change(amount: int):
"""Add the following (positive or negative) amount to health, but limit to 0-100"""
PLAYER["health"] += amount
# don't let health go below zero
if PLAYER["health"] < 0:
PLAYER["health"] = 0
# cap health
if PLAYER["health"] > MAX_HEALTH:
PLAYER["health"] = MAX_HEALTH
def inventory_change(key, quantity=1):
"""Add item to player inventory."""
PLAYER["inventory"].setdefault(key, 0)
PLAYER["inventory"][key] += quantity
# remove from inventory dictionary if quantity is zero
if not PLAYER["inventory"][key]:
PLAYER["inventory"].pop(key)
def place_add(key):
"""Add an item to the current place."""
# get the current place
place = get_place()
# add the item key to the place items list
place.setdefault("items", [])
if key not in place["items"]:
place["items"].append(key)
def place_remove(key):
"""Remove an item from the current place."""
# get the current place
place = get_place()
# remove from place
if key in place.get("items", []):
place["items"].remove(key)
# ## Validation functions ####################################################
def player_has(key, qty=1):
"""Return True if the player has at least qty item(s) associated with key in
their inventory."""
return key in PLAYER["inventory"] and PLAYER["inventory"][key] >= qty
def place_has(item):
"""Return True if current place has a particular item."""
place = get_place()
return item in place.get("items", [])
def place_can(action):
"""Return True if the current place supports a particular action."""
place = get_place()
return action in place.get("can", [])
def is_for_sale(item):
"""Return True if item is for sale (has a price)."""
return "price" in item
# ## Action functions ########################################################
def do_shop():
"""List the items for sale."""
if not place_can("shop"):
error("Sorry, you can't shop here.")
return
place = get_place()
header("Items for sale.")
for key in place.get("items", []):
item = get_item(key)
if not is_for_sale(item):
continue
write(
f'{item["name"]:<13} {item["description"]:<45} '
f'{abs(item["price"]):>2} gems'
)
print()
def do_quit():
"""Exit the game."""
write("Ok, goodbye.\n")
quit()
def do_look():
"""Look at the current place"""
debug("Trying to look around.")
# look up where the player is now
place = get_place()
# print information about the current place
header(f"{place['name']}")
wrap(place["description"])
# get the items in the room
items = place.get("items", [])
if items:
# for each of the place items
# get the info from the ITEMS dictionary
# and make a list of item names
names = []
for key in items:
item = get_item(key)
names.append(item["name"])
# remove the last name from the list
last = names.pop()
# construct a sentence that looks like one of:
# x, x and y
# x and y
# y
text = ", ".join(names)
if text:
text += " and "
text += last
# print the list of items.
print()
wrap(f"You see {text}.\n")
# add a blank line
print()
# print what is in each direction from here
for direction in ("north", "east", "south", "west"):
name = place.get(direction)
if not name:
continue
destination = get_place(name)
write(f"To the {direction} is {destination['name']}.")
def do_examine(args):
"""Look at an item in the current place."""
debug(f"Trying to examine: {args}")
# make sure the player said what they want to examine
if not args:
error("What do you want to examine?")
return
# get the item entered by the user and make it lowercase
name = args[0].lower()
# make sure the item is in this place or in the players inventory
if not (place_has(name) or player_has(name)):
error(f"Sorry, I don't know what this is: {name!r}.")
return
# get the item dictionary
item = get_item(name)
# print the item information
header(item["name"].title())
# print the price if we're in the market
if place_can("shop") and place_has(name) and is_for_sale(item):
write(f"{abs(item['price'])} gems".rjust(WIDTH - MARGIN))
print()
# print the quantity if the item is from inventory
elif player_has(name):
write(f"(x{PLAYER['inventory'][name]})".rjust(WIDTH - MARGIN))
print()
wrap(item["description"])
def do_go(args):
"""Move to a different place"""
debug(f"Trying to go: {args}")
# make sure the player included a direction
if not args:
error("Which way do you want to go?")
return
# get the direction from arguments
# and make it lowercase
direction = args[0].lower()
# make sure it's a valid direction
if direction not in ('north', 'south', 'east', 'west'):
error(f"Sorry, I don't know how to go: {direction}.")
return
# look up where the player is now
old_place = get_place()
# look up what is in that direction from here
new_name = old_place.get(direction)
# print an error if there is nothing in that direction
if not new_name:
error(f"Sorry, you can't go {direction} from here.")
return
# look up the place information
new_place = get_place(new_name)
# move the player to the new place
PLAYER["place"] = new_name
# print information about the new place
header(f"{new_place['name']}")
wrap(new_place["description"])
def do_take(args):
"""Pick up an item and add it to inventory."""
debug(f"Trying to take: {args}")
# make sure the player typed an item
if not args:
error("What do you want to take?")
return
# get the item name from arguments
# and make it lowercase
name = args[0].lower()
# make sure the item is in this place
if not place_has(name):
error(f"Sorry, I don't see a {name!r} here.")
return
# get the item information
item = get_item(name)
if not item.get("can_take"):
error(f"You try to pick up {name!r}, but you find you aren't able to lift it.")
return
# add to inventory
inventory_change(name)
# remove from place
place_remove(name)
wrap(f"You pick up {item['name']} and put it in your pack.")
def do_inventory():
"""Show the players inventory"""
debug("Trying to show inventory.")
health_bar()
header("Inventory")
if not PLAYER["inventory"]:
write("Empty.")
return
for name, qty in PLAYER["inventory"].items():
item = get_item(name)
write(f"(x{qty:>2}) {item['name']}")
print()
def do_drop(args):
"""Remove an item from inventory"""
debug(f"Trying to drop: {args}.")
# make sure the player typed an item
if not args:
error("What do you want to drop?")
return
# get the item name from arguments
# and make it lowercase
name = args[0].lower()
# make sure the item is in inventory
if not player_has(name):
error(f"You don't have any {name!r}.")
return
# get the amount currently in inventory
qty = PLAYER["inventory"][name]
# remove from player inventory
inventory_change(name, -qty)
# add to place items
place_add(name)
# print a message
wrap(f"You set down the {name}.")
def do_buy(args):
"""Purchase an item."""
debug(f"Trying to buy: {args}.")
if not place_can("buy"):
error("Sorry, you can't buy things here.")
return
# make sure the player typed an item
if not args:
error("What do you want to buy?")
return
# get the item name from arguments
# and make it lowercase
name = args[0].lower()
# make sure the item is in this place
if not place_has(name):
error(f"Sorry, I don't see a {name!r} here.")
return
# get the item information
item = get_item(name)
if not is_for_sale(item):
error(f"Sorry, {item['name']} is not for sale.")
return
price = abs(item["price"])
if not player_has("gems", price):
gems = PLAYER["inventory"].get("gems", 0)
error(
f"Sorry, you can't afford {item['name']} "
f"because it costs {price} and you only have {gems}."
)
return
# remove gems from inventory
inventory_change("gems", -price)
# add item to inventory
inventory_change(name)
# remove item from place
place_remove(name)
wrap(f"You bought {item['name']}.")
def do_read(args):
"""Read an item with a message."""
debug(f"Trying to read: {args}")
# make sure the player said what they want to read
if not args:
error("What do you want to read?")
return
# get the item entered by the user and make it lowercase
name = args[0].lower()
# make sure the item is in this place or in the players inventory
if not (place_has(name) or player_has(name)):
error(f"Sorry, I don't know what this is: {name!r}.")
return
# get the item dictionary
item = get_item(name)
# make sure it is an item you can read
if "message" not in item:
error(f"Sorry, I can't read {name!r}.")
return
# print the item header
title = item.get("title", "It reads...")
header(title)
# print the item message
wrap(item["message"], indent=3)
def do_pet(args):
"""Pet dragons"""
debug(f"Trying to pet: {args}")
# make sure they are somewhere they can pet dragons
if not place_can("pet"):
error("You can't do that here.")
return
def main():
header("Welcome!")
while True:
debug(f"You are at: {PLAYER['place']}")
reply = prompt()
args = reply.split()
if not args:
continue
command = args.pop(0)
debug(f"Command: {command!r}, args: {args!r}")
if command in ("q", "quit", "exit"):
do_quit()
elif command in ("shop"):
do_shop()
elif command in ("g", "go"):
do_go(args)
elif command in ("x", "exam", "examine"):
do_examine(args)
elif command in ("l", "look"):
do_look()
elif command in ("t", "take", "grab"):
do_take(args)
elif command in ("i", "inventory"):
do_inventory()
elif command in ("r", "read"):
do_read(args)
elif command == "drop":
do_drop(args)
elif command == "buy":
do_buy(args)
elif command == "pet":
do_pet(args)
else:
error("No such command.")
continue
# print a blank line no matter what
print()
# exit the game if player has no health
if not PLAYER["health"]:
write("Game over.\n")
quit()
if __name__ == "__main__":
main()