Text-based adventure games are where computer games began: you read a description, type a command like go north or take key, and the story moves on. In Python the whole world is a dictionary of rooms, each with a description, exits and items.
Your boat has drifted onto Lighthouse Island at dusk. Light the lamp so a passing ship can find you. Type help any time to see the commands.
Play Lighthouse Island
Press βΆ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (70 lines)
How to play
- Commands: look, go <direction>, take <item>, inventory, help, quit.
- Directions are north, south, east, west, up and down.
- Find what you need, reach the top of the lighthouse and light the lamp.
The complete Lighthouse Island code
Here is the whole program (70 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
ROOMS = {
"dock": {"text": "You stand on a wooden dock. Your little boat bumps against it.",
"exits": {"north": "path"}, "items": ["key"]},
"path": {"text": "A sandy path. A lighthouse stands to the north, a shed to the east.",
"exits": {"south": "dock", "east": "shed", "north": "lighthouse"}, "items": []},
"shed": {"text": "A dusty shed full of nets and ropes.",
"exits": {"west": "path"}, "items": ["matches", "rope"]},
"lighthouse": {"text": "Inside the lighthouse. Stairs spiral upwards.",
"exits": {"south": "path", "up": "lamp room"}, "items": []},
"lamp room": {"text": "The lamp room. A huge lamp waits to be lit. Far away, a ship's lights pass by.",
"exits": {"down": "lighthouse"}, "items": []},
}
room = "dock"
bag = []
print("LIGHTHOUSE ISLAND - type 'help' for commands")
def describe():
here = ROOMS[room]
print(f"\n== {room.upper()} ==")
print(here["text"])
if here["items"]:
print("You see:", ", ".join(here["items"]))
print("Exits:", ", ".join(here["exits"]))
describe()
while True:
words = input("> ").strip().lower().split()
if not words:
continue
verb, noun = words[0], " ".join(words[1:])
if verb == "help":
print("look, go <direction>, take <item>, inventory, light lamp, quit")
elif verb == "look":
describe()
elif verb == "inventory":
print("You carry:", ", ".join(bag) if bag else "nothing")
elif verb == "go":
exits = ROOMS[room]["exits"]
if noun not in exits:
print("You can't go that way.")
elif exits[noun] == "lighthouse" and "key" not in bag:
print("The lighthouse door is locked.")
else:
room = exits[noun]
describe()
elif verb == "take":
if noun in ROOMS[room]["items"]:
ROOMS[room]["items"].remove(noun)
bag.append(noun)
print("Taken:", noun)
else:
print("There is no", noun or "thing", "here.")
elif verb == "light" and noun == "lamp":
if room != "lamp room":
print("There's no lamp here.")
elif "matches" not in bag:
print("You need something to light it with.")
else:
print("The lamp blazes into life! The ship turns towards the island.")
print("You are rescued. THE END")
break
elif verb == "quit":
print("Bye!")
break
else:
print("I don't understand that. Try 'help'.")How the Lighthouse Island game works, step by step
01Build the world as a dictionary
Each room name maps to another dictionary with its text, its exits (direction β room) and a list of items. Adding a room is adding one entry.
ROOMS = {
"dock": {"text": "You stand on a wooden dock.",
"exits": {"north": "path"}, "items": ["key"]},
}02Split commands into a verb and a noun
.split() breaks "take matches" into ["take", "matches"]. The first word is the verb, the rest is the noun, so "go north" and "take rope" are handled the same way.
words = input("> ").strip().lower().split()
verb, noun = words[0], " ".join(words[1:])03Move between rooms
Look up the direction in the current room's exits. If it is there, the room variable changes and the new room is described.
exits = ROOMS[room]["exits"]
if noun in exits:
room = exits[noun]04Carry items in a list
Taking an item removes it from the room's list and appends it to your bag. Puzzles are just checks like "key" in bag.
ROOMS[room]["items"].remove(noun)
bag.append(noun)05Win with a condition
The game loop runs forever until a break. Lighting the lamp in the right room with the matches in your bag is the winning move.
elif verb == "light" and noun == "lamp":
...
breakWhat you'll learn
- Nested dictionaries as a game world
- Parsing commands with
.split()and.join() - Lists as an inventory
- Locked doors and puzzles with
inchecks - A command loop with
while True
Python concepts in this game:
Lighthouse Island coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Split a command
Write parse(text) that returns a tuple (verb, noun): lowercase, extra spaces removed, the noun is all words after the first joined by one space (or ""). parse(" Take OLD Map ") gives ("take", "old map").
Hint
.split() with no argument splits on any run of spaces and drops the empty bits.
Show a solution
def parse(text):
words = text.strip().lower().split()
if not words:
return ("", "")
return (words[0], " ".join(words[1:]))
print(parse(" Take OLD Map "))Where does this exit go?
Write go(rooms, room, direction): return the room that the exit leads to, or the same room if there is no exit that way.
Hint
rooms[room]["exits"] is a dictionary. Check direction in exits.
Show a solution
ROOMS = {"hall": {"exits": {"east": "kitchen"}},
"kitchen": {"exits": {"west": "hall"}}}
def go(rooms, room, direction):
exits = rooms[room]["exits"]
if direction in exits:
return exits[direction]
return room
print(go(ROOMS, "hall", "east"))Pick something up
Write take(items, bag, item). If item is in the room's items list, move it into bag and return True; otherwise change nothing and return False.
Hint
Use items.remove(item) and bag.append(item) inside an if item in items:.
Show a solution
def take(items, bag, item):
if item in items:
items.remove(item)
bag.append(item)
return True
return False
room_items = ["rope", "lamp"]
bag = []
print(take(room_items, bag, "rope"), room_items, bag)Make it your own
Once your challenges pass, try one of these upgrades:
- Add a map command that prints where you have been.
- Give the player a step limit before night falls.
- Load the rooms from a JSON file so others can write levels.
- Add characters you can talk to with a 'talk' verb.
Frequently asked questions
How do you make a text-based game in Python?
Store rooms in a dictionary (description, exits, items), keep the current room in a variable, and loop over input() commands that you split into a verb and a noun.
Is a text adventure a good first Python project?
Yes. It uses only dictionaries, lists, strings and a loop, and you can make it as big as you like by adding rooms.
How do I save the player's progress?
Write the current room and the bag to a file with the json module, and load it again when the game starts.