1"""The Lost Library: a small text adventure.
2
3Find the brass key, light your way, collect the golden manuscript from the vault and
4return to the entrance hall. Commands: look, go <direction> (or n/s/e/w/u/d), take <item>,
5drop <item>, inventory, read <item>, help, quit.
6"""
7import sys
8from dataclasses import dataclass, field
9
10DIRECTIONS = {"n": "north", "s": "south", "e": "east", "w": "west", "u": "up", "d": "down"}
11
12
13@dataclass
14class Room:
15 name: str
16 description: str
17 exits: dict[str, str]
18 items: list[str] = field(default_factory=list)
19 dark: bool = False
20 locked_by: str | None = None
21
22
23def build_world() -> dict[str, Room]:
24 return {
25 "hall": Room("Entrance Hall", "Dusty portraits line the walls. A grand staircase leads up.",
26 {"north": "reading", "east": "kitchen", "up": "gallery"}),
27 "reading": Room("Reading Room", "Rows of desks face a fireplace. A heavy door stands to the north.",
28 {"south": "hall", "north": "vault"}, ["candle"]),
29 "kitchen": Room("Old Kitchen", "Copper pots hang above a cold stove.", {"west": "hall"}, ["matches", "apple"]),
30 "gallery": Room("Gallery", "Moonlight falls on empty frames. Something glints under a bench.",
31 {"down": "hall"}, ["brass key", "note"]),
32 "vault": Room("Vault", "Shelves of locked cases. In the centre, a glass box holds a golden manuscript.",
33 {"south": "reading"}, ["golden manuscript"], dark=True, locked_by="brass key"),
34 }
35
36
37READABLE = {
38 "note": "The note says: 'The vault opens for brass, but sees only by flame.'",
39 "golden manuscript": "Gold letters spell out: 'Knowledge is the only treasure that grows when shared.'",
40}
41
42
43def ask(prompt: str) -> str | None:
44 try:
45 line = input(prompt)
46 except EOFError:
47 print()
48 return None
49 if not sys.stdin.isatty():
50 print(line)
51 return line.strip().lower()
52
53
54class Game:
55 def __init__(self):
56 self.rooms = build_world()
57 self.here = "hall"
58 self.inventory: list[str] = []
59 self.moves = 0
60 self.finished = False
61
62 @property
63 def lit(self) -> bool:
64 return "candle" in self.inventory and "matches" in self.inventory
65
66 def describe(self) -> None:
67 room = self.rooms[self.here]
68 print(f"\n== {room.name} ==")
69 if room.dark and not self.lit:
70 print("It is pitch dark. You can't see a thing.")
71 return
72 print(room.description)
73 if room.items:
74 print(f"You see: {', '.join(room.items)}.")
75 print(f"Exits: {', '.join(room.exits)}.")
76
77 def go(self, direction: str) -> None:
78 direction = DIRECTIONS.get(direction, direction)
79 target = self.rooms[self.here].exits.get(direction)
80 if not target:
81 print("You can't go that way.")
82 return
83 room = self.rooms[target]
84 if room.locked_by and room.locked_by not in self.inventory:
85 print("The heavy door is locked.")
86 return
87 if room.locked_by:
88 print(f"You unlock the door with the {room.locked_by}.")
89 room.locked_by = None
90 self.here = target
91 self.moves += 1
92 self.describe()
93 if self.here == "hall" and "golden manuscript" in self.inventory:
94 print(f"\nYou carry the golden manuscript out into the daylight. You win in {self.moves} moves!")
95 self.finished = True
96
97 def take(self, item: str) -> None:
98 room = self.rooms[self.here]
99 if room.dark and not self.lit:
100 print("You fumble around in the dark but find nothing.")
101 elif item in room.items:
102 room.items.remove(item)
103 self.inventory.append(item)
104 print(f"Taken: {item}.")
105 else:
106 print(f"There is no {item} here.")
107
108 def drop(self, item: str) -> None:
109 if item not in self.inventory:
110 print(f"You don't have {item}.")
111 return
112 self.inventory.remove(item)
113 self.rooms[self.here].items.append(item)
114 print(f"Dropped: {item}.")
115
116 def command(self, line: str) -> bool:
117 verb, _, rest = line.partition(" ")
118 if verb in DIRECTIONS or verb in DIRECTIONS.values():
119 self.go(verb)
120 elif verb == "go" and rest:
121 self.go(rest)
122 elif verb == "look":
123 self.describe()
124 elif verb in ("take", "get") and rest:
125 self.take(rest)
126 elif verb == "drop" and rest:
127 self.drop(rest)
128 elif verb in ("inventory", "i"):
129 print(f"You carry: {', '.join(self.inventory) or 'nothing'}.")
130 elif verb == "read" and rest:
131 print(READABLE.get(rest, "There is nothing to read on that.") if rest in self.inventory else f"You don't have {rest}.")
132 elif verb == "help":
133 print("Commands: look, go <dir>, n/s/e/w/u/d, take <item>, drop <item>, inventory, read <item>, quit")
134 elif verb == "quit":
135 return False
136 else:
137 print("I don't understand that. Type 'help'.")
138 return not self.finished
139
140
141def main() -> None:
142 game = Game()
143 print("THE LOST LIBRARY")
144 game.describe()
145 while True:
146 line = ask("> ")
147 if line is None or not game.command(line):
148 break
149 if not game.finished:
150 print(f"You leave the library after {game.moves} moves. The manuscript remains hidden.")
151
152
153if __name__ == "__main__":
154 main()