Captain Code: Code

You’ve seen the movies; superheroes need to train to truly unleash their powers. If you want to become Captain Code you need to write code, make that lots and lots of code.

But, copying code line by line is no fun. So, to help you out, we’ve included all of the code in the book right here neatly organized by chapter. Just scroll down to find the code you need, and then you can copy and paste it right into Visual Studio Code.

Yep, we’re just that nice!

How do you copy and paste the code? Follow these steps:

  1. Click on the desired Chapter below to see the available code listings for that chapter.
  2. Click on any code listing to display the code.
  3. Mouse up to the top right of the code listing to display popup buttons.
  4. Click the Copy button to copy the listing to the clipboard.
  5. Go back to Visual Studio Code.
  6. Open a .py file.
  7. Select Paste from the Edit menu to paste your copied code.

Part 1: It’s All Fun & Games

Chapter 1: Getting Started

Hello.py

print("Yeah, this works!")

Chapter 2: Mad Libs

Hello2.py

print("Yeah, this works!", "It really does!")

Hello3.py

firstName="Shmuel"
firstName="Ben"
print("Hello, my name is", firstName, "and I'm a coder!")

Hello4.py

firstName = "Shmuel"
lastName = "Forta"
fullName = firstName + " " + lastName
print("Hello, my name is", fullName, "and I'm a coder!")

Hello5.py

name=input("What is your name? ")
print("Hello", name, "nice to meet you!")

Story.py

print("Hello, please answer the following prompts.")
print()
animal=input("Enter an animal: ")
name=input("Enter a name: ")
adjective1=input("Enter an adjective: ")
color1=input("Enter a color: ")
adjective2=input("Enter an adjective: ")
noun1=input("Enter a noun: ")
noun2=input("Enter a noun: ")
noun3=input("Enter a noun: ")
adjective3=input("Enter an adjective: ")
color2=input("Enter a color: ")
noun4=input("Enter a noun: ")
print("Thank you. Here is your story.")
print()
print("I have a pet", animal,"named",name, ".")
print("He is", adjective1, ", ", color1, ", and", adjective2, ".")
print(name, "eats",  noun1, ",", noun2, ", and", noun3, ".")
print("His favorite toy is a", adjective3, color2, noun4, ".")

Chapter 3: Roll the Dice

Random1.py

import random
num=random.randrange(1, 11)
print("Random number is", num)

Random2.py

# Import needed libraries
import random
# Define the choices
# choices="HT"
choices=["Heads","Tails"]
# Pick a random choice
coinToss=random.choice(choices)
# And display it
print("It's", coinToss)

Dice1.py

# Imports
import random
# Roll and print
print("You rolled a", random.randrange(1, 7))

Dice2.py

# Imports
import random
# Roll both dice
die1=random.randrange(1, 7)
die2=random.randrange(1, 7)
# Display total and individual dies
print("You rolled", die1, "and", die2, "- that's", die1+die2)

Chapter 4: Calculate the Day

Date1.py

# Imports
import datetime
# Get today's date
today=datetime.datetime.now()
# Print it
print("It is", today)

Date2.py

# Imports
import datetime
# Get today's date
today=datetime.datetime.now()
# Print today's year, month, and day
print("The year is", today.year)
print("The month is", today.month)
print("The day is", today.day)

Date3.py

# Imports
import datetime
# Get today's date
today=datetime.datetime.now()
# Display the right message for different days of week
#if today.weekday() == 5 or today.weekday() == 6:
if today.weekday() in [5,6]:
    # Display this on Saturday and Sunday
    print("It's the weekend, no school today!")
    print("We can code all day long!")
elif today.weekday() == 4:
    # Display this on Friday
    print("It's Friday, tomorrow we'll have tons of time to code!")
else:
    # Display this every other day
    print("It's a school day.")

Birthday.py (1st version)

# Import
import datetime
# Get user input
year = int(input("What year were you born? "))
year = int(year)
month = input("What month were you born? ")
month = int(month)
day = input("What day were you born? ")
day = int(day)
# Build the date object
bday = datetime.datetime(year, month, day)
# Display the results
if bday.weekday() == 6:
    print("You were born on Sunday")
elif bday.weekday() == 0:
    print("You were born on Monday")
elif bday.weekday() == 1:
    print("You were born on Tuesday")
elif bday.weekday() == 2:
    print("You were born on Wednesday")
elif bday.weekday() == 3:
    print("You were born on Thursday")
elif bday.weekday() == 4:
    print("You were born on Friday")
elif bday.weekday() == 5:
    print("You were born on Saturday")

Birthday.py (2nd version)

# Import
import datetime
# Get user input
year = int(input("What year were you born? "))
year = int(year)
month = input("What month were you born? ")
month = int(month)
day = input("What day were you born? ")
day = int(day)
# Build the date object
bday = datetime.datetime(year, month, day)
# Calculate the day of week
if bday.weekday() == 6:
    dow="Sunday"
elif bday.weekday() == 0:
    dow="Monday"
elif bday.weekday() == 1:
    dow="Tuesday"
elif bday.weekday() == 2:
    dow="Wednesday"
elif bday.weekday() == 3:
    dow="Thursday"
elif bday.weekday() == 4:
    dow="Friday"
elif bday.weekday() == 5:
    dow="Saturday"
# Display the results
print("You were born on", dow)

Chapter 5: Rock Paper Scissors

rps.py

# Imports
import random
# Ask the user for their name
name=input("What is your name?: ")
# Computer picks one
cChoice = random.choice("RPS")
# Get user choice
print("Hello", name, "let's play Rock, Paper, or Scissors")
uChoice=input("Enter R, P, S: ").upper().strip()
# TOP SECRET CODE
if name == "Ben":
    if uChoice == "R":
        cChoice = "S"
    elif uChoice == "P":
        cChoice = "R"
    elif uChoice == "S":
        cChoice = "P"
# Compare choices
if cChoice == uChoice:
    print("It's a tie!")
elif uChoice == "R" and cChoice == "P":
    print("You picked rock, computer picked paper. You lose.")
elif uChoice == "P" and cChoice == "R":
    print("You picked paper, computer picked rock. You win.")
elif uChoice == "R" and cChoice == "S":
    print("You picked rock, computer picked scissors. You win.")
elif uChoice == "S" and cChoice == "R":
    print("You picked scissors, computer picked rock. You lose.")
elif uChoice == "P" and cChoice == "S":
    print("You picked paper, computer picked scissors. You lose.")
elif uChoice == "S" and cChoice == "P":
    print("You picked scissors, computer picked paper. You win.")
else:
    print("Not very good at listening to instructions. Huh?")

Chapter 6: Secret Codes

List1.py

# Create a list
animals=[]
# How many items in it?
print(len(animals), "animals in list")
# Create a list
animals=["ant","bat","cat","dog","eel"]
# How many items in it?
print(len(animals), "animals in list")

List2.py

# Create a list
animals = ["ant","bat","cat","dog","eel"]
# Display a list item
print(animals[1])

List3.py

# Create a list
animals = ["ant","bat","cat","dog","eel"]
# Display the list
print(animals)
# Update item 2
animals[2] = "cow"
# Display the list
print(animals)

List4.py

# Create a list
animals = ["ant","bat","cat","dog","eel"]
# How big is the list?
print(len(animals), "animals in list")
# Add an item
animals.append("fox")
# Now how big is the list?
print(len(animals), "animals in list")

List5.py

# Create a list
animals = ["ant","bat","cat","dog","eel","fox","goat"]
# Is "goat" in the list?
if "goat" in animals:
    # Yes it is
    print("Yes, goat is item", animals.index("goat"))
else:
    # No it isn't
    print("Nope, no goat, sorry.")

List6.py

# Create a list
animals = ["iguana","dog","bat","eel","goat","ant","cat"]
# Display the list
print(animals)
# Sort the list
animals.sort()
# Display the list
print(animals)

Loop1.py

# List of animals
animals=["ant","bat","cat","dog","eel"]
# Loop through the list
for animal in animals:
    # Display one per loop iteration
    print(animal)

Loop2.py

# Loop tfrom 1 to 10
for i in range(1, 11):
    # Display i in each loop iteration
    print(i)

Loop3.py

# Loop from 1 to 12
for i in range(1, 13):
    # Loop from 1 to 12 within each iteration of the outer loop
    for j in range(1, 13):
        # Print both loop values and multiple them
        print(i, "x", j, "=", i*j)

Encrypt.py

# ASCII range of usable characters - anything out of this range could throw errors
asciiMin = 32   # Represents the space character - " "
asciiMax = 126  # Represents the tilde character - "~"
# Secret key
key = 314159    # Top secret! This is the encryption key!
key = str(key)  # Convert to string so can access individual digits
# Get input message
message = input("Enter message to be encrypted: ")
# Initialize variable for encrypted message
messEncr = ""
# Loop through message
for index in range(0, len(message)):
    # Get the ASCII value for this character
    char = ord(message[index])
    # Is this character out of range?
    if char < asciiMin or char > asciiMax:
        # Yes, not safe to encrypt, leave as is
        messEncr += message[index]
    else:
        # Safe to encrypt this character
        # Encrypt and shift the value as per the key
        ascNum = char + int(key[index % len(key)])
        # If shifted past range, cycle back to the beginning of the range
        if ascNum > asciiMax:
            ascNum -= (asciiMax - asciiMin + 1)
        # Convert to a character and add to output
        messEncr = messEncr + chr(ascNum)
# Display result
print("Encrypted message:", messEncr)

Decrypt.py

# ASCII range of usable charcters - anything out of this range could throw errors
asciiMin = 32   # Represents the space character - " "
asciiMax = 126  # Represents the tilde charcater - "~"
# Secret key
key = 314159    # Top secret! This is the encryption key!
key = str(key)  # Convert to string so can access individual digits
# Get input message
message = input("Enter message to be decrypted: ")
# Initialize variable for decrypted message
messDecr = ""
# Loop through message
for index in range(0, len(message)):
    # Get the ASCII value for this character
    char = ord(message[index])
    # Is this character out of range?
    if char < asciiMin or char > asciiMax:
        # Yes, use as is
        messDecr += message[index]
    else:
        # Safe to encrypt this character
        # Decrypt and shift the value as per the key
        ascNum = char - int(key[index % len(key)])
        # If shifted past range, cycle back to the beginning of the range
        if ascNum < asciiMin:
            ascNum += (asciiMax - asciiMin + 1)
        # Convert to a character and add to output
        messDecr += chr(ascNum)
# Display result
print(messDecr)

Chapter 7: Guess the Number

Loop4.py

# Initialize the input variable
userInput=""
# Loop until the user says STOP
while userInput != "STOP":
    userInput=input("Say something, say STOP to stop: ").upper().strip()

Loop5.py

# Create the empty animals array
animals = []
# Variable for input
userInput = " "
# Give instructions to user
print("I can sort animals for you.")
print("Enter your animals, one at a time.")
print("When you are done just press Enter.")
# Loop until get an empty string
while userInput != "":
    # Get input
    userInput=input("Enter an animal, leave empty to end: ").strip()
    # Make sure it is not empty
    if len(userInput) > 0:
        # It's not empty, add it
        animals.append(userInput)
# Sort data
animals.sort()
# Display the list
print(animals)

NumGuess.py (initial version)

# Guess the number between a specified range.
# User is told if the number guess is too high or too low.
# Game tells the user how many guesses were needed
# Imports
import random
# Define variables
userInput = ""  # This holds the user's input
userGuess = 0   # This holds the user's input as a number
# Generate random number
randNum = random.randrange(1, 101)
# Instructions for user
print("I am thinking of a number between 1 and 100")
print("Can you guess the number?")
# Loop until the user has guessed it
while randNum != userGuess:
    # Get user guess
    userInput=input("Your guess: ").strip()
    # Make sure the user typed a valid number
    if userInput.isnumeric() == False:
        # Input was not a number
        print(userInput, "is not a valid number!")
    else:
        # Input was a number, good to proceed
        # Convert the input text to a number
        userGuess=int(userInput)
        # Check the number
        if userGuess < randNum:
            print("Too low. Try again.")
        elif userGuess > randNum:
            print("Too high. Try again.")
        else:
            print("You got it!")
# Goodbye message
print("Thanks for playing!")

NumGuess.py (revised version)

# Guess the number between a specified range.
# User is told if the number guess is too high or too low.
# Game tells the user how many guesses were needed
# Imports
import random
# Define variables
guesses = 0     # To keep track of how many guesses
numMin = 1      # Start of number range
numMax = 100    # End of number range
userInput = ""  # This holds the user's input
userGuess = 0   # This holds the user's input as a number
# Generate random number
randNum = random.randrange(numMin, numMax+1)
# Instructions for user
print("I am thinking of a number between", numMin, "and", numMax)
print("Can you guess the number?")
# Loop until the user has guessed it
while randNum != userGuess:
    # Get user guess
    userInput=input("Your guess: ").strip()
    # Make sure the user typed a valid number
    if not userInput.isnumeric():
        # Input was not a number
        print(userInput, "is not a valid number!")
    else:
        # Input was a number, good to proceed
        # Increment guess counter
        guesses=guesses+1
        # Convert the input text to a number
        userGuess=int(userInput)
        # Check the number
        if userGuess < numMin or userGuess > numMax:
            print(userGuess, "is not between", numMin, "and", numMax)
        elif userGuess < randNum:
            print("Too low. Try again.")
        elif userGuess > randNum:
            print("Too high. Try again.")
        else:
            print("You got it in", guesses, "tries")
# Goodbye message
print("Thanks for playing!")

Chapter 8: Becoming a Coder

User input test code

# Get a guess
currGuess = input("Guess a letter: ").strip().lower()
# Make sure it's just one character
if len(currGuess) > 1:
    currGuess = currGuess[0]
# Display it
print(currGuess)

Storing guesses test code

guessedLetters = [] # List to store guesses
for i in range (0, 5):
    # Get a guess
    currGuess = input("Guess a letter: ").strip().lower()
    # Append to list
    guessedLetters.append(currGuess)
# Sort the list
guessedLetters.sort()
# Display it
print(guessedLetters)

Displaying lists test code

guessedLetters = [] # List to store guesses
if len(guessedLetters) > 0:
    # There are, start with an empty string
    youTried=""
    # Add each guessed letter
    for letter in guessedLetters:
        youTried += letter
    # Display them
    print("You tried:", youTried)

Masking test code

gameWord = "apocalypse"
guessedLetters = ['a','e']
maskChar = "_"
# Start with an empty string
displayWord = ""
# Loop through word
    for letter in gameWord:
    # Has this letter been guessed?
        if letter in guessedLetters:
            # This one has been guessed so add it
            displayWord += letter
        else:
            # This one has not been guessed so mask it
            displayWord += maskChar
# Display results word
print("Original word:", gameWord)
print("Masked word: ", displayWord)

Chapter 9: Hangman

Hangman.py

# Imports
import random
# Variables
maxLives = 7        # Maximum allowed tries
maskChar = "_"      # Mask character
livesUsed = 0       # Try counter
guessedLetters = [] # List to store guesses
#Game words
gameWords = ["anvil", "boutique", "cookie", "fluff",
            "jazz", "pneumonia", "sleigh", "society",
            "topaz", "tsunami", "yummy", "zombie"]
# Pick the word for the game
gameWord = random.choice(gameWords)
# Start the display with a fully masked word
displayWord = maskChar * len(gameWord)
# Actual game starts here
# Loop until guessed word correctly or out of lives
while gameWord != displayWord and livesUsed < maxLives:
    # First display the masked word
    print(displayWord)
    # Next we need to display any letters already guessed
    # Lists don't display nicely, so let's create a string
    # Are there any guessed letters?
    if len(guessedLetters) > 0:
        # There are, start with an empty string
        youTried=""
        # Add each guessed letter
        for letter in guessedLetters:
            youTried += letter
        # Display them
        print("You tried:", youTried)
    # Display remaining lives
    print (maxLives-livesUsed, "tries left")
    # A little space to make it more readable
    print()
    # Get a guess
    currGuess = input("Guess a letter: ").strip().lower()
    # Make sure it's just one character
    if len(currGuess) > 1:
        currGuess = currGuess[0]
    # Don't allow repeated guess
    if currGuess in guessedLetters:
        print("You already guessed", currGuess)
    else:
        # This is a new guess, save to guessed letter list
        guessedLetters.append(currGuess)
        # And sort the list
        guessedLetters.sort()
        # Update mask
        # Start with an empty string
        displayWord = ""
        # Loop through word
        for letter in gameWord:
            # Has this letter been guessed?
            if letter in guessedLetters:
                # This one has been guessed so add it
                displayWord += letter
            else:
                # This one has not been been guessed so mask it
                displayWord += maskChar
        # Is it a correct guess?
        if currGuess in gameWord:
            # Correct answer
            print ("Correct")
        else:
            # Incorrect answer
            print ("Nope")
            # One more life used
            livesUsed += 1
    # A little space to make it more readable
    print()
# Game play is finished, display results
if displayWord == gameWord:
    # If won
    print ("You win,", gameWord, "is correct!")
else:
    # If lost
    print ("You lose, the answer was:", gameWord)

Part 2: On an Adventure

Chapter 11: Getting Func-ky

Func1.py

def sayHello():
    print("Hello")
sayHello()

Func2.py

# Function to multiply and print two numbers
def multiply(n1, n2):
    print(n1, "x", n2, "=", n1*n2)
# Test the function
multiply(12, 8)

Func3.py

# Function to display text within a border
def displayWelcome(txt):
    borderChar = "*"                    # Border character
    print(borderChar * (len(txt) + 4))  # Top line
    print(borderChar, txt, borderChar)  # Middle line
    print(borderChar * (len(txt) + 4))  # Bottom line
# Test it
displayWelcome("Welcome, O Great Coder Ben!")

Func3.py

# Function to display text within a border
def displayWelcome(txt):
    borderChar = "*"                    # Border character
    print(borderChar * (len(txt) + 4))  # Top line
    print(borderChar, txt, borderChar)  # Middle line
    print(borderChar * (len(txt) + 4))  # Bottom line
# Test it
displayWelcome("Welcome, O Great Coder Ben!")

Func4.py

# Numeric input function
def inputNumber(prompt):
    # Input variable
    inp = ""
    # Loop until variable is a valid number
    while not inp.isnumeric():
        # Prompt for input
        inp = input(prompt).strip()
    # Return the number
    return int(inp)
# Get a number
num=inputNumber("Enter a number: ")
# Display it
print(num)

Chapter 12: Exploring

The text-based adventure game we create in Part 2 is a Space Adventure. We think space adventures are really cool (um, Star Wars anyone?), which is why we picked that story idea. But as promised, we’re also providing starters for a couple other stories. The basic game flow and logic for all three game starters are the same. So, although the lessons in Part 2 all use the Space Adventure as an example, you’ll be able to apply what you learn to any of the story ideas. So, pick whichever you prefer. Or try them all (if you do, please put each in a separate game folder to keep your code nicely organized).

Space Adventure Story Starter: Main.py

##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Welcome the player
def doWelcome():
    # Display text
    print("Welcome adventurer!")
    print("You wake in a daze, recalling nothing useful.")
    print("Stumbling you reach for the door, it opens in anticipation.")
    print("You step outside. Nothing is familiar.")
    print("The landscape is dusty, vast, tinged red, barren.")
    print("You notice that you are wearing a spacesuit. Huh?")
# Location: Start
def doStart():
    # Display text
    print("You look around. Red dust, a pile of boulders, more dust.")
    print("There's an odd octagon shaped structure in front of you.")
    print("You hear beeping nearby. It stopped. No, it didn't.")
    # Prompt for user action
    choice=" "
    while not choice in "PSBR":
        print("You can:")
        print("P = Examine boulder pile")
        print("S = Go to the structure")
        print("B = Walk towards the beeping")
        print("R = Run!")
        choice=input("What do you want to do? [P/S/B/R]").strip().upper()
    # Perform action
    if choice == 'P':
        doBoulders()
    elif choice == 'S':
        doStructure()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Boulders
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# This will be the location for the key
def doBoulders():
    # Display text
    print("Seriously? They are boulders.")
    print("Big, heavy, boring boulders.")
    # Go back to start
    doStart()
# Location: Structure
def doStructure():
    # Display text
    print("You examine the the odd structure.")
    print("Eerily unearthly sounds seem to be coming from inside.")
    print("You see no doors or windows.")
    print("Well, that outline might be a door, good luck opening it.")
    print("And that beeping. Where is it coming from?")
    # Prompt for user action
    choice=" "
    while not choice in "SDBR":
        print("You can:")
        print("S = Back to start")
        print("D = Open the door")
        print("B = Walk towards the beeping")
        print("R = Run!")
        choice=input("What do you want to do? [S/D/B/R]").strip().upper()
    # Perform action
    if choice == 'S':
        doStart()
    elif choice == 'D':
        doStructureDoor()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Structure door
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Unlock only when player has key
def doStructureDoor():
    # Display text
    print("The door appears to be locked.")
    print("You see a small circular hole. Is that the keyhole?")
    print("You move your hand towards it, it flashes blue and closes!")
    print("Well, that didn't work as planned.")
    # Prompt for user action
    choice=" "
    while not choice in "SR":
        print("You can:")
        print("S = Back to structure")
        print("R = Run!")
        choice=input("What do you want to do? [S/R]").strip().upper()
    # Perform action
    if choice == 'S':
        doStructure()
    elif choice == 'R':
        doRun()
# Location: Explore beeping
def doBeeping():
    pass
# Player ran
def doRun():
    # Display text
    print("You run, for a moment.")
    print("And then you are floating. Down down down.")
    print("You've fallen into a chasm, never to be seen again.")
    print("Not very brave, are you?")
    # Dead, game over
    gameOver()
# Game over
def gameOver():
    print("Game over!")
# Actual game starts here
# Display welcome message
doWelcome()
# Game start location
doStart()

Superhero Adventure Story Starter: Main.py

##########################################
# Superhero Adventure
# by Ben & Shmuel
##########################################
# Game opening
def doOpening():
    print("Greetings hero! You are a being of unimaginable power!")
    print("Or, well, you were.... Your powers appear to be missing....")
    print("You open you eyes to see harsh, sterile, white light.")
    print("You are lying on your back.")
    print("With a groan, you get up (hands on your hips of course).")
# Location: laboratory
def doLab():
    # Display text
    print("Looking around, you see that you are in a weird laboratory,\nincluding a cool sci-fi computer and very sharp objects.")
    print("This reminds you of your origin story, complete with conveniently dead scientists,\nalien organizations, chemical accidents, the whole 9 yards.")
    print("There is a very large door at the front of the room and a smaller one to the side.")
    # Prompt for user action
    choice=" "
    while not choice in "LSC":
        print("What do you want to do?:")
        print("L = Large Door")
        print("S = Small Door")
        print("C = Use Computer")
        choice=input("What do you want to do? [L/S/C]").strip().upper()
    # Perform action
    if choice == 'L':
        doHallway()
    elif choice == 'S':
        doLabCloset()
    elif choice == 'C':
        doLabComputer()
# Location: Lab Hallway
def doHallway():
    # Display text
    print("You head through the doorway and enter a hallway.")
    print("It is brightly lit. There is no one around.")
    print("You see doors labelled \'Weapons\' and \'Death\' respectively.")
    print("There is also a doorway labelled \'Exit\' and one labelled \'Laboratory\'.")
    print("There is also a trapdoor below you....")
    # Prompt for user action
    choice=" "
    while not choice in "WDELST":
        print("What do you want to do?:")
        print("W = Weapons Room")
        print("D = Death Room")
        print("E = Exit")
        print("L = Laboratory")
        print("S = Search Around")
        print("T = Trapdoor")
        choice=input("What do you want to do? [W/D/E/L/S/T]").strip().upper()
    # Perform action
    if choice == 'W':
        doWeaponsDoor()
    elif choice == 'D':
        doDeathRoom()
    elif choice == 'E':
        doExit()
    elif choice == 'L':
        doLab()
    elif choice == 'S':
        doHallwaySearch()
    elif choice == 'T':
        doTrapdoor()
# Location: Lab Closet
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Hide something in here for when inventory is implemented
def doLabCloset():
    # Display text
    print("You are in a small broom closet.")
    print("It is so small, that you barely fit with your bulging muscles.")
    print("It is very uncomfortable; you definitely will get sore if you stay here too long.")
    # Prompt for user action
    choice=" "
    while not choice in "ES":
        print("What do you want to do?:")
        print("E = Exit")
        print("S = Search Around")
        choice=input("What do you want to do? [E/S]").strip().upper()
    if choice == 'E':
        doLab()
    elif choice == 'S':
        doLabClosetSearch()
# Location: Room of death
def doDeathRoom():
    print("You enter a room that is pitch black. ")
    print("No amount of superpowers will help you see in here.")
    print("Without warning or reason, your mind begins to fuzz, and then everything is gone....")
    print("IT SAID DEATH ON IT, FOR CRYING OUT LOUD!")
    doDie()
# Location: Trapdoor
# You can decide what is here. A room, basement, new hallway full of rooms, enemies, etc.
def doTrapdoor():
    print("This currently does nothing. Back to hallway.")
    doHallway()
# Action: Use lab computer
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Computer is locked. Password is needed to access computer.
# You can have the user enter passwords (of course, they won't get it unless they find it), or just have the computer unlock if they find the password item
# Computer can be used to start getting powers back. Either it can be automatic as you progress, or you need to buy with some kind of currency
def doLabComputer():
    # Display text
    print("The computer boots up all futuristically (but still Windows XP)\nand before it locks you see a brief message:")
    print("\'Subject power removal success. Unfortunately, can restored via...\'")
    print("Before you can read any more, the computer locks.")
    print("Without a password, there is nothing more you can do.")
    doLab()
# Action: Search lab closet
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Need your super vision restored to see in here
def doLabClosetSearch():
    print("It's too dark to see anything and your legs are starting to hurt.")
    print("There isn't much to do but leave. (Temporarily. A hero never quits!)")
    doLabCloset()
# Action: Search hallway
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Computer password in garbage can
def doHallwaySearch():
    print("You find a piece of paper in the garbage can (gross)!")
    print("The password is \'password123\'. Seriously?!")
    doHallway()
# Action: Attempt to leave
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Need your super strength restored to open this door
def doExit():
    print("The door labelled \'Exit\' won't budge! ")
    print("If only you still had your super-strength....")
    doHallway()
# Action: open weapons door
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# You'll need gloves to open this door. If gloves are equipped,
# you can use an 'if' to skip the prints and go straight to another function called doWeaponsRoom()
def doWeaponsDoor():
    print("As you attempt to open the \'Weapons\' door you begin to feel faint.")
    print("It must be Driptonite on the handles! ")
    print("Your damp, warm, and slightly moist weakness!")
    print("Better find a way to open this door without touching it.")
    doHallway()
# Game over
def doDie():
    print("And with that, our hero fell, never to be heard from again.:")
    print("Game Over!")
# Game starts here
doOpening()
doLab()

Fantasy Adventure Story Starter: Main.py

##########################################
# Fantasy Adventure
# by Ben & Shmuel
##########################################
# Welcome the player
def doWelcome():
    # Display text
    print("Welcome adventurer!")
# Location: Clearing
def doClearing():
    # Display text
    print("You are in a deserted grassy clearing.")
    print("You see a heavily worn path leading north into woods ahead of you.")
    print("You look to your right; the view eastward is obscured by vegetation taller than you.")
    print("You think you hear crackling sounds coming from the west.")
    # Prompt for user action
    choice=" "
    while not choice in "NEW":
        print("What do you want to do?:")
        print("N = North")
        print("E = East")
        print("W = West")
        choice=input("What do you want to do? [N/E/W]").strip().upper()
    # Perform action
    if choice == 'N':
        doWoods1()
    elif choice == 'E':
        doVegetationEast()
    elif choice == 'W':
        doCampSite()
# Location: Vegetation heading east
def doVegetationEast():
    # Display text
    print("You slowly work your way through the dense vegetation.")
    print("Progress is slow.")
    print("Eventually the undergrowth thins, and you find yourself in on a path cut through rocky terrain.")
    print("You hear rushing water to the east.")
    print("The clearing is back west, where you came from.")
    # Prompt for user action
    choice=" "
    while not choice in "EWR":
        print("What do you want to do?:")
        print("E = East")
        print("W = West")
        print("R = Examine rock wall")
        choice=input("What do you want to do? [E/W/R]").strip().upper()
    # Perform action
    if choice == 'E':
        doRiver()
    elif choice == 'W':
        doClearing()
    elif choice == 'R':
        doRocks()
# Location: Rocky path
def doRocks():
    # Display text
    print("Your eyes wonder over the rocky wall. A crevice catches your attention.")
    print("The rushing water to the east is much louder now, you must be close to whatever it is.")
    # Prompt for user action
    choice=" "
    while not choice in "EWC":
        print("What do you want to do?:")
        print("E = East")
        print("W = West")
        print("C = Examine crevice")
        choice=input("What do you want to do? [E/W/C]").strip().upper()
    # Perform action
    if choice == 'E':
        doRiver()
    elif choice == 'W':
        doClearing()
    elif choice == 'C':
        doCrevice()
# Location: Crevice
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Sword is in the crevice
# Clearing the web requires branch with fire
def doCrevice():
    # Display text
    print("The crevice is blocked by what appears to be a spider web.")
    print("You shudder thinking about the size of spiders that could create a web this big and thick.")
    print("There's no way you're tearing through this web, sorry.")
    # Prompt for user action
    choice=" "
    while not choice in "B":
        print("What do you want to do?:")
        print("B = Back")
        choice=input("What do you want to do? [B]").strip().upper()
    # Perform action
    if choice == 'B':
        doRocks()
# Location: River
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Should rive be crossable?
# Repair bridge or some other option?
def doRiver():
    # Display text
    print("You walk towards the water you've been hearing; and you stop just in time!")
    print("You are at the edge of a cliff. The raging river roars far below you.")
    print("Fortunately, there's a bridge across the river.")
    print("Unfortunately, most of the bridge has broken and fallen into the river below.")
    # Prompt for user action
    choice=" "
    while not choice in "W":
        print("What do you want to do?:")
        print("W = West")
        choice=input("What do you want to do? [W]").strip().upper()
    # Perform action
    if choice == 'W':
        doRocks()
# Location: Camp site
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# If player has branch, allow them to light it from embers
def doCampSite():
    # Display text
    print("It looks like a camp site.")
    print("It's deserted, but the glowing embers indicate that someone was here recently.")
    print("The clearing is to the east.")
    print("A dark forbidding forest is to the north.")
    # Prompt for user action
    choice=" "
    while not choice in "NE":
        print("What do you want to do?:")
        print("N = North")
        print("E = East")
        choice=input("What do you want to do? [N/E]").strip().upper()
    # Perform action
    if choice == 'N':
        doForest1()
    elif choice == 'E':
        doClearing()
# Location: Forest1
def doForest1():
    # Display text
    print("It is dark. This might not be your best idea.")
    print("The camp site is south of you.")
    print("You wonder what's east, west, or north.")
    print("But it is dark, south seems like the sane option.")
    # Prompt for user action
    choice=" "
    while not choice in "NSEW":
        print("What do you want to do?:")
        print("N = North")
        print("S = South")
        print("E = East")
        print("W = West")
        choice=input("What do you want to do? [N/S/E/W]").strip().upper()
    # Perform action
    if choice == 'N':
        doForest2()
    elif choice == 'S':
        doCampSite()
    elif choice == 'E':
        doWoods1()
    elif choice == 'W':
        doHouse()
# Location: Forest2
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Allow player to see if they have fire
def doForest2():
    # Display text
    print("It is dark, as in really dark.")
    print("If there is anything here it's probably something you don't want to meet.")
    print("You retrace your steps out of this place.")
    # Out of here
    doForest1()
# Location: House
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# Shield is in the house, add code to retrieve
def doHouse():
    # Display text
    print("There's a house at the edge of the forest.")
    print("Although, calling it a house seems overly generous.")
    print("It's a rundown shack, all boarded up.")
    print("The forest is to the east.")
    # Prompt for user action
    choice=" "
    while not choice in "E":
        print("What do you want to do?:")
        print("E = East")
        choice=input("What do you want to do? [E]").strip().upper()
    # Perform action
    if choice == 'E':
        doForest1()
# Location: Woods1
def doWoods1():
    # Display text
    print("You're on a path in the woods. The path continues to the north.")
    print("There are trees all around, and fallen branches.")
    print("A dark forest is to the west.")
    print("The clearing is behind you to the south.")
    # Prompt for user action
    choice=" "
    while not choice in "NSW":
        print("What do you want to do?:")
        print("N = North")
        print("S = South")
        print("W = West")
        choice=input("What do you want to do? [N/S/W]").strip().upper()
    # Perform action
    if choice == 'N':
        doWoods2()
    elif choice == 'S':
        doClearing()
    elif choice == 'W':
        doForest1()
# Location: Woods2
# DEVELOPER NOTES FOR WHEN INVENTORY SYSTEM IS IMPLEMENTED
# If player has sword then this creature will be defeated
def doWoods2():
    # Display text
    print("You head deeper into the woods.")
    print("And run straight into a hideous creature brandishing a giant spear.")
    print("A snout with two horns, one angry eye in the middle of what must be its head ... and the smell!")
    print("You try to figure out what this thing is, only to be impaled by the spear.")
    print("Too late you realize that walking through the woods unarmed was really brave or really stupid.")
    print("Either way, you are really dead.")
    # Game over
    doGameOver()
# Game over
def doGameOver():
    print("Game over!")
# Game starts here
doWelcome()
doClearing()

Chapter 13: Cleanup Time

Main.py

##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
# Welcome the player
def doWelcome():
    # Display text
    print(Strings.get("Welcome"))
# Location: Start
def doStart():
    # Display text
    print(Strings.get("Start"))
    # Prompt for user action
    choice=" "
    while not choice in "PSBR":
        print("You can:")
        print("P = Examine boulder pile")
        print("S = Go to the structure")
        print("B = Walk towards the beeping")
        print("R = Run!")
        choice=input("What do you want to do? [P/S/B/R]").strip().upper()
    # Perform action
    if choice == 'P':
        doBoulders()
    elif choice == 'S':
        doStructure()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Boulders
def doBoulders():
    # Display text
    print(Strings.get("Boulders"))
    # Go back to start
    doStart()
# Location: Structure
def doStructure():
    # Display text
    print(Strings.get("Structure"))
    # Prompt for user action
    choice=" "
    while not choice in "SDBR":
        print("You can:")
        print("S = Back to start")
        print("D = Open the door")
        print("B = Walk towards the beeping")
        print("R = Run!")
        choice=input("What do you want to do? [S/D/B/R]").strip().upper()
    # Perform action
    if choice == 'S':
        doStart()
    elif choice == 'D':
        doStructureDoor()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Structure door
def doStructureDoor():
    # Display text
    print(Strings.get("StructureDoor"))
    print(Strings.get("StructureDoorNoKey"))
    # Prompt for user action
    choice=" "
    while not choice in "SR":
        print("You can:")
        print("S = Back to structure")
        print("R = Run!")
        choice=input("What do you want to do? [S/R]").strip().upper()
    # Perform action
    if choice == 'S':
        doStructure()
    elif choice == 'R':
        doRun()
# Location: Explore beeping
def doBeeping():
    pass
# Player ran
def doRun():
    # Display text
    print(Strings.get("Run"))
    # Dead, game over
    gameOver()
# Game over
def gameOver():
    print(Strings.get("GameOver"))
# Actual game starts here
# Display welcome message
doWelcome()
# Game start location
doStart()

Strings.py

############################################
# Strings.py
# Externalized strings
############################################
def get(id):
    if id == "Welcome":
        return ("Welcome adventurer!\n"
                "You wake in a daze, recalling nothing useful.\n"
                "Stumbling, you reach for the door, it opens in "
                "anticipation.\nYou step outside. Nothing is "
                "familiar.\nThe landscape is dusty, vast, tinged "
                "red, barren.\nYou notice that you are wearing "
                "a spacesuit. Huh?")
    elif id == "Start":
        return ("You look around. Red dust, a pile of boulders, "
                "more dust.\nThere's an odd octagon shaped "
                "structure in front of you.\nYou hear beeping "
                "nearby. It stopped. No, it didn't.")
    elif id == "Boulders":
        return ("Seriously? They are boulders.\n"
                "Big, heavy, boring boulders.")
    elif id == "Structure":
        return ("You examine the the odd structure.\n"
                "Eerily unearthly sounds seem to be coming from "
                "inside.\nYou see no doors or windows.\nWell, that "
                "outline might be a door, good luck opening it.\n"
                "And that beeping. Where is it coming from?")
    elif id == "StructureDoor":
        return ("The door appears to be locked.\nYou see a small "
                "circular hole. Is that the keyhole?")
    elif id == "StructureDoorNoKey":
        return ("You move your hand towards it, it flashes blue "
                "and closes!\nWell, that didn't work as planned.")
    elif id == "Run":
        return ("You run, for a moment.\n"
                "And then you are floating. Down down down.\n"
                "You've fallen into a chasm, never to be seen "
                "again.\nNot very brave, are you?")
    elif id == "GameOver":
        return "Game over!"
    else:
        return ""

Chapter 14: Reduce, Reuse, Recycle, Refactor

Main.py

##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
import Utils
# Welcome the player
def doWelcome():
    # Display text
    print(Strings.get("Welcome"))
# Location: Start
def doStart():
    # Display text
    print(Strings.get("Start"))
    # What can the player do?
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'P':
        doBoulders()
    elif choice == 'S':
        doStructure()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Boulders
def doBoulders():
    # Display text
    print(Strings.get("Boulders"))
    # Go back to start
    doStart()
# Location: Structure
def doStructure():
    # Display text
    print(Strings.get("Structure"))
    # What can the player do?
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStart()
    elif choice == 'D':
        doStructureDoor()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Structure door
def doStructureDoor():
    # Display text
    print(Strings.get("StructureDoor"))
    print(Strings.get("StructureDoorNoKey"))
    # What can the player do?
    choices = [
        ["S", "Back to structure"],
        ["R", "Run!"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStructure()
    elif choice == 'R':
        doRun()
# Location: Explore beeping
def doBeeping():
    pass
# Player ran
def doRun():
    # Display text
    print(Strings.get("Run"))
    # Dead, game over
    gameOver()
# Game over
def gameOver():
    print(Strings.get("GameOver"))
# Actual game starts here
# Display welcome message
doWelcome()
# Game start location
doStart()

Strings.py

############################################
# Strings.py
# Externalized strings
############################################
def get(id):
    if id == "Welcome":
        return ("Welcome adventurer!\n"
                "You wake in a daze, recalling nothing useful.\n"
                "Stumbling, you reach for the door, it opens in anticipation.\n"
                "You step outside. Nothing is familiar.\n"
                "The landscape is dusty, vast, tinged red, barren.\n"
                "You notice that you are wearing a spacesuit. Huh?")
    elif id == "Start":
        return ("You look around. Red dust, a pile of boulders, more dust.\n"
                "There's an odd octagon shaped structure in front of you.\n"
                "You hear beeping nearby. It stopped. No, it didn't.")
    elif id == "Boulders":
        return ("Seriously? They are boulders.\n"
                "Big, heavy, boring boulders.")
    elif id == "Structure":
        return ("You examine the the odd structure.\n"
                "Eerily unearthly sounds seem to be coming from inside.\n"
                "You see no doors or windows.\n"
                "Well, that outline might be a door, good luck opening it.\n"
                "And that beeping. Where is it coming from?")
    elif id == "StructureDoor":
        return ("The door appears to be locked.\n"
                "You see a small circular hole. Is that the keyhole?")
    elif id == "StructureDoorNoKey":
        return ("You move your hand towards it, it flashes blue and closes!\n"
                "Well, that didn't work as planned.")
    elif id == "Run":
        return ("You run, for a moment.\n"
                "And then you are floating. Down down down.\n"
                "You've fallen into a chasm, never to be seen again.\n"
                "Not very brave, are you?")
    elif id == "GameOver":
        return "Game over!"
    else:
        return ""

Utils.py

############################################
# Utils.py
# Utility functions
############################################
# getUserChoice()
# Displays a list of options, prompts for an option, and returns it
# Pass it a list of lists in format [["Letter","Display Text"]]
# Example: [["A","Option A"],["B","Option B"],["C","Option C"]]
# Returns selected letter
def getUserChoice(options):
    # Create a variable to hold valid inputs
    validInputs=""
    # Loop through the options
    for opt in options:
        # Add this one to the valid letters list
        validInputs+=opt[0]
        # And display it
        print(opt[0], "-", opt[1])
    # Create the prompt
    prompt="What do you want to do? [" + validInputs + "]: "
    # Initialize variables
    choice=""
    done=False
    # Main loop
    while not done:
        # Get a single upper case character
        choice=input(prompt).strip().upper()
        # If the user entered more then 1 character
        if len(choice) > 1:
            # Just use the first
            choice=choice[0]
        # Do we have 1 valid input?
        if len(choice) == 1 and choice in validInputs:
            # We do, outa here!
            done = True
    # Return the selected option
    return choice

Chapter 15: Carrying (and Using) Stuff

Main.py

##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
import Utils
import Inventory as inv
# Welcome the player
def doWelcome():
    # Display text
    print(Strings.get("Welcome"))
# Location: Start
def doStart():
    # Display text
    print(Strings.get("Start"))
    # What can the player do?
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"],
        ["I", "Inventory"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'P':
        doBoulders()
    elif choice == 'S':
        doStructure()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
    elif choice == "I":
        inv.display()
        doStart()
# Location: Boulders
def doBoulders():
    # Does the player have the key?
    if not inv.hasStructureKey():
        # No, display text
        print(Strings.get("BouldersKey"))
        # Add key to inventory
        inv.takeStructureKey()
    else:
        # Yes, so display regular boulder message
        print(Strings.get("Boulders"))
    # Go back to start
    doStart()
# Location: Structure
def doStructure():
    # Display text
    print(Strings.get("Structure"))
    # What can the player do?
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStart()
    elif choice == 'D':
        doStructureDoor()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Structure door
def doStructureDoor():
    # Display text
    print(Strings.get("StructureDoor"))
    if inv.hasStructureKey():
        print(Strings.get("StructureDoorKey"))
    else:
        print(Strings.get("StructureDoorNoKey"))
    # What can the player do?
    choices = [
        ["S", "Back to structure"],
        ["R", "Run!"]
    ]
    # Does user have the key?
    if inv.hasStructureKey():
        # Yep, add unlock to choices
        choices.insert(0, ["U","Unlock the door"])
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStructure()
    elif choice == 'R':
        doRun()
    elif choice == 'U':
        doEnterStructure()
# Location: Explore beeping
def doBeeping():
    pass
# Location: Enter structyure
def doEnterStructure():
    pass
# Player ran
def doRun():
    # Display text
    print(Strings.get("Run"))
    # Dead, game over
    gameOver()
# Game over
def gameOver():
    print(Strings.get("GameOver"))
# Actual game starts here
# Display welcome message
doWelcome()
# Game start location
doStart()

Strings.py

############################################
# Strings.py
# Externalized strings
############################################
def get(id):
    if id == "Welcome":
        return ("Welcome adventurer!\n"
                "You wake in a daze, recalling nothing useful.\n"
                "Stumbling, you reach for the door, it opens in anticipation.\n"
                "You step outside. Nothing is familiar.\n"
                "The landscape is dusty, vast, tinged red, barren.\n"
                "You notice that you are wearing a spacesuit. Huh?")
    elif id == "Start":
        return ("You look around. Red dust, a pile of boulders, more dust.\n"
                "There's an odd octagon shaped structure in front of you.\n"
                "You hear beeping nearby. It stopped. No, it didn't.")
    elif id == "Boulders":
        return ("Seriously? They are boulders.\n"
                "Big, heavy, boring boulders.")
    elif id == "BouldersKey":
        return ("You look closer. Was that a blue flash?\n"
                "You reach between the boulders and find ...\n"
                "It looks like a key, it occasionally flashes blue.")
    elif id == "Structure":
        return ("You examine the the odd structure.\n"
                "Eerily unearthly sounds seem to be coming from inside.\n"
                "You see no doors or windows.\n"
                "Well, that outline might be a door, good luck opening it.\n"
                "And that beeping. Where is it coming from?")
    elif id == "StructureDoor":
        return ("The door appears to be locked.\n"
                "You see a small circular hole. Is that the keyhole?")
    elif id == "StructureDoorNoKey":
        return ("You move your hand towards it, it flashes blue and closes!\n"
                "Well, that didn't work as planned.")
    elif id == "StructureDoorKey":
        return ("You look at the key you are holding.\n"
                "It is flashing blue, as is the keyhole.")
    elif id == "Run":
        return ("You run, for a moment.\n"
                "And then you are floating. Down down down.\n"
                "You've fallen into a chasm, never to be seen again.\n"
                "Not very brave, are you?")
    elif id == "GameOver":
        return "Game over!"
    else:
        return ""

Utils.py

############################################
# Utils.py
# Utility functions
############################################
# getUserChoice()
# Displays a list of options, prompts for an option, and returns it
# Pass it a list of lists in format [["Letter","Display Text"]]
# Example: [["A","Option A"],["B","Option B"],["C","Option C"]]
# Returns selected letter
def getUserChoice(options):
    # Create a variable to hold valid inputs
    validInputs=""
    # Loop through the options
    for opt in options:
        # Add this one to the valid letters list
        validInputs+=opt[0]
        # And display it
        print(opt[0], "-", opt[1])
    # Create the prompt
    prompt="What do you want to do? [" + validInputs + "]: "
    # Initialize variables
    choice=""
    done=False
    # Main loop
    while not done:
        # Get a single upper case character
        choice=input(prompt).strip().upper()
        # If the user entered more then 1 character
        if len(choice) > 1:
            # Just use the first
            choice=choice[0]
        # Do we have 1 valid input?
        if len(choice) == 1 and choice in validInputs:
            # We do, outa here!
            done = True
    # Return the selected option
    return choice
# inputNumber()
# Numeric input function
def inputNumber(prompt):
    # Input variable
    inp = ""
    # Loop until variable is a valid number
    while not inp.isnumeric():
        # Prompt for input
        inp = input(prompt).strip()
    # Return the number
    return int(inp)
# inputYesNo()
#User picks Yes or No, return True or False
def inputYesNo(text):
    #Loop until
    while True:
        #Display prompt
        x=input(text + " [Y/N]").upper()
        #Check response
        if x in ["Y", "YES"]:
            return True
        elif x in ["N", "NO"]:
            return False

Inventory.py

############################################
# Inventory.py
# Inventory system
############################################
inv = {
    "StructureKey": False,
    "Coins": 0
}
# Add key to inventory
def takeStructureKey():
    inv["StructureKey"] = True
# Remove key from inventory
def dropStructureKey():
    inv["StructureKey"] = False
# Does the player have the key?
def hasStructureKey():
    return inv["StructureKey"]
# Add coins to inventory
def takeCoins(coins):
    inv["Coins"] += coins
# Remove coins from inventory
def dropCoins(coins):
    inv["Coins"] -= coins
# How many coins does the player have?
def numCoins():
    return inv["Coins"]
# Display inventory
def display():
    print("*** Inventory ***")
    print("You have", numCoins(), "coins")
    if hasStructureKey():
        print("You have a key that flashes blue")
    print("*****************")

Chapter 16: Keeping It Classy

Main.py

##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
import Utils
import Inventory as inv
import Player
# Create player object
p = Player.player()
# Welcome the player
def doWelcome():
    # Display text
    print(Strings.get("Welcome"))
# Location: Start
def doStart():
    # Display text
    print(Strings.get("Start"))
    # What can the player do?
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"],
        ["I", "Inventory"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'P':
        doBoulders()
    elif choice == 'S':
        doStructure()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
    elif choice == "I":
        inv.display()
        doStart()
# Location: Boulders
def doBoulders():
    # Track this visit
    p.visitBoulder()
    # Display text
    if p.getBoulderVisits() == 1:
        print(Strings.get("Boulders"))
    elif p.getBoulderVisits() == 3:
        print(Strings.get("BouldersKey"))
        inv.takeStructureKey()
    else:
        print(Strings.get("Boulders2"))
    # Go back to start
    doStart()
# Location: Structure
def doStructure():
    # Display text
    print(Strings.get("Structure"))
    # What can the player do?
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStart()
    elif choice == 'D':
        doStructureDoor()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Structure door
def doStructureDoor():
    # Display text
    print(Strings.get("StructureDoor"))
    if inv.hasStructureKey():
        print(Strings.get("StructureDoorKey"))
    else:
        print(Strings.get("StructureDoorNoKey"))
    # What can the player do?
    choices = [
        ["S", "Back to structure"],
        ["R", "Run!"]
    ]
    # Does user have the key?
    if inv.hasStructureKey():
        # Yep, add unlock to choices
        choices.insert(0, ["U","Unlock the door"])
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStructure()
    elif choice == 'R':
        doRun()
    elif choice == 'U':
        doEnterStructure()
# Location: Explore beeping
def doBeeping():
    pass
# Location: Enter structyure
def doEnterStructure():
    pass
# Player ran
def doRun():
    # Display text
    print(Strings.get("Run"))
    # Dead, game over
    gameOver()
# Game over
def gameOver():
    print(Strings.get("GameOver"))
# Actual game starts here
# Display welcome message
doWelcome()
# Game start location
doStart()

Strings.py

############################################
# Strings.py
# Externalized strings
############################################
def get(id):
    if id == "Welcome":
        return ("Welcome adventurer!\n"
                "You wake in a daze, recalling nothing useful.\n"
                "Stumbling you reach for the door, it opens in anticipation.\n"
                "You step outside. Nothing is familiar.\n"
                "The landscape is dusty, vast, tinged red, barren.\n"
                "You notice that you are wearing a spacesuit. Huh?")
    elif id == "Start":
        return ("You look around. Red dust, a pile of boulders, more dust.\n"
                "There's an odd octagon shaped structure in front of you.\n"
                "You hear beeping nearby. It stopped. No, it didn't.")
    elif id == "Boulders":
        return ("Seriously? They are boulders.\n"
                "Big, heavy, boring boulders.")
    elif id == "Boulders2":
        return ("What's with you and boulders?\n"
                "They are still big, heavy, boring boulders.")
    elif id == "BouldersKey":
        return ("You look closer. Was that a blue flash?\n"
                "You reach between the boulders and find ...\n"
                "It looks like a key, it occasionally flashes blue.")
    elif id == "Structure":
        return ("You examine the the odd structure.\n"
                "Eerily unearthly sounds seem to be coming from inside.\n"
                "You see no doors or windows.\n"
                "Well, that outline might be a door, good luck opening it.\n"
                "And that beeping. Where is it coming from?")
    elif id == "StructureDoor":
        return ("The door appears to be locked.\n"
                "You see a small circular hole. Is that the keyhole?")
    elif id == "StructureDoorNoKey":
        return ("You move your hand towards it, it flashes blue and closes!\n"
                "Well, that didn't work as planned.")
    elif id == "StructureDoorKey":
        return ("You look at the key you are holding.\n"
                "It is flashing blue, as is the keyhole.")
    elif id == "Run":
        return ("You run, for a moment.\n"
                "And then you are are floating. Down down down.\n"
                "You've fallen into a chasm, never to be seen again.\n"
                "Not very brave, are you?")
    elif id == "GameOver":
        return "Game over!"
    else:
        return ""

Utils.py

############################################
# Utils.py
# Utility functions
############################################
# getUserChoice()
# Displays a list of options, prompts for an option, and returns it
# Pass it a list of lists in format [["Letter","Display Text"]]
# Example: [["A","Option A"],["B","Option B"],["C","Option C"]]
# Returns selected letter
def getUserChoice(options):
    # Create a variable to hold valid inputs
    validInputs=""
    # Loop through the options
    for opt in options:
        # Add this one to the valid letters list
        validInputs+=opt[0]
        # And display it
        print(opt[0], "-", opt[1])
    # Create the prompt
    prompt="What do you want to do? [" + validInputs + "]: "
    # Initialize variables
    choice=""
    done=False
    # Main loop
    while not done:
        # Get a single upper case character
        choice=input(prompt).strip().upper()
        # If the user entered more then 1 character
        if len(choice) > 1:
            # Just use the first
            choice=choice[0]
        # Do we have 1 valid input?
        if len(choice) == 1 and choice in validInputs:
            # We do, outa here!
            done = True
    # Return the selected option
    return choice
# inputNumber()
# Numeric input function
def inputNumber(prompt):
    # Input variable
    inp = ""
    # Loop until variable is a valid number
    while not inp.isnumeric():
        # Prompt for input
        inp = input(prompt).strip()
    # Return the number
    return int(inp)
# inputYesNo()
#User picks Yes or No, return True or False
def inputYesNo(text):
    #Loop until
    while True:
        #Display prompt
        x=input(text + " [Y/N]").upper()
        #Check response
        if x in ["Y", "YES"]:
            return True
        elif x in ["N", "NO"]:
            return False

Inventory.py

############################################
# Inventory.py
# Inventory system
############################################
inv = {
    "StructureKey": False,
    "Coins": 0
}
# Add key to inventory
def takeStructureKey():
    inv["StructureKey"] = True
# Remove key from inventory
def dropStructureKey():
    inv["StructureKey"] = False
# Does the player have the key?
def hasStructureKey():
    return inv["StructureKey"]
# Add coins to inventory
def takeCoins(coins):
    inv["Coins"] += coins
# Remove coins from inventory
def dropCoins(coins):
    inv["Coins"] -= coins
# How many coins does the player have?
def numCoins():
    return inv["Coins"]
# Display inventory
def display():
    print("*** Inventory ***")
    print("You have", numCoins(), "coins")
    if hasStructureKey():
        print("You have a key that flashes blue")
    print("*****************")

Player.py

############################################
# Player.py
# player class
############################################
# Define player class
class player:
    # Properties
    name = "Adventurer"
    livesLeft = 3
    boulderVisits = 0
    # Get name property
    def getName(self):
        return self.name
    # Get number of lives left
    def getLivesLeft(self):
        return self.livesLeft
    # Player died
    def died(self):
        if self.livesLeft > 0:
            self.livesLeft-=1
    # Is player alive
    def isAlive(self):
        return True if self.livesLeft > 0 else False
    # Get number of times boulders were visited
    def getBoulderVisits(self):
        return self.boulderVisits
    # Player visited the boulders
    def visitBoulder(self):
        self.boulderVisits += 1

Chapter 17: Color Your World

Main.py

##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
import Utils
import Inventory as inv
import Player
from colorama import init, Fore, Back
# Create player object
p = Player.player()
# Initialize colorama
init()
# Welcome the player
def doWelcome():
    # Display text
    print(Back.YELLOW+Fore.GREEN+Strings.get("Welcome"))
# Location: Start
def doStart():
    # Display text
    print(Fore.GREEN+Strings.get("Start"))
    # What can the player do?
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"],
        ["I", "Inventory"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'P':
        doBoulders()
    elif choice == 'S':
        doStructure()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
    elif choice == "I":
        inv.display()
        doStart()
# Location: Boulders
def doBoulders():
    # Display text
    if p.getBoulderVisits() == 0:
        print(Fore.GREEN+Strings.get("Boulders1"))
    elif p.getBoulderVisits() == 2:
        print(Fore.GREEN+Strings.get("BouldersKey"))
        inv.takeStructureKey()
    else:
        print(Fore.GREEN+Strings.get("Boulders2"))
    p.visitBoulder()
    # Go back to start
    doStart()
# Location: Structure
def doStructure():
    # Display text
    print(Fore.GREEN+Strings.get("Structure"))
    # What can the player do?
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStart()
    elif choice == 'D':
        doStructureDoor()
    elif choice == 'B':
        doBeeping()
    elif choice == 'R':
        doRun()
# Location: Structure door
def doStructureDoor():
    # Display text
    print(Fore.GREEN+Strings.get("StructureDoor"))
    if inv.hasStructureKey():
        print(Fore.GREEN+Strings.get("StructureDoorKey"))
    else:
        print(Fore.RED+Strings.get("StructureDoorNoKey"))
    # What can the player do?
    choices = [
        ["S", "Back to structure"],
        ["R", "Run!"]
    ]
    # Does user have the key?
    if inv.hasStructureKey():
        # Yep, add unlock to choices
        choices.insert(0, ["U","Unlock the door"])
    # Prompt for user action
    choice = Utils.getUserChoice(choices)
    # Perform action
    if choice == 'S':
        doStructure()
    elif choice == 'R':
        doRun()
    elif choice == 'U':
        doEnterStructure()
# Location: Explore beeping
def doBeeping():
    pass
# Location: Enter structyure
def doEnterStructure():
    pass
# Player ran
def doRun():
    # Display text
    print(Fore.GREEN+Strings.get("Run"))
    # Dead, game over
    gameOver()
# Game over
def gameOver():
    print(Fore.GREEN+Strings.get("GameOver"))
# Actual game starts here
# Display welcome message
doWelcome()
# Game start location
doStart()

Strings.py

############################################
# Strings.py
# Externalized strings
############################################
def get(id):
    if id == "Welcome":
        return ("Welcome adventurer!\n"
                "You wake in a daze, recalling nothing useful.\n"
                "Stumbling you reach for the door, it opens in anticipation.\n"
                "You step outside. Nothing is familiar.\n"
                "The landscape is dusty, vast, tinged red, barren.\n"
                "You notice that you are wearing a spacesuit. Huh?")
    elif id == "Start":
        return ("You look around. Red dust, a pile of boulders, more dust.\n"
                "There's an odd octagon shaped structure in front of you.\n"
                "You hear beeping nearby. It stopped. No, it didn't.")
    elif id == "Boulders":
        return ("Seriously? They are boulders.\n"
                "Big, heavy, boring boulders.")
    elif id == "Boulders2":
        return ("What's with you and boulders?\n"
                "They are still big, heavy, boring boulders.")
    elif id == "BouldersKey":
        return ("You look closer. Was that a blue flash?\n"
                "You reach between the boulders and find ...\n"
                "It looks like a key, it occasionally flashes blue.")
    elif id == "Structure":
        return ("You examine the the odd structure.\n"
                "Eerily unearthly sounds seem to be coming from inside.\n"
                "You see no doors or windows.\n"
                "Well, that outline might be a door, good luck opening it.\n"
                "And that beeping. Where is it coming from?")
    elif id == "StructureDoor":
        return ("The door appears to be locked.\n"
                "You see a small circular hole. Is that the keyhole?")
    elif id == "StructureDoorNoKey":
        return ("You move your hand towards it, it flashes blue and closes!\n"
                "Well, that didn't work as planned.")
    elif id == "StructureDoorKey":
        return ("You look at the key you are holding.\n"
                "It is flashing blue, as is the keyhole.")
    elif id == "Run":
        return ("You run, for a moment.\n"
                "And then you are are floating. Down down down.\n"
                "You've fallen into a chasm, never to be seen again.\n"
                "Not very brave, are you?")
    elif id == "GameOver":
        return "Game over!"
    else:
        return ""

Utils.py

############################################
# Utils.py
# Utility functions
############################################
from colorama import Fore
# getUserChoice()
# Displays a list of options, prompts for an option, and returns it
# Pass it a list of lists in format [["Letter","Display Text"]]
# Example: [["A","Option A"],["B","Option B"],["C","Option C"]]
# Returns selected letter
def getUserChoice(options):
    # Create a variable to hold valid inputs
    validInputs=""
    # Loop through the options
    for opt in options:
        # Add this one to the valid letters list
        validInputs+=opt[0]
        # And display it
        print(Fore.YELLOW+opt[0], "-", opt[1])
    # Create the prompt
    prompt="What do you want to do? [" + validInputs + "]: "
    # Initialize variables
    choice=""
    done=False
    # Main loop
    while not done:
        # Get a single upper case character
        choice=input(prompt).strip().upper()
        # If the user entered more then 1 character
        if len(choice) > 1:
            # Just use the first
            choice=choice[0]
        # Do we have 1 valid input?
        if len(choice) == 1 and choice in validInputs:
            # We do, outa here!
            done = True
    # Return the selected option
    return choice
# inputNumber()
# Numeric input function
def inputNumber(prompt):
    # Input variable
    inp = ""
    # Loop until variable is a valid number
    while not inp.isnumeric():
        # Prompt for input
        inp = input(prompt).strip()
    # Return the number
    return int(inp)
# inputYesNo()
#User picks Yes or No, return True or False
def inputYesNo(text):
    #Loop until
    while True:
        #Display prompt
        x=input(text + " [Y/N]").upper()
        #Check response
        if x in ["Y", "YES"]:
            return True
        elif x in ["N", "NO"]:
            return False

Inventory.py

############################################
# Inventory.py
# Inventory system
############################################
# Imports
from colorama import Fore
inv = {
    "StructureKey": False,
    "Coins": 0
}
# Add key to inventory
def takeStructureKey():
    inv["StructureKey"] = True
# Remove key from inventory
def dropStructureKey():
    inv["StructureKey"] = False
# Does the player have the key?
def hasStructureKey():
    return inv["StructureKey"]
# Add coins to inventory
def takeCoins(coins):
    inv["Coins"] += coins
# Remove coins from inventory
def dropCoins(coins):
    inv["Coins"] -= coins
# How many coins does the player have?
def numCoins():
    return inv["Coins"]
# Display inventory
def display():
    print(Fore.CYAN+"*** Inventory ***")
    print(Fore.CYAN+"You have", numCoins(), "coins")
    if hasStructureKey():
        print(Fore.CYAN+"You have a key that flashes blue")
    print(Fore.CYAN+"*****************")

Player.py

############################################
# Player.py
# player class
############################################
# Define player class
class player:
    # Properties
    name = "Adventurer"
    livesLeft = 3
    boulderVisits = 0
    # Get name property
    def getName(self):
        return self.name
    # Get number of lives left
    def getLivesLeft(self):
        return self.livesLeft
    # Player died
    def died(self):
        if self.livesLeft > 0:
            self.livesLeft-=1
    # Is player alive
    def isAlive(self):
        return True if self.livesLeft > 0 else False
    # Get number of times boulders were visited
    def getBoulderVisits(self):
        return self.boulderVisits
    # Player visited the boulders
    def visitBoulder(self):
        self.boulderVisits += 1

Part 3: Hit the Road

Chapter 19: Crazy Driver

Main.py

# Imports
import sys
import pygame
from pygame.locals import *
# Game colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
# Main game starts here
# Initialize PyGame
pygame.init()
# Initialize frame manager
clock = pygame.time.Clock()
# Set frame rate
clock.tick(60)
# Set caption bar
pygame.display.set_caption("Crazy Driver")
# Initialize game screen
screen = pygame.display.set_mode((500, 800))
# Set background color
screen.fill(WHITE)
# Update screen
pygame.display.update()
# Main game loop
while True:
    # Check for events
    for event in pygame.event.get():
        # Did the player quit?
        if event.type == QUIT:
            # Quit pygame
            pygame.quit()
            sys.exit()
    # Update screen
    pygame.display.update()

Chapter 20: Image-ine the Possibilities

Main.py

# Imports
import sys, os, random
import pygame
from pygame.locals import *
# Game colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
# Build game paths
GAME_ROOT_FOLDER=os.path.dirname(__file__)
IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
# Main game starts here
# Initialize PyGame
pygame.init()
# Initialize frame manager
clock = pygame.time.Clock()
# Set frame rate
clock.tick(60)
# Set caption bar
pygame.display.set_caption("Crazy Driver")
# Load images
IMG_ROAD = pygame.image.load(os.path.join(IMAGE_FOLDER, "Road.png"))
IMG_PLAYER = pygame.image.load(os.path.join(IMAGE_FOLDER, "Player.png"))
IMG_ENEMY = pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy.png"))
# Initialize game screen
screen = pygame.display.set_mode(IMG_ROAD.get_size())
# Create game objects
# Calculate initial player position
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
# Create player sprite
player = pygame.sprite.Sprite()
player.image = IMG_PLAYER
player.surf = pygame.Surface(IMG_PLAYER.get_size())
player.rect = player.surf.get_rect(center = (h, v))
# Enemy
# Calculate initial enemy position
hl=IMG_ENEMY.get_width()//2
hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
h=random.randrange(hl, hr)
v=0
# Create enemy sprite
enemy = pygame.sprite.Sprite()
enemy.image = IMG_ENEMY
enemy.surf = pygame.Surface(IMG_ENEMY.get_size())
enemy.rect = enemy.surf.get_rect(center = (h, v))
# Main game loop
while True:
    # Place background
    screen.blit(IMG_ROAD, (0,0))
    # Place player on screen
    screen.blit(player.image, player.rect)
    # Place enemy on screen
    screen.blit(enemy.image, enemy.rect)
    # Check for events
    for event in pygame.event.get():
        # Did the player quit?
        if event.type == QUIT:
            # Quit pygame
            pygame.quit()
            sys.exit()
    # Update screen
    pygame.display.update()

Chapter 21: We Like To Move It

Main.py

# Imports
import sys, os, random
import pygame
from pygame.locals import *
# Game colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
# Game variables
moveSpeed = 5
# Build game paths
GAME_ROOT_FOLDER=os.path.dirname(__file__)
IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
# Main game starts here
# Initialize PyGame
pygame.init()
# Initialize frame manager
clock = pygame.time.Clock()
# Set frame rate
clock.tick(60)
# Set caption bar
pygame.display.set_caption("Crazy Driver")
# Load images
IMG_ROAD = pygame.image.load(os.path.join(IMAGE_FOLDER, "Road.png"))
IMG_PLAYER = pygame.image.load(os.path.join(IMAGE_FOLDER, "Player.png"))
IMG_ENEMY = pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy.png"))
# Initialize game screen
screen = pygame.display.set_mode(IMG_ROAD.get_size())
# Create game objects
# Calculate initial player position
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
# Create player sprite
player = pygame.sprite.Sprite()
player.image = IMG_PLAYER
player.surf = pygame.Surface(IMG_PLAYER.get_size())
player.rect = player.surf.get_rect(center = (h, v))
# Enemy
# Calculate initial enemy position
hl=IMG_ENEMY.get_width()//2
hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
h=random.randrange(hl, hr)
v=0
# Create enemy sprite
enemy = pygame.sprite.Sprite()
enemy.image = IMG_ENEMY
enemy.surf = pygame.Surface(IMG_ENEMY.get_size())
enemy.rect = enemy.surf.get_rect(center = (h, v))
# Main game loop
while True:
    # Place background
    screen.blit(IMG_ROAD, (0,0))
    # Place player on screen
    screen.blit(player.image, player.rect)
    # Get keys pressed
    keys = pygame.key.get_pressed()
    # Check for LEFT key
    if keys[K_LEFT] and player.rect.left > 0:
        # Move left
        player.rect.move_ip(-moveSpeed, 0)
        # Make sure we didn't go too far left
        if player.rect.left < 0:
            # To far, fix it
            player.rect.left = 0
    #  Check for RIGHT key
    if keys[K_RIGHT] and player.rect.right < IMG_ROAD.get_width():
        # Move right
        player.rect.move_ip(moveSpeed, 0)
        # Make sure we didn't go too far right
        if player.rect.right > IMG_ROAD.get_width():
            # To far, fix it
            player.rect.right = IMG_ROAD.get_width()
    # Place enemy on screen
    screen.blit(enemy.image, enemy.rect)
    # Move enemy downwards
    enemy.rect.move_ip(0, moveSpeed)
    # Check didn't go off edge of screen
    if (enemy.rect.bottom > IMG_ROAD.get_height()):
        # Calculate new random location
        hl=IMG_ENEMY.get_width()//2
        hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
        h=random.randrange(hl, hr)
        v=0
        # And place it
        enemy.rect.center = (h, v)
    # Check for events
    for event in pygame.event.get():
        # Did the player quit?
        if event.type == QUIT:
            # Quit pygame
            pygame.quit()
            sys.exit()
    # Update screen
    pygame.display.update()

Chapter 22: Crash Bang

Main.py

# Imports
import sys, os, random
import pygame
from pygame.locals import *
# Game colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
# Game variables
moveSpeed = 5
maxSpeed = 10
score = 0
# Build game paths
GAME_ROOT_FOLDER=os.path.dirname(__file__)
IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
# Game over function
def GameOver():
    # Quit Pygame
    pygame.quit()
    sys.exit()
# Main game starts here
# Initialize PyGame
pygame.init()
# Initialize frame manager
clock = pygame.time.Clock()
# Set frame rate
clock.tick(60)
# Set caption bar
pygame.display.set_caption("Crazy Driver")
# Load images
IMG_ROAD = pygame.image.load(os.path.join(IMAGE_FOLDER, "Road.png"))
IMG_PLAYER = pygame.image.load(os.path.join(IMAGE_FOLDER, "Player.png"))
IMG_ENEMY = pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy.png"))
# Initialize game screen
screen = pygame.display.set_mode(IMG_ROAD.get_size())
# Create game objects
# Calculate initial player position
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
# Create player sprite
player = pygame.sprite.Sprite()
player.image = IMG_PLAYER
player.surf = pygame.Surface(IMG_PLAYER.get_size())
player.rect = player.surf.get_rect(center = (h, v))
# Enemy
# Calculate initial enemy position
hl=IMG_ENEMY.get_width()//2
hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
h=random.randrange(hl, hr)
v=0
# Create enemy sprite
enemy = pygame.sprite.Sprite()
enemy.image = IMG_ENEMY
enemy.surf = pygame.Surface(IMG_ENEMY.get_size())
enemy.rect = enemy.surf.get_rect(center = (h, v))
# Main game loop
while True:
    # Update caption with score
    pygame.display.set_caption("Crazy Driver - Score " + str(score))
    # Place background
    screen.blit(IMG_ROAD, (0,0))
    # Place player on screen
    screen.blit(player.image, player.rect)
    # Get keys pressed
    keys = pygame.key.get_pressed()
    # Check for LEFT key
    if keys[K_LEFT] and player.rect.left > 0:
        # Move left
        player.rect.move_ip(-moveSpeed, 0)
        # Make sure we didn't go too far left
        if player.rect.left < 0:
            # To far, fix it
            player.rect.left = 0
    #  Check for RIGHT key
    if keys[K_RIGHT] and player.rect.right < IMG_ROAD.get_width():
        # Move right
        player.rect.move_ip(moveSpeed, 0)
        # Make sure we didn't go too far right
        if player.rect.right > IMG_ROAD.get_width():
            # To far, fix it
            player.rect.right = IMG_ROAD.get_width()
    # Place enemy on screen
    screen.blit(enemy.image, enemy.rect)
    # Move enemy downwards
    enemy.rect.move_ip(0, moveSpeed)
    # Check didn't go off edge of screen
    if (enemy.rect.bottom > IMG_ROAD.get_height()):
        # Calculate new random location
        hl=IMG_ENEMY.get_width()//2
        hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
        h=random.randrange(hl, hr)
        v=0
        # And place it
        enemy.rect.center = (h, v)
        # Update the score
        score += 1
        # Increase the speed
        if moveSpeed < maxSpeed:
            moveSpeed += 1
    # Check for collisions
    if pygame.sprite.collide_rect(player, enemy):
        # Crash! Game over
        GameOver()
    # Check for events
    for event in pygame.event.get():
        # Did the player quit?
        if event.type == QUIT:
            # Quit pygame
            pygame.quit()
            sys.exit()
    # Update screen
    pygame.display.update()

Chapter 23: Finishing Touches

Main.py

# Imports
import sys, os, random, time
import pygame
from pygame.locals import *
# Game colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
# Game variables
startSpeed = 5
moveSpeed = startSpeed
maxSpeed = 10
score = 0
eNum = -1
paused = False
textFonts = ['comicsansms','arial']
textSize = 48
# Build game paths
GAME_ROOT_FOLDER=os.path.dirname(__file__)
IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
# GameOver function
# Displays message and cleans things up
def GameOver():
    # Game Over text creation
    fontGameOver = pygame.font.SysFont(textFonts, textSize)
    textGameOver = fontGameOver.render("Game Over!", True, RED)
    rectGameOver = textGameOver.get_rect()
    rectGameOver.center = (IMG_ROAD.get_width()//2,
                           IMG_ROAD.get_height()//2)
    # Black screen with game over text
    screen.fill(BLACK)
    screen.blit(textGameOver, rectGameOver)
    # Update the display
    pygame.display.update()
    # Destroy objects
    player.kill()
    enemy.kill()
    # Pause
    time.sleep(5)
    # Quit pygame
    pygame.quit()
    sys.exit()
# Main game starts here
# Initialize PyGame
pygame.init()
# Initialize frame manager
clock = pygame.time.Clock()
# Set frame rate
clock.tick(60)
# Set caption bar
pygame.display.set_caption("Crazy Driver")
# Load images
IMG_ROAD = pygame.image.load(os.path.join(IMAGE_FOLDER, "Road.png"))
IMG_PLAYER = pygame.image.load(os.path.join(IMAGE_FOLDER, "Player.png"))
IMG_ENEMIES = []
IMG_ENEMIES.append(pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy.png")))
IMG_ENEMIES.append(pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy2.png")))
IMG_ENEMIES.append(pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy3.png")))
IMG_ENEMIES.append(pygame.image.load(os.path.join(IMAGE_FOLDER, "IceCube.png")))
# Initialize game screen
screen = pygame.display.set_mode(IMG_ROAD.get_size())
# Create game objects
# Calculate initial player position
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
# Create player sprite
player = pygame.sprite.Sprite()
player.image = IMG_PLAYER
player.surf = pygame.Surface(IMG_PLAYER.get_size())
player.rect = player.surf.get_rect(center = (h, v))
# Main game loop
while True:
    # Update caption with score
    pygame.display.set_caption("Crazy Driver - Score " + str(score))
    # Place background
    screen.blit(IMG_ROAD, (0,0))
    # Place player on screen
    screen.blit(player.image, player.rect)
    # Make sure we have an enemy
    if eNum == -1:
        # Get a random enemy
        eNum = random.randrange(0, len(IMG_ENEMIES))
        # Calculate initial enemy position
        hl=IMG_ENEMIES[eNum].get_width()//2
        hr=IMG_ROAD.get_width()-(IMG_ENEMIES[eNum].get_width()//2)
        h=random.randrange(hl, hr)
        v=0
        # Create enemy sprite
        enemy = pygame.sprite.Sprite()
        enemy.image = IMG_ENEMIES[eNum]
        enemy.surf = pygame.Surface(IMG_ENEMIES[eNum].get_size())
        enemy.rect = enemy.surf.get_rect(center = (h, v))
    # Get keys pressed
    keys = pygame.key.get_pressed()
    # Are we paused?
    if paused:
        # Check for SPACE
        if not keys[K_SPACE]:
            # Turn off pause
            # Set speed back to what it was
            moveSpeed=tempSpeed
            # Turn off flag
            paused=False
    else:
        # Check for LEFT key
        if keys[K_LEFT] and player.rect.left > 0:
            # Move left
            player.rect.move_ip(-moveSpeed, 0)
            # Make sure we didn't go too far left
            if player.rect.left < 0:
                # To far, fix it
                player.rect.left = 0
        #  Check for RIGHT key
        if keys[K_RIGHT] and player.rect.right < IMG_ROAD.get_width():
            # Move right
            player.rect.move_ip(moveSpeed, 0)
            # Make sure we didn't go too far right
            if player.rect.right > IMG_ROAD.get_width():
                # To far, fix it
                player.rect.right = IMG_ROAD.get_width()
        # Check for SPACE key
        if keys[K_SPACE]:
            # Turn on pause
            # Save speed
            tempSpeed=moveSpeed
            # Set speed to 0
            moveSpeed=0
            # Turn on flag
            paused=True
    # Place enemy on screen
    screen.blit(enemy.image, enemy.rect)
    # Move enemy downwards
    enemy.rect.move_ip(0, moveSpeed)
    # Check didn't go off edge of screen
    if (enemy.rect.bottom > IMG_ROAD.get_height()):
        # Kill enemy object
        enemy.kill()
        # No enemy
        eNum = -1
        # Increment the score
        score += 1
        # Increase the speed
        moveSpeed += 1
        # Increase the speed
        if moveSpeed < maxSpeed:
            moveSpeed += 1
    # Check for collisions
    if eNum >= 0 and pygame.sprite.collide_rect(player, enemy):
        # Is it enemy 3?
        if eNum == 3:
            # It's the ice cube, reset the speed
            moveSpeed = startSpeed
        else:
            # Crash! Game over
            GameOver()
    # Check for events
    for event in pygame.event.get():
        # Did the player quit?
        if event.type == QUIT:
            # Quit pygame
            pygame.quit()
            sys.exit()
    # Update screen
    pygame.display.update()

What Next?

Class version of Crazy Driver: Main.py

In There’s a Lot More to Python we suggest that you build a class-based version of Crazy Driver, and we said we’d post one online to get you started. Well, here it is.

# Imports
import sys, os, random, time, pickle
import pygame
from pygame.locals import *
class Game():
    # Game Objects - will hold player and enemies. Intialize to empty
    gameObjects = pygame.sprite.Group()
    ### Storage classes
    # Game variables
    class Variables():
        # Game colors - constant
        BLACK = (0, 0, 0)
        WHITE = (255, 255, 255)
        RED   = (255, 0, 0)
        # Other constant
        MAX_SPEED = 10
        TEXT_FONTS = ['comicsansms','arial']
        TEXT_SIZE_GAME_OVER = 48
        TEXT_SIZE_SCORE = 36
        SAVE_DATA_FILE = "crazyDriverSave.p"
        # Variables
        startSpeed = 3.0
        moveSpeed = startSpeed
        tempSpeed = moveSpeed
        score = 0
        highScore = 0
        eNum = -1
        # Save high score
        @classmethod
        def Save(self, val):
            # Create database
            db = {
                "highScore": val
            }
            # Save it
            pickle.dump(db, open(self.SAVE_DATA_FILE, "wb"))
        # Load high score
        @classmethod
        def Load(self):
            # If save file exists
            if os.path.isfile(self.SAVE_DATA_FILE):
                # Read and return high score
                db = pickle.load(open(self.SAVE_DATA_FILE, "rb"))
                self.highScore =  db["highScore"]
        # Returns score for read purposes
        @classmethod
        def GetScore(self):
            # Return enemy number
            return self.score
        # Returns high score for read purposes
        @classmethod
        def GetHighScore(self):
            # Return enemy number
            return self.highScore
        # Returns color
        @classmethod
        def GetColor(self, col):
            # Set to lowercase for consistency
            col = col.lower().strip()
            # Return requested color
            if col == 'red':
                return self.RED
            elif col == 'white':
                return self.WHITE
            elif col == 'black':
                return self.BLACK
        # Returns enemy value for read purposes
        @classmethod
        def GetEnemy(self):
            # Return enemy number
            return self.eNum
        # Allows setting of eNum exteranlly
        @classmethod
        def SetEnemy(self, val):
            # Set eNum to arguement
            self.eNum = val
        # Returns speed for read purposes
        @classmethod
        def GetSpeed(self):
            # Return speed
            return self.moveSpeed
        # Raises speed
        @classmethod
        def RaiseSpeed(self):
            # Add points
            self.RaisePoints()
            # If haven't exceeded max speed
            if self.moveSpeed < self.MAX_SPEED:
                # Raise speed
                self.moveSpeed += 0.5
        # Gets points
        @classmethod
        def RaisePoints(self):
            # Raise score
            # At top speed, 3 points
            if self.moveSpeed >= self.MAX_SPEED:
                self.score += 3
            # at half speed, 2 points
            elif self.moveSpeed > (self.startSpeed + self.MAX_SPEED) / 2:
                self.score += 2
            # 1 point otherwise
            else:
                self.score += 1
            # If beat high score
            if self.score > self.highScore:
                # Set new high score and save it
                self.highScore = self.score
                self.Save(self.highScore)
        # Resets speed to starting point
        @classmethod
        def ResetSpeed(self):
            # Reset speed
            self.moveSpeed = self.startSpeed
        # Toggles pause and unpause
        @classmethod
        def PauseToggle(self):
            # If speed is zero, game is paused
            if self.moveSpeed == 0:
                # Unpause - set moveSpeed back
                self.moveSpeed = self.tempSpeed
            # If speed isn't zero, game is unpaused
            else:
                # Store speed in temp variable and set speed to zero
                self.tempSpeed = self.moveSpeed
                self.moveSpeed = 0
        # Checks if paused
        @classmethod
        def IsPaused(self):
            # Return true if speed is zero because that means paused
            return self.moveSpeed == 0
        # Gets text parameters for game over screen
        @classmethod
        def GetTextParams(self):
            return self.TEXT_FONTS, self.TEXT_SIZE_GAME_OVER, self.TEXT_SIZE_SCORE
    # Images
    class Images():
        # Build game paths
        GAME_ROOT_FOLDER=os.path.dirname(__file__)
        IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
        # Initialize images - constant
        IMG_ROAD = pygame.image.load(os.path.join(IMAGE_FOLDER, "Road.png"))
        IMG_PLAYER = pygame.image.load(os.path.join(IMAGE_FOLDER, "Player.png"))
        IMG_ENEMIES = [
            pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy.png")),
            pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy2.png")),
            pygame.image.load(os.path.join(IMAGE_FOLDER, "Enemy3.png")),
            pygame.image.load(os.path.join(IMAGE_FOLDER, "IceCube.png")),
            pygame.image.load(os.path.join(IMAGE_FOLDER, "Oil.png"))
        ]
        # Returns image, optional arguement is for specific enemy image
        @classmethod
        def GetImage(self, name, opt = 0):
            # Set to lowercase for consistency
            name = name.lower().strip()
            # Return requested image
            if name == 'road':
                return self.IMG_ROAD
            elif name == 'player':
                return self.IMG_PLAYER
            elif name == 'enemy':
                return self.IMG_ENEMIES[opt]
        # Returns length of enemies array
        @classmethod
        def GetEnemyAmt(self):
            return len(self.IMG_ENEMIES)
    ### Game classes
    # Player - is also a spite, so deafult to all sprite parameters (inheritance)
    class Player(pygame.sprite.Sprite):
        def __init__(self, imgs):
            # Initialize the sprite stuff
            super().__init__()
            # Calculate initial player position
            h = imgs.GetImage('road').get_width()//2
            v = imgs.GetImage('road').get_height() - (imgs.GetImage('player').get_height()//2)
            # Create player sprite
            self.image = imgs.GetImage('player')
            self.surf = pygame.Surface(imgs.GetImage('player').get_size())
            self.rect = self.surf.get_rect(center = (h, v))
        def move(self, imgs, vars):
            # Get keys pressed
            keys = pygame.key.get_pressed()
            # Are we paused?
            if vars.IsPaused() :
                # Check for SPACE
                if not keys[K_SPACE]:
                    # Turn off pause
                    vars.PauseToggle()
            else:
                # Check for LEFT key
                if keys[K_LEFT] and self.rect.left > 0:
                    # Move left
                    self.rect.move_ip(-vars.GetSpeed(), 0)
                    # Make sure we didn't go too far left
                    if self.rect.left < 0:
                        # To far, fix it
                        self.rect.left = 0
                #  Check for RIGHT key
                if keys[K_RIGHT] and self.rect.right < imgs.GetImage('road').get_width():
                    # Move right
                    self.rect.move_ip(vars.GetSpeed(), 0)
                    # Make sure we didn't go too far right
                    if self.rect.right > imgs.GetImage('road').get_width():
                        # To far, fix it
                        self.rect.right = imgs.GetImage('road').get_width()
                # Check for SPACE key
                if keys[K_SPACE]:
                    # Turn on pause
                    vars.PauseToggle()
        # Hit oil slick, teleport
        def teleport(self, imgs):
            # Set the rect to a random position for next render
            h = random.randrange(imgs.GetImage('player').get_width()//2, imgs.GetImage('road').get_width() - imgs.GetImage('player').get_width()//2)
            v = imgs.GetImage('road').get_height() - (imgs.GetImage('player').get_height()//2)
            self.rect = self.surf.get_rect(center = (h, v))
    # All enemies and obstacles - is also a spite, so deafult to all sprite parameters (inheritance)
    class Enemy(pygame.sprite.Sprite):
        def __init__(self, imgs, vars):
            # Initialize the sprite stuff
            super().__init__()
            # Get a random enemy
            vars.SetEnemy(random.randrange(0, imgs.GetEnemyAmt()))
            # Calculate initial enemy position
            hl = imgs.GetImage('enemy', vars.GetEnemy()).get_width()//2
            hr = imgs.GetImage('road').get_width() - imgs.GetImage('enemy', vars.GetEnemy()).get_width()//2
            h = random.randrange(hl, hr)
            v = 0
            # Create enemy sprite
            self.image = imgs.GetImage('enemy', vars.GetEnemy())
            self.surf = pygame.Surface(imgs.GetImage('enemy', vars.GetEnemy()).get_size())
            self.rect = self.surf.get_rect(center = (h, v))
        def move(self, imgs, vars):
            # Move enemy downwards
            self.rect.move_ip(0, vars.GetSpeed())
            # Check didn't go off edge of screen
            if (self.rect.bottom > imgs.GetImage('road').get_height()):
                # Kill enemy object
                self.kill()
                # No enemy
                vars.SetEnemy(-1)
                # Increase the speed and score
                vars.RaiseSpeed()
    # Game init
    def __init__(self):
        # Load data - just high score for now
        self.Variables.Load()
        # Initialize PyGame
        pygame.init()
        # Initialize frame manager
        self.clock = pygame.time.Clock()
        # Set frame rate
        self.clock.tick(60)
        # Set caption bar
        pygame.display.set_caption("Crazy Driver")
        # Initialize game screen
        self.screen = pygame.display.set_mode(self.Images.GetImage('road').get_size())
        # Create player and add to game object group
        self.gameObjects.add(self.Player(self.Images))
        # Start game
        self.Play()
    ### Game functions
    # Main play
    def Play(self):
        # Main game loop
        while True:
            # Update caption with score
            pygame.display.set_caption("Crazy Driver - Score " + str(self.Variables.GetScore()))
            # Place background
            self.screen.blit(self.Images.GetImage('road'), (0,0))
            # Create enemy if needed and add to game object group
            if self.Variables.GetEnemy() == -1:
                self.gameObjects.add(self.Enemy(self.Images, self.Variables))
            # Blit all objects
            for obj in self.gameObjects:
                self.screen.blit(obj.image, obj.rect)
            # Move all objects
            for obj in self.gameObjects:
                obj.move(self.Images, self.Variables)
            # Check for collision
            # Loop through sprite group
            for obj in self.gameObjects:
                # If obj is of type Player (not Enemy)
                if type(obj) is self.Player:
                    # Remove player from group for collision testing
                    self.gameObjects.remove(obj)
                    # If any collisions occured (True term says to destroy enemy if so)
                    if pygame.sprite.spritecollide(obj, self.gameObjects, True):
                        # If ice cube...
                        if self.Variables.GetEnemy() == 3:
                            # Set speed back to start speed
                            self.Variables.ResetSpeed()
                        # If oil slick
                        elif self.Variables.GetEnemy() == 4:
                            # Move player to random location
                            obj.teleport(self.Images)
                        # Otherwise it's a regular enemy...
                        else:
                            # End game
                            self.GameOver()
                        self.Variables.SetEnemy(-1)
                    # If game isn't over, put player object back into group as testing is done
                    self.gameObjects.add(obj)
            # Check for events
            for event in pygame.event.get():
                # Did the player quit?
                if event.type == QUIT:
                    # Quit pygame
                    pygame.quit()
                    sys.exit()
            # Update screen
            pygame.display.update()
    # GameOver function - Displays message and cleans things up
    def GameOver(self):
        # Get text variables
        (font, sizeGameOver, sizeScore) = self.Variables.GetTextParams()
        # Game Over text creation
        fontGameOver = pygame.font.SysFont(font, sizeGameOver)
        textGameOver = fontGameOver.render("Game Over!", True, self.Variables.GetColor('red'))
        rectGameOver = textGameOver.get_rect()
        rectGameOver.center = (self.Images.GetImage('road').get_width()//2, self.Images.GetImage('road').get_height()//2)
        # Score text creation
        fontScore = pygame.font.SysFont(font, sizeScore)
        textScore = fontScore.render("Score: " + str(self.Variables.GetScore()), True, self.Variables.GetColor('red'))
        rectScore = textScore.get_rect()
        rectScore.center = (self.Images.GetImage('road').get_width()//2, self.Images.GetImage('road').get_height()//2 + self.Images.GetImage('road').get_height()//8)
        # High score text creation
        textHighScore = fontScore.render("High Score: " + str(self.Variables.GetHighScore()), True, self.Variables.GetColor('red'))
        rectHighScore = textHighScore.get_rect()
        rectHighScore.center = (self.Images.GetImage('road').get_width()//2, self.Images.GetImage('road').get_height()//2 + self.Images.GetImage('road').get_height()//4)
        # Black screen with game over text
        self.screen.fill(self.Variables.GetColor('black'))
        self.screen.blit(textGameOver, rectGameOver)
        self.screen.blit(textScore, rectScore)
        self.screen.blit(textHighScore, rectHighScore)
        # Update the display
        pygame.display.update()
        # Destroy objects
        for obj in self.gameObjects:
            obj.kill()
        # Pause
        time.sleep(5)
        # Quit pygame
        pygame.quit()
        sys.exit()
# Actual class call
Game()

4 responses to “Captain Code: Code”

  1. Chris Avatar
    Chris

    There is no code for the challenges related to chapter 10.

    1. BenForta Avatar
      BenForta

      The code for the 3 Chapter 10 Challenges are on the Challenges page.

  2. Ryan Zhou Avatar
    Ryan Zhou

    Where are the pictures for crazy driver?

    1. BenForta Avatar
      BenForta

      Go to the main book page https://forta.com/books/0137653573/, scroll down, you’ll see a link for them.

Leave a Reply