⚔️ Module 9
Text Based Game Part 2
Level-up your adventure: polish the loop, clear the screen between scenes, and roll the dice on random events.
🪄 The concept
When a function must change a variable defined outside it, you may need global — useful for a game_over flag, but use it carefully.
Terminal “animation” is often just prints + time.sleep(), sometimes with os.system("clear") between frames so scenes feel cinematic.
random.choice and random.randint turn a static story into a replayable one — every run a slightly different corridor.
💬 Discussion
Talk these through with a friend, a class, or just your notes app:
- Why might too many
globals make a game hard to debug? - What random events would make your school adventure fun on a second playthrough?
- Is clearing the screen always better? When would you want to keep old text visible?
💻 Code walkthrough
Copy into your editor, or download the .py file and run it. Tinker — change names, numbers, and spells.
global flag and a simple menu menu_duel.py
# Use global when a function must change a variable defined outside it
game_over = False
def duel():
global game_over
print("You raise your wand...")
move = input("Cast (s)tun or (r)un? ")
if move == "r":
print("You escape!")
game_over = True
else:
print("Stupefy! The duel continues.")
while not game_over:
print("\n--- Hogwarts adventure ---")
action = input("(d)uel, (i)nventory, (q)uit: ")
if action == "d":
duel()
elif action == "q":
game_over = True
else:
print("Your bag: wand, chocolate frogs")Simple “animation” with print simple_animation_with_print.py
# Repeat prints to suggest movement (clear screen in full projects)
import time
for step in range(3):
print("The owl flies" + "." * (step + 1))
time.sleep(0.5) # pause half a second between framesClear the screen between scenes (terminal games) clear_the_screen_between_scenes_terminal_games.py
import os
import time
def clear():
# "cls" on Windows, "clear" on Mac/Linux
os.system("cls" if os.name == "nt" else "clear")
for scene in ["Owl arrives...", "Letter opens...", "Train departs..."]:
clear()
print(scene)
time.sleep(1)Random encounter mini-game random_encounter.py
import random
encounters = ["troll in the corridor", "friendly ghost", "lost first-year"]
event = random.choice(encounters)
print("You round the corner and see a", event + "!")
roll = random.randint(1, 6) # random whole number from 1 to 6
if roll >= 4:
print(f"You rolled {roll} — success!")
else:
print(f"You rolled {roll} — hide behind a statue.")🧪 Try this
- Add two more encounters to the random list. Play five times — did you see variety?
- Combine clear-screen + three of your own story scenes. Time the pauses so it feels readable, not rushed.
- In the duel menu, add a heal option that prints a message but does not end the game.
📁 Local files
All runnable Python for this module: