Capstone35 min+50 XP

Project structure

Split the game into modules: data, player, puzzles and saving each get their own file.

0% done

Run this room's code on your own computer in VS Code. You set this up in Module 07.

TASK 1

Splitting code into modules

Key idea

Each module has one job, and main.py imports them all.

Key words
main.pygame loop, parse()test_game.py4 testsrooms.pythe ROOMS dataplayer.pyclass Playerpuzzles.pydecode(), battle()save.pyJSON save + scoressave.jsonscores.txtimportimports
The architecture of Vault Breaker 1.0: files, modules and data files.

One huge file gets hard to read. Professional projects split code into modules: separate .py files that each do one job. Any .py file in the same folder can be imported by name: from player import Player loads the Player class from player.py.

Vault Breaker 1.0 uses five modules:

  • rooms.py: the world data (the rooms dictionary)
  • player.py: the Player class (from the OOP module)
  • puzzles.py: the Caesar decoder and the battle function
  • save.py: saving with JSON, loading with exceptions, and the high score file
  • main.py: the game loop that brings them together

Create each file below in your vault_breaker folder and paste in the code. Read every line: you have learned everything used here. Change the room descriptions to match your design document if you like.

Real life linkA tidy kitchen has cutlery in one drawer and pans in another. Splitting a project into files means you always know where to look.
  1. rooms.py: the world as data. Nested dictionaries from Module 06.
    """Room data for Vault Breaker."""
    
    ROOMS = {
        "Cell": {
            "desc": "A cold server cell. Fans hum in the dark.",
            "exits": {"north": "Corridor"},
            "item": "torch",
        },
        "Corridor": {
            "desc": "Red warning lights flash along the walls.",
            "exits": {"south": "Cell", "east": "Lab", "west": "Armoury", "north": "Exit"},
            "item": None,
        },
        "Lab": {
            "desc": "Screens everywhere. A security bot guards a desk.",
            "exits": {"west": "Corridor"},
            "item": "keycard",
            "enemy": "Firewall",
        },
        "Armoury": {
            "desc": "Racks of old hardware. Something glows on a shelf.",
            "exits": {"east": "Corridor"},
            "item": "energy drink",
        },
        "Exit": {
            "desc": "A huge steel door with a glowing keypad.",
            "exits": {"south": "Corridor"},
            "item": None,
        },
    }
    
    DOOR_MESSAGE = "UFXXBTWI NX KWJJITR"
    
  2. player.py: a class with a protected health property (Module 11) and a to_dict method used for saving.
    """The Player class for Vault Breaker."""
    
    
    class Player:
        """A hacker exploring the vault."""
    
        def __init__(self, name, health=100):
            self.name = name
            self._health = health
            self.inventory = []
            self.location = "Cell"
            self.visited = {"Cell"}
    
        @property
        def health(self):
            return self._health
    
        @health.setter
        def health(self, value):
            # keep health between 0 and 100
            self._health = max(0, min(100, value))
    
        @property
        def alive(self):
            return self._health > 0
    
        def take(self, item):
            self.inventory.append(item)
    
        def has(self, item):
            return item in self.inventory
    
        def to_dict(self):
            """Turn the player into a dictionary that json can save."""
            return {
                "name": self.name,
                "health": self._health,
                "inventory": self.inventory,
                "location": self.location,
                "visited": sorted(self.visited),
            }
    
        def __str__(self):
            items = ", ".join(self.inventory) or "nothing"
            return f"{self.name} | HP {self._health} | Carrying: {items}"
    
  3. puzzles.py: the cipher (Module 09) and the battle loop (Modules 04 and 11). It uses the player object's health property.
    """Puzzles and combat for Vault Breaker."""
    import random
    
    
    def decode(text, shift):
        """Decode a Caesar cipher by shifting capital letters backwards."""
        result = ""
        for ch in text:
            if "A" <= ch <= "Z":
                result += chr((ord(ch) - 65 - shift) % 26 + 65)
            else:
                result += ch
        return result
    
    
    def battle(player, enemy_name, enemy_hp=40):
        """Fight an enemy. Returns True if the player wins."""
        print(f"{enemy_name} blocks your way!")
        while player.alive and enemy_hp > 0:
            hit = random.randint(8, 15)
            enemy_hp = max(enemy_hp - hit, 0)
            print(f"You hit {enemy_name} for {hit}. {enemy_name} HP: {enemy_hp}")
            if enemy_hp > 0:
                damage = random.randint(4, 10)
                player.health -= damage
                print(f"{enemy_name} zaps you for {damage}. Your HP: {player.health}")
        if player.alive:
            print(f"{enemy_name} shuts down.")
            return True
        print("Your screen goes black...")
        return False
    
  4. save.py: JSON saving (Module 10), exceptions for missing or damaged saves, and the score file.
    """Saving and loading Vault Breaker games."""
    import json
    
    from player import Player
    
    
    def save_game(player, path="save.json"):
        with open(path, "w") as f:
            json.dump(player.to_dict(), f, indent=2)
        print("Game saved.")
    
    
    def load_game(path="save.json"):
        """Return a Player from the save file, or None if there is no valid save."""
        try:
            with open(path) as f:
                data = json.load(f)
        except FileNotFoundError:
            print("No save file found.")
            return None
        except json.JSONDecodeError:
            print("The save file is damaged.")
            return None
        player = Player(data["name"], data["health"])
        player.inventory = data["inventory"]
        player.location = data["location"]
        player.visited = set(data["visited"])
        print("Game loaded.")
        return player
    
    
    def record_score(name, score, path="scores.txt"):
        with open(path, "a") as f:
            f.write(f"{name},{score}\n")
    
    
    def score_of(row):
        return row[1]
    
    
    def top_scores(path="scores.txt", count=3):
        try:
            with open(path) as f:
                rows = [line.strip().split(",") for line in f if line.strip()]
        except FileNotFoundError:
            return []
        rows = [(name, int(score)) for name, score in rows]
        rows.sort(key=score_of, reverse=True)
        return rows[:count]
    
  5. Commit the modules:
    git add rooms.py player.py puzzles.py save.py
    git commit -m "Add game modules"
TASK 2

Capture the flag

+10 XP

Write the line that imports the Player class from player.py.

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

MILESTONE

Modules in place

+20 XP

Check your project structure.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.