#!/usr/bin/python3
"""Space Station Snack Run -- a one-file, terminal exploration teaching library.

Save this file beside your own my_game.py:

    import snack_station

    game = snack_station.Game(player_name="Captain Crumbs")
    game.say("Welcome aboard! Try changing my name.")
    game.run()

Run: python3 my_game.py       Demo: python3 snack_station.py
Docs (no terminal needed): python3 snack_station.py --guide
Student workbook:          python3 snack_station.py --lessons
Copyable programs:      python3 snack_station.py --examples
Controls: arrows/WASD move; E interact; I inspect; B inventory; M log;
          ? help; . wait one turn; Q quit. Escape cancels menus.

No quest, hunger clock, enemies, score target, or forced ending is built in.
Only standard-library modules are needed. Python 3.12 or later; curses on POSIX.
Importing this module never opens a terminal, prints, or asks for input.

STUDENT DOCUMENTATION is below. ENGINE INTERNALS follow the examples.
"""

import argparse
import copy
import difflib
import heapq
import sys
import textwrap
from collections import deque

DECK_NAMES = (
    "Habitation & Snack Court", "Cargo & Docking", "Hydroponics & Gardens",
    "Engineering & Maintenance", "Communications & Observation",
)
DIRECTIONS = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}

GUIDE = r"""
SPACE STATION SNACK RUN: STUDENT GUIDE
====================================
Put snack_station.py next to your program. Import it, create Game(), configure
it and register functions, then call game.run(). Registration does not execute
your function. The engine calls it later when the corresponding event happens.
There are no required decorators, subclasses, annotations, or threads.
Use --examples for complete, independent programs. Start with example 1.

CONTROLS AND SCREEN
Arrows or WASD: move. E: interact with an object on your tile or one cardinal
step away. I: inspect nearby objects, IDs, and the tile ahead. B: inventory.
M: scrollable message history. ?: help and legend. .: wait one player turn.
Q: exit from exploration, menus, and viewers. Escape: cancel/close a menu.
In a text question, Q is ordinary text; Escape cancels and F10 exits.
Menus use Up/Down, PageUp/PageDown, Home/End, Enter, or 1-9 for visible entries.
Movement keys in menus never move the astronaut. Resizing never takes a turn.
Below 60 columns by 16 rows, play pauses and Q still exits. Enlarge to resume.
At 80x24 the header, map, legend and four recent wrapped message lines fit.
The astronaut remains at (viewport_height//2, viewport_width//2), using the
lower/right center cell when even. Blank space appears beyond world boundaries.
All essential artwork is ASCII; color is unnecessary. Non-ASCII student text
is shown as '?' in the interface, but inventory/flags retain the original text.

QUICK API REFERENCE (all methods belong to your game)
Game(player_name='Astronaut', player_symbol='@')
  Name is text. Symbol is one visible ASCII character; change these attributes
  before run(), or inside callbacks. Invalid symbols produce a clear error.
say(text)                         Append a message; also works before run().
choose(prompt, options)            Nonempty list/tuple of distinct text options.
                                  Returns selected text, or None on Escape.
ask(prompt)                       Returns typed text (possibly ''), or None.
                                  Editing: Backspace; maximum 200 characters.
  Prompts stay inside curses. Outside run(), queue_answers(...) supplies scripted
  answers for tests; otherwise prompts raise RuntimeError (never call input()).
give(item, quantity=1)             Add a positive integer quantity of text item.
has(item, quantity=1)              True if inventory contains enough.
remove(item, quantity=1)           True on success; False if insufficient; atomic.
                                  Zero counts disappear from inventory.
set_flag(name, value)              Remember a student variable of any kind.
get_flag(name, default=None)       Read it; missing flags return default.
set_object(id, name=..., symbol=..., description=..., enabled=...)
                                  Change only supplied properties. Disabled
                                  objects are hidden, nonblocking, unusable.
                                  Collected snacks cannot be re-enabled.
open_door(id) / close_door(id)      Real collision changes; False if closing on
                                  player or another enabled object, else True.
                                  Use these, not symbol changes, to open doors.
teleport(location)                Move to nearest vacant reachable floor near
                                  a named location; no turn, safe for testing.
add_object(id, location, name=None, symbol='?', description='Not programmed yet.')
add_snack(id, location, name=None, symbol='*', description='An unclaimed snack.')
                                  IDs must be unique. Finds vacant reachable
                                  floor near location, never inside a wall.
                                  Returns id. Items are passable; E picks up.
move_object(id, direction)         'up', 'down', 'left', 'right'. Returns success;
                                  respects walls, doors, bounds, objects, player.
                                  Intended for robots, not lifts/doors/docks.
get_object(id)                    Independent dictionary of object properties.
get_delivery(id)                  Independent dictionary with contents mapping,
                                  dock, vessel, state, and arrival_turn.
list_objects() / list_locations() Return lists of valid IDs/names.
after(turns, callback)             Schedule callback(game) once, after a positive
                                  integer number of FUTURE completed turns.
on_turn(callback)                 Add callback(game) after every completed turn.
on_interact(id, callback)          callback(game, object_id) replaces that object's
                                  default interaction. One handler per object;
                                  registering again replaces the old handler.
on_pickup(id, callback)            callback(game, snack_id), only for snacks.
on_delivery(callback)             callback(game, delivery_id) when cargo arrives.
on_collect(callback)              callback(game, delivery_id) after cargo pickup.
on_travel(callback)               callback(game, from_deck, to_deck) after lift.
                                  These three and on_turn append listeners in
                                  registration order. Callback returns ignored.
request_delivery(dock_id, contents, delay=3, vessel='Alien courier')
                                  contents is list/tuple of item names OR a
                                  dictionary {item: positive_quantity}.
                                  Returns stable delivery ID, e.g. delivery_1.
set_lift_destinations(lift_id, deck_ids)
                                  List of integer deck IDs 0..4 (empty locks it).
                                  Only that lift's departures are restricted.
win(message='You win!')            Set won=True and show message once. Exploration
                                  continues; students decide what winning means.
step(action)                      Headless action: up/down/left/right, wait, or
                                  an object ID. Returns whether a turn happened.
camera_origin(width, height)      Testing helper: top-left world (x, y) of the
                                  centered viewport; never clamps at boundaries.
queue_answers(*answers)            Test prompts without curses. Each answer must
                                  be an offered string (or None to cancel).
                                  For ask(), any text or None is accepted.

Public read-only-by-convention state: turn, deck (0..4), x, y, inventory, flags,
messages, won. Change inventory/position/objects through helpers. get_object and
get_delivery return copies. Internal maps and registries are not the student API.
All state belongs to one Game; separate instances do not share mutable data.
Misspelled IDs include suggestions. Invalid types/options fail early. Student
exceptions are NOT swallowed: curses restores the terminal, then Python prints
the original traceback including your program's filename and line number.

TURNS AND EVENT ORDER (no wall-clock timers)
A successful move, wait, or nearby enabled-object interaction takes ONE turn.
A wall/closed door, absent/disabled/distant object, invalid key, or canceled
object-selection menu takes NONE. Help, inspection, inventory, log, resizing,
configuration calls, and typing/viewing menus take none by themselves.
Once you select an object to interact with, that interaction takes one turn even
if you cancel its inner question/menu. A canceled lift menu also takes one turn.
1. Perform the action. Snack: mark collected and hide it, add inventory, then
   call its pickup handler. Interact handlers replace defaults, INCLUDING pickup
   if registered on a snack. Pickup handlers extend default pickup instead.
2. Increment turn exactly once.
3. Run due scheduled functions, ordered by due turn then registration order.
4. Run a snapshot of the turn listeners in registration order.
Callbacks may use helpers but must not recursively call step() or run().
after(1, f) before run fires after the first completed action. Inside an
interaction/pickup/travel callback it fires after the NEXT completed action,
not at the end of the action currently executing. Inside timers/turn listeners
it likewise waits one further completed action. after(3, f) waits three such
future actions. A scheduled function registering another delay never runs it
in the same turn. Blocked movement never advances deliveries or timers.

DELIVERIES AND LIFTS
The terminal is idle until you register a handler. request_delivery creates
pending cargo; after delay future turns it becomes arrived, logs the vessel,
and calls arrival listeners. No network, subprocess, or spaceship simulator.
Interact with the named dock to collect its oldest ARRIVED delivery (FIFO by
arrival order). Pending cargo cannot be collected and does not block arrived
cargo. One interaction collects one delivery, sets state to collected, adds
ALL contents, then calls collection listeners. Repeated interaction cannot
collect it again. Cargo resides at the physical dock, not an unreachable tile.
Disabling a dock hides access but retains its deliveries until re-enabled.
All three lift shafts connect all five decks by default. A destination must
have an enabled landing lift; arrivals choose clear floor beside that lift.
Handlers may restrict destinations or observe travel. Same-deck travel is
not offered. Lift use never changes the camera centering rule.

WORLD, IDS, AND CLASSROOM SHORTCUTS
Five 180x90 decks have loop corridors, authored rooms of varied sizes and shapes, furniture/windows,
three lift shafts, distributed snacks and distinct equipment. Decorations are
not objects: # walls, = windows, b beds, c chairs, t tables, % cargo, v plants,
~ water, o machinery, : cables, ^ dishes. Signs label rooms. Furniture blocks;
room signs/windows are walls. Dots are floor; blanks outside are not. I explains
nearby objects with IDs and the last faced tile. ? displays the whole legend.

Named locations (teleport/add_* use these; no coordinates needed):
start, snack_court, classroom, optional_room, cargo_dock, cargo_dock_b,
garden, engineering_lift, observation, and every built-in object ID. New objects do not automatically create
locations. Every deck also has deck_0_start through deck_4_start. Legacy room aliases use
room_D_R_C (deck D=0..4, room row R=0..3, column C=0..4).
optional_room always lands OUTSIDE the optional locked lounge.

Near start: alien_terminal (T), vending_machine (V), service_robot (R),
alien_plant (P), engineering_switch (!), access_panel (A), moon_chips (*).
optional_door (+ closed, / open) gates a side room; essential routes stay open.
Dock objects: cargo_dock (D), cargo_dock_b (D).
Other snacks: quantum_pickle, comet_cake, nebula_noodles, vacuum_popcorn.
Other equipment: cargo_console, garden_pet, power_console, observation_scope.
Lifts: habitation_lift, cargo_lift, hydroponics_lift, engineering_lift,
communications_lift (forward shaft); lift_D_mid and lift_D_aft on each deck.
Use game.list_objects() and game.list_locations() for the full current lists.
teleport('cargo_dock') is a convenient classroom retrieval shortcut. Teleports
and configuration do not consume turns; press . to wait for a delivery.

TRY CHANGING THIS
Change a snack name or welcome message first. Then add a conditional on a flag,
ask a different question, or change a delivery delay. Reuse the SAME Game.
The --examples programs are alternatives. To combine them, keep one import,
one Game(), and one run() LAST; put configuration and function registrations
before run(). Different handlers on the same object replace each other.
"""

EXAMPLE_PROGRAMS = (
    ("1. Name and welcome", '''import snack_station

game = snack_station.Game(player_name="Captain Crumbs")
game.say("Welcome! The station is yours to explore.")
# Try changing the name, sprite, or message.
game.run()
'''),
    ("2. A snack reaction", '''import snack_station

game = snack_station.Game()
def chips(game, snack_id):
    game.say("These chips taste like Tuesday!")
    game.set_flag("chips_eaten", True)
# Inventory already contains Moon chips when this runs.
game.on_pickup("moon_chips", chips)
# Try giving a souvenir with game.give("Tuesday badge").
game.run()
'''),
    ("3. Program the vending machine", '''import snack_station

game = snack_station.Game()
def vending(game, object_id):
    snack = game.choose("Fabricate what?", ["Comet cake", "Nebula noodles"])
    if snack is not None:
        game.give(snack)
        game.say("One suspiciously warm " + snack + "!")
game.on_interact("vending_machine", vending)
# Try adding a third choice or requiring an ingredient.
game.run()
'''),
    ("4. An item opens the optional door", '''import snack_station

game = snack_station.Game()
def chips(game, snack_id):
    game.give("crumb key")
    game.say("A key fell out of the packet. Find the access panel.")
def panel(game, object_id):
    if game.has("crumb key"):
        game.open_door("optional_door")
        game.say("The optional lounge is open!")
    else:
        game.say("Bring a crumb key. Try the Moon chips.")
game.on_pickup("moon_chips", chips)
game.on_interact("access_panel", panel)
# Try replacing the key check with game.ask("Password?").
game.run()
'''),
    ("5. Alien snack delivery", '''import snack_station

game = snack_station.Game()
def contact(game, object_id):
    game.say("Transmission from the Pickle Nebula!")
    snack = game.choose("Order?", ["Quantum pickle", "Comet cake"])
    if snack is not None:
        delivery_id = game.request_delivery("cargo_dock", [snack], delay=3,
                                            vessel="The Flying Colander")
        game.say("Order accepted: " + delivery_id + ". Wait three turns.")
def arrived(game, delivery_id):
    game.say("Visit cargo_dock and press E to retrieve your order.")
    # Classroom shortcut; delete this teleport for a real expedition.
    game.teleport("cargo_dock")
def collected(game, delivery_id):
    cargo = game.get_delivery(delivery_id)
    game.say("Received: " + ", ".join(cargo["contents"]))
game.on_interact("alien_terminal", contact)
game.on_delivery(arrived)
game.on_collect(collected)
# Interact with T, then press . three times. Try changing the vessel/delay.
game.run()
'''),
    ("6. A student-defined secret", '''import snack_station

game = snack_station.Game()
def chips(game, snack_id):
    game.give("crumb key")
def order(game, object_id):
    if not game.get_flag("ordered", False):
        game.request_delivery("cargo_dock", ["Quantum pickle"], delay=2)
        game.set_flag("ordered", True)
        game.say("The secret order is on its way.")
    else:
        game.say("The courier remembers you.")
def arrived(game, delivery_id):
    game.teleport("cargo_dock")  # Remove to explore the cargo deck yourself.
def panel(game, object_id):
    if game.has("crumb key") and game.has("Quantum pickle"):
        game.open_door("optional_door")
        game.set_flag("secret_open", True)
        game.win("You founded the Intergalactic Pickle Club!")
    else:
        game.say("The club needs a crumb key AND a Quantum pickle.")
game.on_pickup("moon_chips", chips)
game.on_interact("alien_terminal", order)
game.on_delivery(arrived)
game.on_interact("access_panel", panel)
# After collecting cargo, use game.teleport("start") in your program or a
# callback for quick testing; otherwise ride a lift home. Try another secret.
game.run()
'''),
)
EXAMPLES = "\n\n".join(title + "\n" + "-" * len(title) + "\n" + code
                           for title, code in EXAMPLE_PROGRAMS)

GUIDE += r"""
EXPANDED STATION: CODE OPENS THE SHIP
Decks now mix unequal chambers, garden domes and broad galleries. On each deck,
hatch_D_0 and hatch_D_1 seal service branches; hatch_D_N_panel is their control.
Register on_interact on a panel, then call open_door with the hatch ID. The
branch contains hatch_D_N_snack. Door footprints block every doorway cell.
The second hatch requires visiting the corresponding entry in
list_destinations() at least once (deck 0 home_orbit, then pickle_nebula, crumb_moon,
sugar_comet, salvage_ring). Doors stay unlocked until explicitly closed.

Engineering has a huge circular engine hall with a central containment core.
engine_lock is outside; engine_door is its only normal entrance. Inside are
reactor_control, cooling_control, containment_control and engine_start.
set_system(system_id, active=True): known systems are reactor, cooling,
containment, navigation, helm. system_active(id) reads these or 'engine'.
start_engine() returns False until engine_door has been opened and all three
engine systems configured. stop_engine() stops it; disabling an engine system
also stops it. bridge_navigation and bridge_helm are inert programmable terminals
on deck 4. travel(destination_id) requires engine, navigation and helm; returns
False if unavailable or already there. Successful travel changes station_location
and observation_scope. It takes no extra turn within an interaction. This is
named-destination travel, not flight simulation or an exterior map.
request_delivery(..., origin=destination_id) optionally requires the current
station location at request time. Accepted couriers follow subsequent travel.
There is no automatic solution: students decide passwords, fuel items, menus,
and objectives. teleport remains a deliberate debugging override for locked areas.
New component IDs also have named locations. engine_room lands outside the lock.
Each second branch also has vault_D_panel, vault_D_door, vault_D_snack. Register
its panel independently; the outer hatch does not open the inner lock.
shortcut_D_panel controls shortcut_D_door in a narrow maintenance shortcut.
Extra idle equipment: irrigation_console, quarantine_panel, tractor_console,
gravity_console, signal_decoder. Program these with the SAME interaction API.
Read python3 snack_station.py --lessons for step-by-step tasks and expected results.
"""

EXAMPLE_PROGRAMS += (("7. Open a hatch", '''import snack_station
game = snack_station.Game()
def unlock(game, object_id):
    if game.ask("Secret word?") == "crumbs":
        game.open_door("hatch_0_0")
game.on_interact("hatch_0_0_panel", unlock)
game.run()
'''), ("8. Configure propulsion and travel", '''import snack_station
game = snack_station.Game()
def unlock(game, object_id):
    game.open_door("engine_door")
def reactor(game, object_id): game.set_system("reactor")
def cooling(game, object_id): game.set_system("cooling")
def field(game, object_id): game.set_system("containment")
def start(game, object_id): game.start_engine()
def navigation(game, object_id): game.set_system("navigation")
def helm(game, object_id):
    game.set_system("helm")
    destination = game.choose("Set course", game.list_destinations())
    if destination is not None: game.travel(destination)
game.on_interact("engine_lock", unlock)
game.on_interact("reactor_control", reactor)
game.on_interact("cooling_control", cooling)
game.on_interact("containment_control", field)
game.on_interact("engine_start", start)
game.on_interact("bridge_navigation", navigation)
game.on_interact("bridge_helm", helm)
# Try requiring an inventory item before enabling the reactor.
game.run()
'''))
EXAMPLES = "\n\n".join(title + "\n" + code for title, code in EXAMPLE_PROGRAMS)

WORKBOOK = r"""
SPACE STATION SNACK RUN: STUDENT WORKBOOK
=======================================

0. SET UP YOUR TWO FILES
Download snack_station.py. In the SAME folder create my_game.py. Do not name
it snack_station.py, random.py, or curses.py: those names hide imported modules.
Put this in my_game.py (four spaces indent any code inside a function):

    import snack_station
    game = snack_station.Game(player_name="Captain Crumbs")
    game.say("My station is open for snacks!")
    game.run()

Save it. In the terminal, change to that folder and run python3 my_game.py.
If the terminal is too short, drag its top edge upward. Q exits. Stop the game,
edit, SAVE, and run again to see changes. A new run resets inventory and flags;
this library does not save progress. Your source code is your saved creation.

You can read the workbook without playing: python3 snack_station.py --lessons
API reference: --guide. Complete independent programs: --examples.
Each example starts with import and ends with game.run(). Copy ONE whole
program at a time. To combine programs, use just one Game() and one run(), last.
Put registrations before run(). They tell the engine WHAT function to call later.

1. GET A VISIBLE RESULT
Try changing player_name, player_symbol="&", and the welcome message.
Expected: the header or sprite changes as soon as your new program starts.
Move with arrows/WASD. The world scrolls while your astronaut stays centered.
E uses nearby objects. I identifies them. B shows your bag. M shows old messages.
? explains the symbols. . waits a turn. Escape closes a menu; Q exits.
When several objects are nearby, E offers a menu with their readable IDs.
Menus use arrows and Enter, or the displayed numbers. Menu keys never move you.

2. YOUR FIRST CALLBACK: A SNACK REACTION
Copy example 2. Moon chips (*) are one step below the starting astronaut.
Press E and select Moon chips if a menu appears. Expected: B contains Moon chips, the star disappears,
and the funny message appears. A second E cannot collect the packet again.
The engine adds inventory BEFORE calling chips(game, snack_id).
The arguments are supplied by the engine. Register chips, NOT chips().
Try changing the message, giving a badge, or incrementing your own flag:

    count = game.get_flag("packets", 0)
    game.set_flag("packets", count + 1)

Use those lines inside your pickup function. Callback returns are ignored.

3. A MACHINE THAT ASKS A QUESTION
Copy example 3. Walk one step up from the starting position, press E, and select
the Snack fabricator. Choose an option. Expected: B contains your selection.
Escape returns None; always check that before giving an item.
Try requiring an ingredient: if game.remove("Moon chips"): ...
remove returns False and removes nothing if the ingredient is missing.
Use game.ask("Password?") for typed text, never Python input() during play.
Inside a text question Q types Q; Escape cancels and F10 exits the game.

4. OPEN A REAL DOOR WITH CODE
Copy example 7. Add game.teleport("hatch_0_0_panel") just before game.run()
for a quick test. The panel is A and the closed corridor hatch is +.
Press E on the panel, type crumbs, and press Enter. Expected: the hatch becomes
/ and you can walk through it. The branch contains a sealed bonbon (*).
Try a wrong password first: the hatch stays solid. Try an inventory requirement
instead of a password, or remember the answer with a flag.

The panel and door have DIFFERENT IDs. Register the panel; open the door.
Every deck has hatch_D_0_panel and hatch_D_1_panel, where D is 0,1,2,3,4.
Their doors are hatch_D_0 and hatch_D_1. The second branch requires a destination
visit (lesson 7). It also contains vault_D_panel, controlling vault_D_door.
The inner vault holds vault_D_snack. Nested locks are independent: opening the
outer hatch does not automatically open the vault. Interact with each panel.
No hidden route or lift bypasses the engine lock or these sealed branches.
There is also shortcut_D_panel controlling shortcut_D_door on each deck.
Its narrow maintenance spine shortens an existing loop, rather than hiding a wing.

5. MAKE A CHANGE HAPPEN LATER
Copy example 9: a greenhouse responds to feeding. Start with an ingredient in
inventory; the example supplies it for testing. Interact with irrigation_console.
Expected: the ingredient disappears; three future turns later a snack appears
near garden. Walk, interact, or press . three times. A wall bump does not count.
The harvest_started flag prevents duplicate jobs, even after the harvest.
Try changing the recipe, delay, and snack name. Change both add_snack's unique
ID and its displayed name when creating a different permanent snack.
A collected snack cannot be re-enabled: add a NEW snack with a new ID instead.

6. UNLOCK AND CONFIGURE THE ENGINE
Copy example 8. This is a starting solution; replace its simple actions with
your own checks. Add game.teleport("engine_lock") before game.run() for testing.
A large circular hall lies beyond the blast lock. Walk beside the exterior
engine_lock terminal and press E. Expected: all three cells of engine_door open.
Enter the hall. The central core is solid machinery; walk around its ring.
The three unusual assemblies have controls immediately beside them:

    reactor_control      -> game.set_system("reactor")
    cooling_control      -> game.set_system("cooling")
    containment_control  -> game.set_system("containment")

Use each control, then engine_start. Expected: the start message confirms the
engine is ready. If you start early, it explains what is missing.
start_engine returns True on success, False on unmet prerequisites. Configuration
alone is insufficient: the engine hatch must have been opened at least once.
Closing it later does not shut the engine down. stop_engine() does;
set_system("cooling", False) also stops it. Restart explicitly after repair.
Try requiring a coolant bottle, checking a password, or delaying a warmup using
after. Use game.system_active("engine") to test whether propulsion is running.

7. PROGRAM THE BRIDGE AND MOVE THE STATION
Continue with example 8. Ride a lift to deck 5 (deck ID 4). On the Command bridge,
interact with bridge_navigation, then bridge_helm. Choose pickle_nebula.
Expected: the status shows pickle_nebula and the observation scope describes it.
Trying travel before engine/nav/helm readiness fails with a message and returns
False. The five IDs are home_orbit, pickle_nebula, crumb_moon, sugar_comet,
salvage_ring. game.list_destinations() supplies them to a choice menu.
Travel is a station-location change, not a flight simulator or an exterior map.
Calling travel inside an interaction uses that interaction's one turn.

Visit destinations to enable the second branch hatch on the matching deck:
    deck 0: home_orbit       deck 1: pickle_nebula    deck 2: crumb_moon
    deck 3: sugar_comet      deck 4: salvage_ring
Visiting makes a hatch eligible; it does NOT program its panel or open it.
Register a function that calls open_door for it. Previously unlocked doors stay
open during travel. Visits are remembered for this run; you need not stay there.
Try a menu that offers destinations based on your own flags or inventory.

8. ORDER AND RETRIEVE REMOTE SNACKS
Example 5 demonstrates arrival and collection callbacks. Example 10 additionally
uses origin="pickle_nebula" and must be combined with the engine/bridge setup
as explained in its comments, or configured before play as its test setup shows.
request_delivery returns an ID such as delivery_1. States are pending, arrived,
collected. Menus do not make time pass: take turns or use . to await arrival.
Interact with cargo_dock to receive the oldest ARRIVED shipment, exactly once.
The collection callback runs AFTER all its items are in inventory.
Origin is checked when ordering. An accepted courier follows the station if it
moves before arrival. Different orders at the same dock queue safely.
Try changing the vessel, contents, quantity, delay, or destination.

9. BUILD YOUR OWN SNACK EXPEDITION
Example 11 combines engine setup, destination travel, a branch hatch, an inner
vault, and a student-defined celebration. It adds no automatic quest to the
library: those rules live in your own importing program. Test one piece first.
A useful sequence: open engine -> configure three controls -> start -> enable
navigation -> use helm to visit Pickle Nebula -> cargo deck branch panel ->
inner vault panel -> collect the Forbidden 1 truffle. Read each message.
Try replacing a password with an item exchange or delivery prerequisite.
Other projects: program service_robot with dialogue or move_object; use on_turn
for optional wall-respecting robot movement; make signal_decoder remember a
password; let tractor_console request cargo; connect gravity_console to a hatch.
Same helpers, different stories. There is no required score or forced ending.

TESTING AND TROUBLESHOOTING
- No response? Check spelling with game.list_objects(), I, or --guide. Check
  that your registration is before game.run() and targets the intended panel.
- Unknown ID? Read the suggested names. Labels on screen and IDs differ.
- Function ran immediately? Register function_name, not function_name().
- TypeError in a callback? Interactions/pickups take (game, object_id); timers
  and turn functions take (game); deliveries take (game, delivery_id); lift
  listeners take (game, from_deck, to_deck). Return values are ignored.
- IndentationError? Use consistent four-space indentation inside def/if blocks.
- NameError? Define the function before registering it. Put run() last.
- Changes missing? Save the file, Q out, and restart python3 my_game.py.
- Waiting forever? after waits for player TURNS, not seconds. Press . on floor.
- Duplicates? Set a pending/finished flag BEFORE scheduling work. Use distinct
  object IDs for spawned snacks. One interaction handler per object is retained;
  registering a new one replaces the old one. on_turn listeners accumulate.
- Engine refuses to start? Open engine_door; activate all three engine systems.
  Bridge navigation and helm alone cannot power the station.
- Hatch remains closed? The panel needs a handler. A destination-gated hatch
  additionally needs its destination visited. Check open_door's boolean result.
- Door refuses to close? Move out of its full doorway footprint first.
- Prompt outside play? Put it in a callback. For a headless test, supply answers
  with queue_answers(...); choose returns an offered string or None.
- Need a shortcut? Add game.teleport("engine_lock") or another named location
  just before run(). teleport is intentionally a DEBUG override, even into
  locked areas. It does not itself unlock/configure systems or consume a turn.
- Error traceback? The terminal is restored first. Read your filename and line
  near the end of the traceback. Correct the code and run again.

To test without opening curses, import your library and call game.step("wait")
or game.step("up") or a nearby object ID. No threads or terminal input needed.
Check --guide for the exact event order and validation rules. Optional teacher
check: run python3 -m py_compile my_game.py to check Python syntax before class.
"""

EXAMPLE_PROGRAMS += (
    ('9. A delayed greenhouse recipe', '''import snack_station
game = snack_station.Game()
game.give("Moon chips")
def grow(game, object_id):
    if game.get_flag("harvest_started"):
        game.say("Only one experimental harvest per run.")
    elif game.remove("Moon chips"):
        game.set_flag("harvest_started", True)
        game.after(3, harvest)
        game.say("Growing a snack. Wait three future turns.")
    else:
        game.say("Bring Moon chips.")
def harvest(game):
    game.add_snack("grown_cookie", "garden", name="Photosynthetic cookie")
    game.say("A cookie grew near garden. Find its star and press E.")
game.on_interact("irrigation_console", grow)
game.teleport("irrigation_console")
game.run()
'''),
    ('10. Origin-restricted delivery', '''import snack_station
game = snack_station.Game()
# Test setup. Replace with example 8's physical controls for an expedition.
game.open_door("engine_door")
for system in ["reactor", "cooling", "containment", "navigation", "helm"]:
    game.set_system(system)
game.start_engine()
game.travel("pickle_nebula")
def order(game, object_id):
    if game.station_location != "pickle_nebula":
        game.say("Visit Pickle Nebula first.")
    else:
        game.request_delivery("cargo_dock", {"Brine biscuit": 2}, delay=2,
                              vessel="The Colander", origin="pickle_nebula")
def arrived(game, delivery_id):
    game.say("Cargo ready. Use the dock to collect it.")
game.on_interact("tractor_console", order)
game.on_delivery(arrived)
game.teleport("tractor_console")
game.run()
'''),
)

_expedition = EXAMPLE_PROGRAMS[7][1].rsplit('game.run()', 1)[0] + '''
def branch(game, object_id):
    if game.open_door("hatch_1_1"):
        game.say("The Pickle Nebula annex is open. Find the inner vault panel.")
def vault(game, object_id):
    if game.ask("The club password?") == "crunch":
        game.open_door("vault_1_door")
    else:
        game.say("Hint: it rhymes with lunch.")
def prize(game, snack_id):
    game.set_flag("pickle_club", True)
    game.win("You founded the Forbidden Truffle Club!")
game.on_interact("hatch_1_1_panel", branch)
game.on_interact("vault_1_panel", vault)
game.on_pickup("vault_1_snack", prize)
# Temporary classroom shortcut; remove it for the full journey.
game.teleport("engine_lock")
game.run()
'''
EXAMPLE_PROGRAMS += (("11. A complete student-defined expedition", _expedition),)
EXAMPLES = "\n\n".join(title + "\n" + code for title, code in EXAMPLE_PROGRAMS)

# ------------------------- ENGINE INTERNALS -------------------------


class TerminalError(RuntimeError):
    """An unavailable terminal, distinct from errors in student code."""


class _QuitGame(Exception):
    pass


def _text(value, label):
    if not isinstance(value, str) or not value.strip():
        raise ValueError(f"{label} must be nonempty text")
    return value


def _positive(value, label):
    if type(value) is not int or value < 1:
        raise ValueError(f"{label} must be a positive integer")
    return value


def _symbol(value):
    if not isinstance(value, str) or len(value) != 1 or not '!' <= value <= '~':
        raise ValueError("symbol must be one visible ASCII character, such as '@'")
    return value


def _visible(value):
    """One-column printable ASCII, excluding terminal control sequences."""
    return ''.join(c if ' ' <= c <= '~' else '?' for c in str(value))


def _lines(text, width):
    result = []
    for line in str(text).splitlines() or ['']:
        result.extend(textwrap.wrap(_visible(line.expandtabs(4)), max(1, width),
                                    replace_whitespace=False) or [''])
    return result


class Game:
    """Independent station state; see GUIDE or --guide for the public API."""

    width = 180
    height = 90

    def __init__(self, player_name='Astronaut', player_symbol='@'):
        self.player_name = _text(player_name, 'player_name')
        self.player_symbol = _symbol(player_symbol)
        self.inventory = {}
        self.flags = {}
        self.messages = []
        self.turn = 0
        self.won = False
        self.deck, self.x, self.y = 0, 20, 12
        self._objects = {}
        self._locations = {}
        self._maps = []
        self._interactions = {}
        self._pickups = {}
        self._listeners = {name: [] for name in ('turn', 'delivery', 'collect', 'travel')}
        self._tasks = []
        self._sequence = 0
        self._deliveries = {}
        self._dock_queues = {}
        self._answers = deque()
        self._ui = None
        self._stepping = False
        self._action_phase = False
        self._facing = 'down'
        self._build_station()
        self.say('Welcome aboard. E interacts; ? explains symbols. No mission required.')

    def _lookup(self, registry, key, label):
        if not isinstance(key, str) or key not in registry:
            choices = difflib.get_close_matches(str(key), registry, n=3)
            hint = ' Did you mean ' + ', '.join(choices) + '?' if choices else ''
            raise ValueError(f"Unknown {label} {key!r}.{hint}")
        return registry[key]

    def _object(self, object_id, kind=None):
        obj = self._lookup(self._objects, object_id, 'object ID')
        if kind and obj['kind'] != kind:
            raise ValueError(f"{object_id!r} is not a {kind}")
        return obj

    def list_objects(self):
        return list(self._objects)

    def list_locations(self):
        return list(self._locations)

    def get_object(self, object_id):
        return copy.deepcopy(self._object(object_id))

    def get_delivery(self, delivery_id):
        return copy.deepcopy(self._lookup(self._deliveries, delivery_id, 'delivery ID'))

    def say(self, text):
        self.messages.append(str(text))

    def give(self, item, quantity=1):
        _text(item, 'item'); _positive(quantity, 'quantity')
        self.inventory[item] = self.inventory.get(item, 0) + quantity

    def has(self, item, quantity=1):
        _text(item, 'item'); _positive(quantity, 'quantity')
        return self.inventory.get(item, 0) >= quantity

    def remove(self, item, quantity=1):
        if not self.has(item, quantity):
            return False
        remaining = self.inventory[item] - quantity
        if remaining:
            self.inventory[item] = remaining
        else:
            del self.inventory[item]
        return True

    def set_flag(self, name, value):
        self.flags[_text(name, 'flag name')] = value

    def get_flag(self, name, default=None):
        return self.flags.get(_text(name, 'flag name'), default)

    def set_object(self, object_id, **changes):
        obj = self._object(object_id)
        unknown = set(changes) - {'name', 'symbol', 'description', 'enabled'}
        if unknown:
            raise ValueError('Unknown object option(s): ' + ', '.join(sorted(unknown)))
        for key, value in changes.items():
            if key == 'symbol':
                _symbol(value)
            elif key == 'enabled':
                if type(value) is not bool:
                    raise ValueError('enabled must be True or False')
                if value and obj.get('collected'):
                    raise ValueError('Collected snacks cannot be re-enabled; add a new snack')
                if value and obj['kind'] == 'door' and not obj['open'] and any(
                        self._occupied(obj['deck'], x, y, exclude=object_id)
                        for x,y in obj.get('cells',[(obj['x'],obj['y'])])):
                    raise ValueError('Cannot enable a closed door on an occupied cell')
            elif key == 'name':
                _text(value, 'name')
            elif not isinstance(value, str):
                raise ValueError('description must be text')
        obj.update(changes)

    def open_door(self, object_id):
        door = self._object(object_id, 'door')
        if door.get('destination') and door['destination'] not in self._visited:
            self.say('This hatch requires visiting '+door['destination']); return False
        if object_id=='engine_door': self._engine_unlocked=True
        door['open'] = True
        door['symbol'] = '/'
        return True

    def close_door(self, object_id):
        door = self._object(object_id, 'door')
        if any(self._occupied(door['deck'], x,y, exclude=object_id) for x,y in door.get('cells',[(door['x'],door['y'])])):
            return False
        door['open'] = False
        door['symbol'] = '+'
        return True

    def _occupied(self, deck, x, y, exclude=None):
        return (deck, x, y) == (self.deck, self.x, self.y) or any(
            oid != exclude and o['enabled'] and o['deck']==deck and (x,y) in o.get('cells',[(o['x'],o['y'])])
            for oid, o in self._objects.items())

    def _walkable(self, deck, x, y):
        if not (0 <= deck < len(self._maps) and 0 <= x < self.width and 0 <= y < self.height):
            return False
        if self._maps[deck][y][x] != '.':
            return False
        return not any(o['enabled'] and o['kind'] == 'door' and not o['open'] and
                       o['deck']==deck and (x,y) in o.get('cells',[(o['x'],o['y'])])
                       for o in self._objects.values())

    def _landing(self, location):
        deck, x, y = location
        # Search only the connected walkable component of the named anchor.
        if not self._walkable(deck, x, y):
            raise ValueError('Location anchor is blocked; open its door first')
        todo = deque([(x, y)])
        seen = {(x, y)}
        while todo:
            x, y = todo.popleft()
            if not self._occupied(deck, x, y):
                return deck, x, y
            for dx, dy in DIRECTIONS.values():
                p = (x + dx, y + dy)
                if p not in seen and self._walkable(deck, *p):
                    seen.add(p); todo.append(p)
        raise ValueError('No vacant reachable floor near this location')

    def teleport(self, location):
        anchor = self._lookup(self._locations, location, 'location')
        # Staying at a vacant current anchor should not unexpectedly move us.
        if anchor == (self.deck, self.x, self.y) and not any(
                o['enabled'] and (o['deck'], o['x'], o['y']) == anchor
                for o in self._objects.values()):
            return
        self.deck, self.x, self.y = self._landing(anchor)

    def _place(self, object_id, deck, x, y, name, symbol, description, kind='object', **extra):
        self._objects[object_id] = dict(id=object_id, deck=deck, x=x, y=y,
                                       name=name, symbol=symbol, description=description,
                                       enabled=True, kind=kind, **extra)

    def add_object(self, object_id, location, name=None, symbol='?',
                   description='Not programmed yet.'):
        _text(object_id, 'object ID'); _symbol(symbol)
        if object_id in self._objects or object_id in DIRECTIONS or object_id == 'wait':
            raise ValueError(f'Object ID {object_id!r} is already used or reserved')
        _text(name if name is not None else object_id, 'name')
        if not isinstance(description, str):
            raise ValueError('description must be text')
        anchor = self._lookup(self._locations, location, 'location')
        deck, x, y = self._landing(anchor)
        self._place(object_id, deck, x, y, name or object_id, symbol, description)
        return object_id

    def add_snack(self, object_id, location, name=None, symbol='*',
                  description='An unclaimed snack.'):
        self.add_object(object_id, location, name, symbol, description)
        self._objects[object_id].update(kind='snack', collected=False)
        return object_id

    def move_object(self, object_id, direction):
        obj = self._object(object_id)
        if obj['kind'] in ('lift', 'door', 'dock'):
            raise ValueError('Lifts, doors, and docks have fixed positions')
        if direction not in DIRECTIONS:
            raise ValueError('direction must be up, down, left, or right')
        if not obj['enabled']:
            return False
        dx, dy = DIRECTIONS[direction]
        x, y = obj['x'] + dx, obj['y'] + dy
        if not self._walkable(obj['deck'], x, y) or self._occupied(obj['deck'], x, y):
            return False
        obj['x'], obj['y'] = x, y
        return True

    @staticmethod
    def _callback(callback):
        if not callable(callback):
            raise TypeError('callback must be a function; pass its name without parentheses')
        return callback

    def on_interact(self, object_id, callback):
        self._object(object_id)
        self._interactions[object_id] = self._callback(callback)

    def on_pickup(self, object_id, callback):
        self._object(object_id, 'snack')
        self._pickups[object_id] = self._callback(callback)

    def on_turn(self, callback):
        self._listeners['turn'].append(self._callback(callback))

    def on_delivery(self, callback):
        self._listeners['delivery'].append(self._callback(callback))

    def on_collect(self, callback):
        self._listeners['collect'].append(self._callback(callback))

    def on_travel(self, callback):
        self._listeners['travel'].append(self._callback(callback))

    def _emit(self, event, *args):
        for callback in tuple(self._listeners[event]):
            callback(self, *args)

    def after(self, turns, callback):
        _positive(turns, 'turns'); self._callback(callback)
        # Action effects are before the increment. Timers/listeners are after it.
        due = self.turn + turns + int(self._action_phase)
        self._sequence += 1
        heapq.heappush(self._tasks, (due, self._sequence, callback))

    def request_delivery(self, dock_id, contents, delay=3, vessel='Alien courier', origin=None):
        if origin is not None and origin != self.station_location:
            raise ValueError('Delivery origin must be the current station destination')
        self._object(dock_id, 'dock'); _positive(delay, 'delay'); _text(vessel, 'vessel')
        if isinstance(contents, (list, tuple)):
            cargo = {}
            for item in contents:
                _text(item, 'cargo item')
                cargo[item] = cargo.get(item, 0) + 1
        elif isinstance(contents, dict):
            cargo = dict(contents)
            for item, amount in cargo.items():
                _text(item, 'cargo item'); _positive(amount, 'cargo quantity')
        else:
            raise ValueError('contents must be a list of items or a quantity dictionary')
        if not cargo:
            raise ValueError('contents must not be empty')
        delivery_id = f'delivery_{len(self._deliveries) + 1}'
        self._deliveries[delivery_id] = dict(id=delivery_id, dock=dock_id, contents=cargo,
                                           vessel=vessel, state='pending', arrival_turn=None)

        def arrive(game):
            delivery = game._deliveries[delivery_id]
            delivery.update(state='arrived', arrival_turn=game.turn)
            game._dock_queues[dock_id].append(delivery_id)
            game.say(f'{vessel} arrived at {game._object(dock_id)["name"]}. Cargo ready!')
            game._emit('delivery', delivery_id)

        self.after(delay, arrive)
        return delivery_id

    def set_lift_destinations(self, lift_id, deck_ids):
        lift = self._object(lift_id, 'lift')
        if not isinstance(deck_ids, (list, tuple)) or any(
                type(d) is not int or not 0 <= d < 5 for d in deck_ids):
            raise ValueError('deck_ids must be a list of integers from 0 to 4')
        if len(set(deck_ids)) != len(deck_ids):
            raise ValueError('deck_ids must not contain duplicates')
        lift['destinations'] = list(deck_ids)

    def win(self, message='You win!'):
        if not self.won:
            self.won = True
            self.say(message)

    def queue_answers(self, *answers):
        self._answers.extend(answers)

    def choose(self, prompt, options):
        _text(prompt, 'prompt')
        if not isinstance(options, (list, tuple)) or not options:
            raise ValueError('options must be a nonempty list or tuple of text')
        for option in options:
            _text(option, 'option')
        if len(set(options)) != len(options):
            raise ValueError('options must be distinct')
        if self._answers:
            answer = self._answers.popleft()
            if answer is not None and answer not in options:
                raise ValueError(f'Scripted answer {answer!r} is not in options')
            return answer
        if self._ui is None:
            raise RuntimeError('choose() needs run(), or queue_answers() in a headless test')
        return self._ui.choose(prompt, options)

    def ask(self, prompt):
        _text(prompt, 'prompt')
        if self._answers:
            answer = self._answers.popleft()
            if answer is not None and not isinstance(answer, str):
                raise ValueError('Scripted text answer must be text or None')
            return answer
        if self._ui is None:
            raise RuntimeError('ask() needs run(), or queue_answers() in a headless test')
        return self._ui.ask(prompt)

    def _nearby(self):
        return [oid for oid, o in self._objects.items() if o['enabled'] and
                o['deck'] == self.deck and any(abs(x-self.x)+abs(y-self.y)<=1
                for x,y in o.get('cells',[(o['x'],o['y'])]))]

    def step(self, action):
        if self._stepping:
            raise RuntimeError('Do not call step() recursively from a callback')
        if action is None:
            return False
        if not isinstance(action, str):
            raise ValueError('action must be a direction, wait, or object ID')
        if action not in DIRECTIONS and action != 'wait':
            self._object(action)  # Detect spelling errors even for distant objects.
            if action not in self._nearby():
                return False
        self._stepping = True
        try:
            self._action_phase = True
            if action in DIRECTIONS:
                self._facing = action
                dx, dy = DIRECTIONS[action]
                if not self._walkable(self.deck, self.x + dx, self.y + dy):
                    self.say('Blocked. Walls, furniture and closed doors are solid.')
                    return False
                self.x += dx; self.y += dy
            elif action != 'wait':
                self._interact(action)
            self._action_phase = False
            self.turn += 1
            while self._tasks and self._tasks[0][0] <= self.turn:
                _, _, callback = heapq.heappop(self._tasks)
                callback(self)
            self._emit('turn')
            return True
        finally:
            self._action_phase = False
            self._stepping = False

    def _interact(self, object_id):
        obj = self._object(object_id)
        if object_id in self._interactions:
            self._interactions[object_id](self, object_id)
        elif obj['kind'] == 'snack':
            obj.update(enabled=False, collected=True)
            self.give(obj['name'])
            self.say('Picked up ' + obj['name'] + '.')
            if object_id in self._pickups:
                self._pickups[object_id](self, object_id)
        elif obj['kind'] == 'lift':
            targets = []
            for deck in obj['destinations']:
                target = self._objects[self._lift_ids[deck, obj['shaft']]]
                if deck != self.deck and target['enabled']:
                    targets.append((f'{deck + 1}: {DECK_NAMES[deck]}', target))
            if not targets:
                self.say('This lift has no available destinations.')
                return
            choice = self.choose('Lift destination', [label for label, _ in targets])
            if choice is not None:
                target = dict(targets)[choice]
                old_deck = self.deck
                self.deck, self.x, self.y = self._landing(
                    (target['deck'], target['x'], target['y']))
                self.say('Arrived: ' + DECK_NAMES[self.deck])
                self._emit('travel', old_deck, self.deck)
        elif obj['kind'] == 'dock':
            queue = self._dock_queues[object_id]
            if not queue:
                self.say('No arrived cargo here. Pending deliveries need player turns.')
                return
            delivery_id = queue.popleft()
            delivery = self._deliveries[delivery_id]
            delivery['state'] = 'collected'
            for item, amount in delivery['contents'].items():
                self.give(item, amount)
            self.say('Cargo collected: ' + ', '.join(delivery['contents']))
            self._emit('collect', delivery_id)
        elif obj['kind'] == 'door':
            self.say(('Open' if obj['open'] else 'Closed') + ' door. ' + obj['description'])
        else:
            self.say(obj['description'])

    def camera_origin(self, viewport_width, viewport_height):
        """Pure camera helper: top-left world (x, y); no edge clamping."""
        _positive(viewport_width, 'viewport_width'); _positive(viewport_height, 'viewport_height')
        return self.x - viewport_width // 2, self.y - viewport_height // 2

    def run(self):
        if self._ui is not None or self._stepping:
            raise RuntimeError('run() cannot be nested or called from a callback')
        _symbol(self.player_symbol); _text(self.player_name, 'player_name')
        if not sys.stdin.isatty() or not sys.stdout.isatty():
            raise TerminalError('Play in a real terminal: python3 snack_station.py (docs: --guide)')
        try:
            import curses
        except ImportError as error:
            raise TerminalError('Python curses is unavailable. Documentation modes still work.') from error
        try:
            curses.setupterm()
        except curses.error as error:
            raise TerminalError('Terminal setup failed; use a terminal with a valid TERM setting.') from error
        started = False

        def play(screen):
            nonlocal started
            started = True
            self._ui = _Terminal(self, screen, curses)
            self._ui.run()

        try:
            curses.wrapper(play)
        except (_QuitGame, KeyboardInterrupt):
            pass
        except curses.error as error:
            if not started:
                raise TerminalError('Curses could not initialize this terminal.') from error
            raise  # A student callback may itself raise curses.error: preserve it.
        finally:
            self._ui = None

    def _build_station(self):
        # Room footprints are authored per deck; routes connect their entrances.
        # Rectangles below are inclusive. Ellipses compensate for tall terminal cells.
        self._rooms = []
        self._lift_ids = {}
        self._systems = dict.fromkeys(('reactor', 'cooling', 'containment', 'navigation', 'helm'), False)
        self._engine_running = False
        self._engine_unlocked = False
        self.station_location = 'home_orbit'
        self._destinations = ['home_orbit', 'pickle_nebula', 'crumb_moon', 'sugar_comet', 'salvage_ring']
        self._visited = {'home_orbit'}
        layouts = (
            [('Snack market','rect',(7,3,35,20)), ('Dining rotunda','ellipse',(43,3,95,27)),
             ('Crew cabin','rect',(108,4,124,15)), ('Bunkhouse','L',(130,3,170,27)),
             ('Arcade','L',(9,29,46,54)), ('Galley','rect',(55,34,83,56)),
             ('Quiet garden','ellipse',(94,33,132,57)), ('Recreation','rect',(143,37,174,60))],
            [('Dock control','rect',(7,3,35,22)), ('Loading bay','rect',(44,4,115,36)),
             ('Customs booth','rect',(126,4,143,17)), ('Dispatch','L',(150,3,175,31)),
             ('Crate maze','L',(7,33,51,59)), ('Sorting hall','rect',(62,43,119,59)),
             ('Courier lounge','ellipse',(131,39,174,61))],
            [('Seed lab','ellipse',(6,3,38,23)), ('Fern dome','ellipse',(44,3,100,32)),
             ('Alien orchard','ellipse',(110,3,174,33)), ('Water garden','ellipse',(8,34,58,60)),
             ('Compost lab','L',(69,41,99,59)), ('Pet sanctuary','ellipse',(110,41,151,61)),
             ('Nursery','rect',(160,43,175,60))],
            [('Workshop','L',(7,3,38,25)), ('Battery alcove','rect',(44,3,59,17)),
             ('Tool store','rect',(8,32,34,46)), ('Coolant depot','L',(9,49,52,62)),
             ('Engine hall','ellipse',(66,14,158,64))],
            [('Command bridge','ellipse',(5,3,63,29)), ('Chart room','L',(73,4,112,27)),
             ('Observation gallery','ellipse',(122,3,175,33)), ('Radio booth','rect',(8,39,27,58)),
             ('Signal lab','L',(38,36,82,59)), ('Archive','rect',(93,43,123,59)),
             ('Antenna control','ellipse',(135,42,175,62))],
        )
        routes = (
            [(20,24),(55,30),(100,30),(140,31),(164,31),(164,64),(20,64),(20,24)],
            [(20,26),(59,39),(124,39),(164,35),(164,64),(20,64),(20,26)],
            [(20,27),(64,36),(104,36),(164,37),(164,64),(20,64),(20,27)],
            [(20,27),(55,27),(55,10),(164,10),(164,66),(20,66),(20,27)],
            [(20,32),(65,33),(117,35),(164,36),(164,64),(20,64),(20,32)],
        )

        def path(grid, points, radius=1):
            for (x1,y1),(x2,y2) in zip(points, points[1:]):
                for a,b in (((x1,y1),(x2,y1)),((x2,y1),(x2,y2))):
                    for y in range(min(a[1],b[1])-radius, max(a[1],b[1])+radius+1):
                        for x in range(min(a[0],b[0])-radius, max(a[0],b[0])+radius+1):
                            if 1 <= x < 179 and 1 <= y < 89:
                                grid[y][x] = '.'

        def chamber(grid, name, shape, box, deck):
            x1,y1,x2,y2 = box
            cx,cy = (x1+x2)//2,(y1+y2)//2
            for y in range(y1+1,y2):
                for x in range(x1+1,x2):
                    inside = True
                    if shape == 'ellipse':
                        inside = ((x-cx)/((x2-x1)/2))**2 + ((y-cy)/((y2-y1)/2))**2 < .90
                    elif shape == 'L':
                        inside = x < x1+(x2-x1)*.48 or y > y1+(y2-y1)*.52
                    if inside: grid[y][x] = '.'
            self._rooms.append(dict(deck=deck,name=name,shape=shape,box=box))
            # Furniture clusters stay separated; floors around each are connected.
            glyphs = ('btc','%%o','vv~','o:o','^to')[deck]
            for n in range(3):
                for dx in range(3):
                    x,y = x1+5+dx,y1+4+n*4
                    if x<x2-2 and y<y2-2 and grid[y][x]=='.': grid[y][x]=glyphs[n]
            for x in range(x1+3,min(x2-2,x1+14)):
                if grid[y1][x]=='#': grid[y1][x]='='
            # Put names on solid walls, never across passable routes.
            if shape != 'ellipse':
                for i,c in enumerate(name.upper()[:x2-x1-3]):
                    if grid[y1][x1+2+i] in '#=': grid[y1][x1+2+i]=c
            return cx,cy

        for deck in range(5):
            grid = [['#']*self.width for _ in range(self.height)]
            self._maps.append(grid)
            path(grid,routes[deck])
            anchors=[]
            for name,shape,box in layouts[deck]:
                if name=='Engine hall': continue  # Build the sealed hall last.
                cx,cy=chamber(grid,name,shape,box,deck)
                # Connect to the nearest segment point rather than a repeated grid.
                target=min(routes[deck],key=lambda p:abs(p[0]-cx)+abs(p[1]-cy))
                path(grid,[(cx,cy),target])
                anchors.append((deck,cx,cy))
                self._locations[name.lower().replace(' ','_')]=(deck,cx,cy)
            # Lift spurs and a long aft access gallery remain unrestricted.
            for shaft,x,y in (('forward',20,19),('mid',60 if deck==3 else 92,39),('aft',164,79)):
                target=min(routes[deck],key=lambda p:abs(p[0]-x)+abs(p[1]-y))
                path(grid,[(x,y),target])
                oid=(('habitation','cargo','hydroponics','engineering','communications')[deck]+'_lift'
                     if shaft=='forward' else f'lift_{deck}_{shaft}')
                self._lift_ids[deck,shaft]=oid
                self._place(oid,deck,x,y,shaft.title()+' lift','L','Choose a destination deck.',
                            'lift',shaft=shaft,destinations=list(range(5)))
                self._locations[oid]=(deck,x,y+1)
            # Preserve old numbered names as stable aliases to new room centers.
            for row in range(4):
                for col in range(5):
                    self._locations[f'room_{deck}_{row}_{col}']=min(
                        anchors,key=lambda p:abs(p[1]-(20+col*36))+abs(p[2]-(12+row*20)))
            self._locations[f'deck_{deck}_start']=(deck,20,20)

        self._locations.update(start=(0,20,12),classroom=(0,20,12),snack_court=(0,20,12),
                               optional_room=(0,56,30),cargo_dock=(1,22,12),
                               cargo_dock_b=(1,162,54),garden=(2,20,12),
                               engineering_lift=(3,20,20),observation=(4,148,18))
        equipment=(
            ('alien_terminal',0,19,11,'Alien terminal','T','Program a conversation or delivery request.'),
            ('vending_machine',0,21,11,'Snack fabricator','V','Program a recipe or choice menu.'),
            ('service_robot',0,18,13,'Service robot','R','Program dialogue or safe turn-based movement.'),
            ('alien_plant',0,22,13,'Alien plant','P','Program feeding or delayed snacks.'),
            ('engineering_switch',0,23,14,'Practice switch','!','Program a flag or door change.'),
            ('access_panel',0,24,15,'Lounge panel','A','Program this to open optional_door.'),
            ('cargo_console',1,20,12,'Cargo console','T','Program cargo sorting or delivery choices.'),
            ('garden_pet',2,20,12,'Garden pet','P','Program feeding and remembered visits.'),
            ('power_console',3,20,12,'Power console','!','Program workshop equipment.'),
            ('observation_scope',4,148,18,'Observation scope','O','Stars over home_orbit.'),
            ('bridge_navigation',4,20,12,'Navigation terminal','T','Program navigation with set_system.'),
            ('bridge_helm',4,24,12,'Helm terminal','T','Program helm and call travel(destination_id).'),
        )
        for oid,d,x,y,name,sym,description in equipment:
            # Short spurs for legacy classroom coordinates, all outside gated zones.
            target=min(routes[d],key=lambda p:abs(p[0]-x)+abs(p[1]-y))
            path(self._maps[d],[(x,y),target])
            self._place(oid,d,x,y,name,sym,description)
            self._locations[oid]=(d,x,y)
        for oid,name,d,x,y in (
                ('moon_chips','Moon chips',0,20,13), ('quantum_pickle','Quantum pickle',1,108,27),
                ('comet_cake','Comet cake',2,56,22),('nebula_noodles','Nebula noodles',3,30,57),
                ('vacuum_popcorn','Vacuum popcorn',4,105,52)):
            target=min(routes[d],key=lambda p:abs(p[0]-x)+abs(p[1]-y))
            path(self._maps[d],[(x,y),target])
            self._place(oid,d,x,y,name,'*','An unclaimed snack.','snack',collected=False)
            self._locations[oid]=(d,x,y)
        for oid in ('cargo_dock','cargo_dock_b'):
            d,x,y=self._locations[oid]
            path(self._maps[d],[(x,y),min(routes[d],key=lambda p:abs(p[0]-x)+abs(p[1]-y))])
            self._place(oid,d,x,y,oid.replace('_',' ').title(),'D','Retrieve arrived cargo.','dock')
            self._dock_queues[oid]=deque()

        # The former dining rotunda is now a sealed optional lounge.
        grid=self._maps[0]
        for y in range(2,30):
            for x in range(43,97):
                grid[y][x]='.' if ((x-70)/25)**2+((y-16)/12)**2 < .90 else '#'
        for y in range(25,32):grid[y][70]='.'
        self._place('optional_door',0,70,28,'Lounge door','+',
                    'Program access_panel to open this door.','door',open=False)
        self._locations['optional_door']=(0,70,30)
        self._locations['optional_room']=(0,70,30)
        self._locations['dining_rotunda']=(0,70,30)

        # Engine footprint overwrites old routes; the surrounding loop stays open.
        grid=self._maps[3]
        for y in range(14,65):
            for x in range(66,159):grid[y][x]='#'
        chamber(grid,'Engine hall','ellipse',(66,14,158,64),3)
        # Erase generic furniture; create sci-fi assemblies with clear rings.
        for y in range(17,62):
            for x in range(69,156):
                if grid[y][x] in 'o:':grid[y][x]='.'
                if ((x-112)/11)**2+((y-39)/5)**2<1:grid[y][x]='o'
        for cx,cy,glyph in ((92,30,':'),(132,30,'~'),(112,54,'^')):
            for dy in (-2,-1,0,1,2):
                for dx in range(-4,5):
                    if abs(dx)+2*abs(dy)<7:grid[cy+dy][cx+dx]=glyph
        path(grid,[(55,39),(74,39)])
        self._place('engine_door',3,68,39,'Engine blast lock','+',
                    'Program engine_lock to open engine_door.','door',open=False,
                    cells=[(68,y) for y in range(38,41)])
        for oid,x,y,description in (
                ('engine_lock',63,39,'Exterior lock: call open_door("engine_door").'),
                ('reactor_control',92,33,'Configure reactor with set_system.'),
                ('cooling_control',132,33,'Configure cooling with set_system.'),
                ('containment_control',112,57,'Configure containment with set_system.'),
                ('engine_start',92,39,'Program this to call start_engine().')):
            grid[y][x]='.'
            self._place(oid,3,x,y,oid.replace('_',' ').title(),'T',description)
            self._locations[oid]=(3,x,y)
        self._locations['engine_room']=(3,63,39)

        # Long sealed branches, broad hatch footprints and a nested vault.
        for d in range(5):
            grid=self._maps[d]
            for side,x in enumerate((46,126)):
                for y in range(68,89):
                    for xx in range(x-13,x+14):grid[y][xx]='#'
                path(grid,[(x,64 if d!=3 else 66),(x,74)])
                for y in range(75,88):
                    for xx in range(x-11,x+12):grid[y][xx]='.'
                oid=f'hatch_{d}_{side}'
                self._place(oid,d,x,69,'Service branch hatch','+',
                            'Program '+oid+'_panel to open this hatch.','door',open=False,
                            cells=[(xx,69) for xx in range(x-1,x+2)])
                self._place(oid+'_panel',d,x,67,'Branch access panel','A',
                            'Register on_interact; open_door("'+oid+'").')
                self._locations[oid]=(d,x,68)
                self._locations[oid+'_panel']=(d,x,68)
                self._locations[f'service_branch_{d}_{side}']=(d,x,74)
                self._place(oid+'_snack',d,x-5,80,'Sealed '+str(d)+'-'+str(side)+' bonbon','*',
                            'A snack in a programmed wing.','snack',collected=False)
                self._locations[oid+'_snack']=(d,x-5,80)
                if side==1:
                    self._objects[oid]['destination']=self._destinations[d]
                    # Cross-wall ensures the deep vault cannot be reached sideways.
                    for xx in range(x-11,x+12):grid[83][xx]='#'
                    grid[83][x]='.'
                    vault=f'vault_{d}_door'
                    self._place(vault,d,x,83,'Inner snack vault hatch','+',
                                'A second lock: program vault_'+str(d)+'_panel.','door',open=False)
                    self._place(f'vault_{d}_panel',d,x,81,'Vault panel','A',
                                'Use inventory or flags to open '+vault+'.')
                    self._locations[vault]=(d,x,82)
                    self._locations[f'vault_{d}_panel']=(d,x,82)
                    snack=f'vault_{d}_snack'
                    self._place(snack,d,x,86,'Forbidden '+str(d)+' truffle','*',
                                'A snack behind two programmed locks.','snack',collected=False)
                    self._locations[snack]=(d,x,86)
        # A narrow maintenance spine offers an optional shortcut around each loop.
        for d in range(5):
            upper=routes[d][0][1]
            lower=66 if d==3 else 64
            path(self._maps[d],[(20,upper),(2,upper),(2,lower),(20,lower)],radius=0)
            oid=f'shortcut_{d}_door'
            self._place(oid,d,2,42,'Maintenance shortcut hatch','+',
                        'Program shortcut_'+str(d)+'_panel to open this shortcut.','door',open=False)
            self._place(f'shortcut_{d}_panel',d,2,40,'Shortcut control','A',
                        'Open '+oid+' to connect the maintenance spine.')
            self._locations[oid]=(d,2,41)
            self._locations[f'shortcut_{d}_panel']=(d,2,41)
        # Extra reusable machinery, deliberately idle until registered by students.
        for oid,loc,sym,description in (
                ('irrigation_console','garden','!','Program a timed greenhouse harvest.'),
                ('quarantine_panel','garden','A','Program hatch_2_0 access checks.'),
                ('tractor_console','cargo_dock','T','Program origin-restricted cargo requests.'),
                ('gravity_console','classroom','!','Program pantry access or an object change.'),
                ('signal_decoder','observation','T','Program a password or transmission puzzle.')):
            self.add_object(oid,loc,symbol=sym,description=description)
            o=self._objects[oid];self._locations[oid]=(o['deck'],o['x'],o['y'])
        # Repair legacy aliases swallowed by a gated footprint: aliases point to
        # public approach cells, while explicit interior locations remain debug aids.
        for name,anchor in list(self._locations.items()):
            if name.startswith('room_'):
                d,x,y=anchor
                if d==3 and 66<=x<=158 and 14<=y<=64:
                    self._locations[name]=(3,63,39)
                elif d==0 and 43<=x<=97 and 2<=y<=29:
                    self._locations[name]=(0,70,30)

    def set_system(self, system_id, active=True):
        self._lookup(self._systems,system_id,'system')
        if type(active) is not bool: raise ValueError('active must be True or False')
        self._systems[system_id]=active
        self.say(system_id.title() + (' online.' if active else ' offline.'))
        if not all(self._systems[n] for n in ('reactor','cooling','containment')):
            self._engine_running=False

    def system_active(self, system_id):
        if system_id=='engine': return self._engine_running
        return self._lookup(self._systems,system_id,'system')

    def start_engine(self):
        if not self._engine_unlocked or not all(self._systems[n] for n in ('reactor','cooling','containment')):
            self.say('Open the engine lock and configure reactor, cooling and containment first.')
            return False
        self._engine_running=True
        self.say('The containment rings flare. Engines ready!')
        return True

    def stop_engine(self):
        self._engine_running=False

    def list_destinations(self):
        return list(self._destinations)

    def travel(self, destination_id):
        if destination_id not in self._destinations: raise ValueError('Unknown destination: '+str(destination_id))
        if not self._engine_running or not self._systems['navigation'] or not self._systems['helm']:
            self.say('Travel needs a running engine, navigation and helm.')
            return False
        if destination_id==self.station_location: return False
        self.station_location=destination_id
        self._visited.add(destination_id)
        self.say('Stars sweep past the windows. Arrived: '+destination_id)
        vistas={'home_orbit':'Blue planet and commuter shuttles',
                'pickle_nebula':'Green brine clouds and cucumber-shaped freighters',
                'crumb_moon':'A cratered biscuit moon and flour tugs',
                'sugar_comet':'Sparkling sugar ice and syrup tankers',
                'salvage_ring':'Broken satellites and snack rescue barges'}
        self.set_object('observation_scope',description=vistas[destination_id])
        self.set_object('cargo_console',description='Local cargo traffic: '+vistas[destination_id])
        return True


LEGEND = '''# walls / = windows / room lettering: solid station structure.
b bed, c chair, t table, % crate, v vegetation, ~ water, o machine,
: cable rack, ^ antenna: decorative solid furniture (not interactable).
. clear floor; @ astronaut (customizable).
L lift, T terminal, V fabricator, R robot, P plant/pet, ! switch,
A access panel, D cargo dock, O observation scope, * snack,
+ closed door (blocks), / open door. Custom objects may use other symbols.
E selects nearby interactables. I explains their names, IDs, descriptions,
and the tile you face. Multiple nearby objects open a selection menu.'''


class _Terminal:
    """Single-threaded curses adapter; game rules never call curses directly."""

    def __init__(self, game, screen, curses):
        self.game, self.screen, self.c = game, screen, curses
        screen.keypad(True)
        try:
            curses.curs_set(0)
        except curses.error:
            pass
        # A finite read interval lets resize/redraw recover even without SIGWINCH.
        screen.timeout(150)

    def _size(self):
        return self.screen.getmaxyx()

    def _small(self):
        h, w = self._size()
        return h < 16 or w < 60

    def _put(self, y, text, x=0, attribute=0):
        h, w = self._size()
        if 0 <= y < h and 0 <= x < w - 1:
            try:
                self.screen.addnstr(y, x, _visible(text), w - 1 - x, attribute)
            except self.c.error:
                # A resize can race getmaxyx() and addnstr(); next redraw recovers.
                pass

    def _refresh(self):
        try:
            self.screen.refresh()
        except self.c.error:
            pass

    def _small_screen(self):
        self.screen.erase()
        self._put(0, 'Resize: need 60 columns x 16 rows.')
        self._put(1, 'Q quits. Enlarge to resume automatically.')
        self._refresh()

    def _key(self):
        try:
            return self.screen.get_wch()
        except self.c.error:
            return None

    def _quit_key(self, key, text_entry=False):
        if key == self.c.KEY_F10 or (not text_entry and key in ('q', 'Q')):
            raise _QuitGame()

    def _ready_key(self, text_entry=False):
        """Every modal uses this, preserving selection/input across tiny resizes."""
        paused = False
        while True:
            if self._small():
                paused = True
                self._small_screen()
                key = self._key()
                self._quit_key(key)
                continue
            if paused:
                return self.c.KEY_RESIZE  # Redraw before accepting another action.
            key = self._key()
            self._quit_key(key, text_entry)
            if self._small():
                continue  # A resize raced the read; never execute hidden movement.
            return key

    def draw(self):
        if self._small():
            self._small_screen()
            return
        g = self.game
        _symbol(g.player_symbol)
        h, w = self._size()
        vw, vh = w - 1, h - 7
        left, top = g.camera_origin(vw, vh)
        self.screen.erase()
        self._put(0, f'{g.player_name} | D{g.deck+1} {DECK_NAMES[g.deck].split(" &")[0]} | {g.station_location} | T{g.turn}')
        objects = {cell:o['symbol'] for o in g._objects.values() if o['enabled'] and o['deck']==g.deck for cell in o.get('cells',[(o['x'],o['y'])])}
        for row in range(vh):
            wy = top + row
            line = []
            for col in range(vw):
                wx = left + col
                ch = g._maps[g.deck][wy][wx] if 0 <= wx < g.width and 0 <= wy < g.height else ' '
                ch = objects.get((wx, wy), ch)
                if (wx, wy) == (g.x, g.y):
                    ch = g.player_symbol
                line.append(ch)
            self._put(row + 1, ''.join(line))
        self._put(h - 6, 'Move arrows/WASD  E use  I inspect  B bag  M log  ? help  Q quit')
        self._put(h - 5, 'L lift * snack D dock T terminal + door | # wall = window | . wait')
        recent = []
        for message in reversed(g.messages):
            recent = _lines(message, vw) + recent
            if len(recent) >= 4:
                break
        for i, line in enumerate(recent[-4:]):
            self._put(h - 4 + i, line)
        self._refresh()

    def choose(self, prompt, options):
        selected = 0
        while True:
            if self._small():
                self._ready_key()
                continue
            self.screen.erase()
            h, w = self._size()
            prompt_lines = _lines(prompt, w - 2)[:3]
            for y, line in enumerate(prompt_lines):
                self._put(y, line)
            start_y = len(prompt_lines) + 1
            page_size = max(1, h - start_y - 3)
            start = (selected // page_size) * page_size
            visible = options[start:start + page_size]
            for i, option in enumerate(visible):
                prefix = '> ' if start + i == selected else '  '
                number = str(i + 1) if i < 9 else ' '
                self._put(start_y + i, prefix + number + ' ' + option)
            self._put(h - 2, f'{selected + 1}/{len(options)}  Up/Down Enter; 1-9 visible; Esc cancel; Q quit')
            self._refresh()
            key = self._ready_key()
            if key in ('\x1b',):
                return None
            if key in ('\n', '\r', self.c.KEY_ENTER):
                return options[selected]
            if key == self.c.KEY_UP:
                selected = (selected - 1) % len(options)
            elif key == self.c.KEY_DOWN:
                selected = (selected + 1) % len(options)
            elif key == self.c.KEY_PPAGE:
                selected = max(0, selected - page_size)
            elif key == self.c.KEY_NPAGE:
                selected = min(len(options) - 1, selected + page_size)
            elif key == self.c.KEY_HOME:
                selected = 0
            elif key == self.c.KEY_END:
                selected = len(options) - 1
            elif isinstance(key, str) and key in '123456789' and key:
                index = start + int(key) - 1
                if index < min(start + page_size, len(options)):
                    return options[index]

    def ask(self, prompt):
        value = ''
        while True:
            if self._small():
                self._ready_key(text_entry=True)
                continue
            self.screen.erase()
            h, w = self._size()
            for i, line in enumerate(_lines(prompt, w - 2)[:h - 5]):
                self._put(i, line)
            self._put(h - 4, '> ' + value[-max(1, w - 5):] + '_')
            self._put(h - 2, 'Enter submits; Backspace edits; Esc cancels; F10 quits.')
            self._refresh()
            key = self._ready_key(text_entry=True)
            if key == '\x1b':
                return None
            if key in ('\n', '\r', self.c.KEY_ENTER):
                return value
            if key in ('\b', '\x7f', self.c.KEY_BACKSPACE):
                value = value[:-1]
            elif isinstance(key, str) and key.isprintable() and len(value) < 200:
                value += key

    def view(self, title, text):
        offset = 0
        while True:
            if self._small():
                self._ready_key()
                continue
            self.screen.erase()
            h, w = self._size()
            lines = _lines(text, w - 2)
            page = h - 3
            offset = max(0, min(offset, max(0, len(lines) - page)))
            self._put(0, title)
            for i, line in enumerate(lines[offset:offset + page]):
                self._put(i + 1, line)
            self._put(h - 1, 'Up/Down/PageUp/PageDown scroll; Esc/Enter close; Q quit')
            self._refresh()
            key = self._ready_key()
            if key in ('\x1b', '\n', '\r', self.c.KEY_ENTER):
                return
            if key == self.c.KEY_UP:
                offset -= 1
            elif key == self.c.KEY_DOWN:
                offset += 1
            elif key == self.c.KEY_PPAGE:
                offset -= page
            elif key == self.c.KEY_NPAGE:
                offset += page
            elif key == self.c.KEY_HOME:
                offset = 0
            elif key == self.c.KEY_END:
                offset = len(lines)

    def _inspect(self):
        g = self.game
        lines = []
        for oid in g._nearby():
            o = g._objects[oid]
            lines.append(f'{o["symbol"]} {o["name"]} [{oid}]: {o["description"]}')
        dx, dy = DIRECTIONS[g._facing]
        x, y = g.x + dx, g.y + dy
        tile = g._maps[g.deck][y][x] if 0 <= x < g.width and 0 <= y < g.height else ' '
        names = {'.': 'clear floor', '#': 'solid wall', '=': 'window', 'b': 'bed',
                 'c': 'chair', 't': 'table', '%': 'cargo crate', 'v': 'planting bed',
                 '~': 'water tank', 'o': 'machinery', ':': 'cable rack', '^': 'antenna'}
        lines.append('Facing: ' + names.get(tile, 'solid room sign / outside station') + '.')
        self.view('Nearby objects (E to interact)', '\n'.join(lines))

    def run(self):
        arrows = {self.c.KEY_UP: 'up', self.c.KEY_DOWN: 'down',
                  self.c.KEY_LEFT: 'left', self.c.KEY_RIGHT: 'right'}
        letters = {'w': 'up', 's': 'down', 'a': 'left', 'd': 'right'}
        while True:
            self.draw()
            key = self._ready_key()
            if key is None or key == self.c.KEY_RESIZE:
                continue
            if key in arrows:
                self.game.step(arrows[key])
            elif isinstance(key, str):
                key = key.lower()
                if key in letters:
                    self.game.step(letters[key])
                elif key == '.':
                    self.game.step('wait')
                elif key == 'e':
                    nearby = self.game._nearby()
                    if not nearby:
                        self.game.say('Nothing nearby. Walk toward a symbol; I inspects.')
                    else:
                        labels = [self.game._objects[oid]['name'] + f' [{oid}]' for oid in nearby]
                        choice = labels[0] if len(labels) == 1 else self.game.choose('Interact with?', labels)
                        if choice is not None:
                            self.game.step(nearby[labels.index(choice)])
                elif key == 'i':
                    self._inspect()
                elif key == 'b':
                    self.view('Inventory', '\n'.join(f'{n} x {item}' for item, n in
                                                     self.game.inventory.items()) or 'Empty pockets.')
                elif key == 'm':
                    self.view('Message history', '\n'.join(self.game.messages))
                elif key == '?':
                    self.view('Station help', __doc__ + '\n' + LEGEND + '\n\n' +
                              'Five decks; no required objective. E uses nearby objects.\n' +
                              'Closed doors block; canceled inner menus still use one interaction turn.')


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    modes = parser.add_mutually_exclusive_group()
    modes.add_argument('--guide', action='store_true', help='print student API guide without curses')
    modes.add_argument('--lessons', action='store_true', help='print step-by-step student workbook')
    modes.add_argument('--examples', action='store_true', help='print independent student programs')
    args = parser.parse_args(argv)
    if args.guide:
        print(GUIDE)
    elif args.examples:
        print(EXAMPLES)
    elif args.lessons:
        print(WORKBOOK)
    else:
        try:
            Game().run()
        except TerminalError as error:
            print('Snack Station: ' + str(error), file=sys.stderr)
            return 1
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
