Advanced Python Coding

 

 

 

 

 

 

by Brendon Thiede

Student Goals

  • Use lists and dictionaries to organize data
  • Write functions to keep code reusable
  • Build a Player class with attributes and methods
  • Save and load game progress with a file
  • Complete a working multi-room text RPG

Icebreaker

If you were designing a video game...

What is the first room the player starts in?

Describe it in one sentence.

Let's Get Set Up

Time to get our starter code!

Step 1: Fork or Sync

  1. Go to the workshop repository on GitHub
  2. If new: click Fork
  3. If returning: click Sync fork → Update branch

https://github.com/Lansing-Tech-Studio/workshops

https://github.com/Lansing-Tech-Studio/workshops

Step 2: Clone & Navigate


git clone https://github.com/YOUR-USERNAME/workshops.git
cd workshops/advanced-python/starter-code
					

Already cloned? Run git pull instead

Step 3: Open in VS Code


code .
					

Open the integrated terminal: View → Terminal

Step 4: Run the Starter Game


cd advanced-python/starter-code
python game.py
					

You should see the game title and a name prompt!

Type a name, then type quit to exit

Lists

Ordered collections — perfect for inventories

Creating a List


inventory = []                 # empty list
inventory.append("sword")      # add an item
inventory.append("torch")      # add another
print(inventory)               # ['sword', 'torch']
print(inventory[0])            # 'sword'  (starts at 0!)
print(len(inventory))          # 2
					

Square brackets [ ] — items separated by commas

Looping Over a List


inventory = ["sword", "torch", "map"]

for item in inventory:
    print(f"  - {item}")
					

Output:


  - sword
  - torch
  - map
					

Dictionaries

Labeled data — perfect for room descriptions

Creating a Dictionary


room = {
    "name": "Dark Cave",
    "description": "Cold and damp.",
    "exits": ["entrance", "tunnel"],
    "item": "torch"
}

print(room["name"])      # Dark Cave
print(room["exits"])     # ['entrance', 'tunnel']
print(room["exits"][0])  # entrance
					

Curly braces { } — key: value pairs

A Dictionary of Dictionaries

This is how game.py stores all the rooms!


rooms = {
    "cave": {
        "name": "Dark Cave",
        "exits": ["entrance"],
        "item": "torch"
    },
    "entrance": {
        "name": "Cave Entrance",
        "exits": ["cave", "forest"],
        "item": None
    },
}

print(rooms["cave"]["item"])   # torch
					

Open game.py

Find the rooms dictionary at the top.

What does rooms["forest"]["item"] return?

Functions

Reusable pieces of code — the secret to bigger programs

Why Functions?

Without functions:


# Room 1
print("=== Dark Cave ===")
print(rooms["cave"]["description"])
print(f"Exits: {', '.join(rooms['cave']['exits'])}")

# Room 2
print("=== Forest ===")
print(rooms["forest"]["description"])
print(f"Exits: {', '.join(rooms['forest']['exits'])}")

# ... repeat for every room
					

Copy-paste is a warning sign — time for a function!

With a Function


def describe_room(room):
    print(f"\n=== {room['name']} ===")
    print(room['description'])
    print(f"Exits: {', '.join(room['exits'])}")
    if room['item']:
        print(f"You see: {room['item']}")

# Now call it for any room:
describe_room(rooms["cave"])
describe_room(rooms["forest"])
					

Change the function once → fixes everything

Function Anatomy


def greet(name):         # def, function name, parameter
    message = f"Hello, {name}!"
    return message       # send a value back

result = greet("Alex")   # call the function
print(result)            # Hello, Alex!
					

Your First TODO: take_item()

Find take_item() in game.py. It currently does nothing (pass). Make it:

  1. Check if room['item'] is not None
  2. If true: add the item to player.inventory, clear room['item'], print a message
  3. If false: print "There is nothing to take here."

Target Code: take_item()


def take_item(player, room):
    if room['item']:
        item = room['item']
        player.inventory.append(item)
        room['item'] = None
        print(f"You picked up: {item}")
    else:
        print("There is nothing to take here.")
					

Energizer Break

Coding Riddle

Why do programmers prefer dark mode?

Bugs are attracted to light!

Classes

Blueprints for creating objects

What is a Class?

A class describes what data an object has and what it can do.


class Player:
    def __init__(self, name):     # runs when created
        self.name = name          # attribute
        self.health = 100         # attribute
        self.inventory = []       # attribute

player = Player("Alex")           # create one Player
print(player.name)                # Alex
print(player.health)              # 100
					

Methods: Functions on an Object


class Player:
    def __init__(self, name):
        self.name = name
        self.health = 100

    def is_alive(self):
        return self.health > 0

player = Player("Alex")
print(player.is_alive())    # True
player.health = 0
print(player.is_alive())    # False
					

self refers to this specific Player object

Modules: Splitting Code into Files

player.py holds the Player class.

game.py imports it:


from player import Player

player = Player("Alex")
					

One file, one responsibility — easier to read and fix

Your Second TODO: player.py

Open player.py and add two methods:

  1. take_damage(self, amount) — reduce health, print status
  2. has_item(self, item_name) — return True/False

Target Code: player.py methods


def take_damage(self, amount):
    self.health = self.health - amount
    print(f"You took {amount} damage! Health: {self.health}")

def has_item(self, item_name):
    return item_name in self.inventory
					

Don't forget to indent your methods inside the class!

File I/O

Making your game remember between sessions

Save & Load

The save_game() and load_game() functions are already in game.py.


import json

# Writing to a file
data = {"name": "Alex", "inventory": ["torch"]}
with open("savegame.json", "w") as f:
    json.dump(data, f)

# Reading from a file
with open("savegame.json", "r") as f:
    data = json.load(f)
print(data["inventory"])    # ['torch']
					

Try It Now

  1. Run the game: python game.py
  2. Pick up an item (go to a room, type take)
  3. Type save, then quit
  4. Run the game again and load your save
  5. Your inventory is still there!

Open savegame.json in VS Code to see what Python wrote

Hands-On: Build Your RPG!

Minimum Mission

  1. Complete take_item() in game.py
  2. Complete take_damage() and has_item() in player.py
  3. Run the game end-to-end
  4. Pick up an item, save, quit, reload

Extend Your Game

  • Add a new room to the rooms dict and connect it
  • Add a "help" command to the dispatcher
  • Add an enemy: entering a room calls player.take_damage()
  • Add a win condition when all items are collected
  • Add a max_inventory limit to the Player class

Getting Help

  • KeyError — check for typos in room names
  • AttributeError — make sure your method has self
  • IndentationError — check method is inside the class
  • Delete savegame.json if the save file is corrupted
  • Ask an instructor — we're here to help!

Save Your Work

Let's commit to Git!

Git Commands


git add .
git commit -m "Complete text RPG"
git push
					

Now your RPG is saved on GitHub!

Show & Tell

Who wants to demo their game?

Enter a room, pick up an item, save, and reload!

Wrap-Up

What We Learned

  • Lists store ordered collections — great for inventories
  • Dictionaries store labeled data — great for rooms
  • Functions keep code reusable and readable
  • Classes are blueprints for creating objects
  • Files let programs remember data between runs

Reflection

Which concept clicked the most for you today?

What would you add to your RPG with more time?

These Skills Unlock...

  • Web apps — Flask uses dicts + functions for every page
  • Data analysis — Pandas works with lists of dicts
  • AI projects — every AI library uses classes
  • Async programming — the next step after event loops

Keep Building

  • Expand your RPG: more rooms, enemies, puzzles
  • Try the Next Steps guide for async, Flask, and more
  • Read other people's Python projects on GitHub
  • Every program you read teaches you something new
Questions?

Thank you!