Ben Forta

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, and lots of it.

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. Click on any chapter below to see its code listings, then copy and paste into Visual Studio Code.

How to copy: Click a chapter to expand it, then click the Copy button next to any listing. Switch to VS Code, open a .py file, and paste.

Part 1: It's All Fun & Games

Chapter 1: Getting Started 1 listing
Hello.py
print("Yeah, this works!")
Chapter 2: Mad Libs 5 listings
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 4 listings
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 5 listings
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 1 listing
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 11 listings
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 from 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 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 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 decrypt 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 4 listings
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 4 listings
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 1 listing
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)
    # 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")
    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)
        guessedLetters.sort()
        # Update mask
        displayWord = ""
        for letter in gameWord:
            if letter in guessedLetters:
                displayWord += letter
            else:
                displayWord += maskChar
        # Is it a correct guess?
        if currGuess in gameWord:
            print ("Correct")
        else:
            print ("Nope")
            livesUsed += 1
    print()
# Game play is finished, display results
if displayWord == gameWord:
    print ("You win,", gameWord, "is correct!")
else:
    print ("You lose, the answer was:", gameWord)

Part 2: On an Adventure

Chapter 11: Getting Func-ky 4 listings
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!")
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 3 listings

The text-based adventure game in Part 2 is a Space Adventure. We are also providing starters for two other stories. Pick whichever you prefer, or try them all (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
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
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
doWelcome()
doStart()
Superhero Adventure Story Starter: Main.py
##########################################
# Superhero Adventure
# by Ben & Shmuel
##########################################
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).")
def doLab():
    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.")
    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()
    if choice == 'L':
        doHallway()
    elif choice == 'S':
        doLabCloset()
    elif choice == 'C':
        doLabComputer()
def doHallway():
    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....")
    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()
    if choice == 'W': doWeaponsDoor()
    elif choice == 'D': doDeathRoom()
    elif choice == 'E': doExit()
    elif choice == 'L': doLab()
    elif choice == 'S': doHallwaySearch()
    elif choice == 'T': doTrapdoor()
def doLabCloset():
    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.")
    choice=" "
    while not choice in "ES":
        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()
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()
def doTrapdoor():
    print("This currently does nothing. Back to hallway.")
    doHallway()
def doLabComputer():
    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()
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()
def doHallwaySearch():
    print("You find a piece of paper in the garbage can (gross)!")
    print("The password is 'password123'. Seriously?!")
    doHallway()
def doExit():
    print("The door labelled 'Exit' won't budge!")
    print("If only you still had your super-strength....")
    doHallway()
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()
def doDie():
    print("And with that, our hero fell, never to be heard from again.:")
    print("Game Over!")
doOpening()
doLab()
Fantasy Adventure Story Starter: Main.py
##########################################
# Fantasy Adventure
# by Ben & Shmuel
##########################################
def doWelcome():
    print("Welcome adventurer!")
def doClearing():
    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.")
    choice=" "
    while not choice in "NEW":
        print("N = North")
        print("E = East")
        print("W = West")
        choice=input("What do you want to do? [N/E/W]").strip().upper()
    if choice == 'N': doWoods1()
    elif choice == 'E': doVegetationEast()
    elif choice == 'W': doCampSite()
def doVegetationEast():
    print("You slowly work your way through the dense vegetation.")
    print("Progress is slow.")
    print("Eventually the undergrowth thins, and you find yourself 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.")
    choice=" "
    while not choice in "EWR":
        print("E = East")
        print("W = West")
        print("R = Examine rock wall")
        choice=input("What do you want to do? [E/W/R]").strip().upper()
    if choice == 'E': doRiver()
    elif choice == 'W': doClearing()
    elif choice == 'R': doRocks()
def doRocks():
    print("Your eyes wonder over the rocky wall. A crevice catches your attention.")
    print("The rushing water to the east is much louder now.")
    choice=" "
    while not choice in "EWC":
        print("E = East")
        print("W = West")
        print("C = Examine crevice")
        choice=input("What do you want to do? [E/W/C]").strip().upper()
    if choice == 'E': doRiver()
    elif choice == 'W': doClearing()
    elif choice == 'C': doCrevice()
def doCrevice():
    print("The crevice is blocked by what appears to be a spider web.")
    print("There's no way you're tearing through this web, sorry.")
    choice=" "
    while not choice in "B":
        print("B = Back")
        choice=input("What do you want to do? [B]").strip().upper()
    if choice == 'B': doRocks()
def doRiver():
    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.")
    choice=" "
    while not choice in "W":
        print("W = West")
        choice=input("What do you want to do? [W]").strip().upper()
    if choice == 'W': doRocks()
def doCampSite():
    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.")
    choice=" "
    while not choice in "NE":
        print("N = North")
        print("E = East")
        choice=input("What do you want to do? [N/E]").strip().upper()
    if choice == 'N': doForest1()
    elif choice == 'E': doClearing()
def doForest1():
    print("It is dark. This might not be your best idea.")
    choice=" "
    while not choice in "NSEW":
        print("N = North  S = South  E = East  W = West")
        choice=input("What do you want to do? [N/S/E/W]").strip().upper()
    if choice == 'N': doForest2()
    elif choice == 'S': doCampSite()
    elif choice == 'E': doWoods1()
    elif choice == 'W': doHouse()
def doForest2():
    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.")
    doForest1()
def doHouse():
    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.")
    choice=" "
    while not choice in "E":
        print("E = East")
        choice=input("What do you want to do? [E]").strip().upper()
    if choice == 'E': doForest1()
def doWoods1():
    print("You're on a path in the woods. The path continues to the north.")
    print("There are trees all around, and fallen branches.")
    choice=" "
    while not choice in "NSW":
        print("N = North  S = South  W = West")
        choice=input("What do you want to do? [N/S/W]").strip().upper()
    if choice == 'N': doWoods2()
    elif choice == 'S': doClearing()
    elif choice == 'W': doForest1()
def doWoods2():
    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.")
    doGameOver()
def doGameOver():
    print("Game over!")
doWelcome()
doClearing()
Chapter 13: Cleanup Time 2 listings
Main.py
##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
# Welcome the player
def doWelcome():
    print(Strings.get("Welcome"))
# Location: Start
def doStart():
    print(Strings.get("Start"))
    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()
    if choice == 'P': doBoulders()
    elif choice == 'S': doStructure()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
def doBoulders():
    print(Strings.get("Boulders"))
    doStart()
def doStructure():
    print(Strings.get("Structure"))
    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()
    if choice == 'S': doStart()
    elif choice == 'D': doStructureDoor()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
def doStructureDoor():
    print(Strings.get("StructureDoor"))
    print(Strings.get("StructureDoorNoKey"))
    choice=" "
    while not choice in "SR":
        print("S = Back to structure")
        print("R = Run!")
        choice=input("What do you want to do? [S/R]").strip().upper()
    if choice == 'S': doStructure()
    elif choice == 'R': doRun()
def doBeeping():
    pass
def doRun():
    print(Strings.get("Run"))
    gameOver()
def gameOver():
    print(Strings.get("GameOver"))
doWelcome()
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 3 listings
Main.py
##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
import Utils
# Welcome the player
def doWelcome():
    print(Strings.get("Welcome"))
def doStart():
    print(Strings.get("Start"))
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'P': doBoulders()
    elif choice == 'S': doStructure()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
def doBoulders():
    print(Strings.get("Boulders"))
    doStart()
def doStructure():
    print(Strings.get("Structure"))
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStart()
    elif choice == 'D': doStructureDoor()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
def doStructureDoor():
    print(Strings.get("StructureDoor"))
    print(Strings.get("StructureDoorNoKey"))
    choices = [
        ["S", "Back to structure"],
        ["R", "Run!"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStructure()
    elif choice == 'R': doRun()
def doBeeping():
    pass
def doRun():
    print(Strings.get("Run"))
    gameOver()
def gameOver():
    print(Strings.get("GameOver"))
doWelcome()
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 4 listings
Main.py
##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
import Utils
import Inventory as inv
def doWelcome():
    print(Strings.get("Welcome"))
def doStart():
    print(Strings.get("Start"))
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"],
        ["I", "Inventory"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'P': doBoulders()
    elif choice == 'S': doStructure()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
    elif choice == "I":
        inv.display()
        doStart()
def doBoulders():
    if not inv.hasStructureKey():
        print(Strings.get("BouldersKey"))
        inv.takeStructureKey()
    else:
        print(Strings.get("Boulders"))
    doStart()
def doStructure():
    print(Strings.get("Structure"))
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStart()
    elif choice == 'D': doStructureDoor()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
def doStructureDoor():
    print(Strings.get("StructureDoor"))
    if inv.hasStructureKey():
        print(Strings.get("StructureDoorKey"))
    else:
        print(Strings.get("StructureDoorNoKey"))
    choices = [["S", "Back to structure"], ["R", "Run!"]]
    if inv.hasStructureKey():
        choices.insert(0, ["U","Unlock the door"])
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStructure()
    elif choice == 'R': doRun()
    elif choice == 'U': doEnterStructure()
def doBeeping():
    pass
def doEnterStructure():
    pass
def doRun():
    print(Strings.get("Run"))
    gameOver()
def gameOver():
    print(Strings.get("GameOver"))
doWelcome()
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
############################################
def getUserChoice(options):
    validInputs=""
    for opt in options:
        validInputs+=opt[0]
        print(opt[0], "-", opt[1])
    prompt="What do you want to do? [" + validInputs + "]: "
    choice=""
    done=False
    while not done:
        choice=input(prompt).strip().upper()
        if len(choice) > 1:
            choice=choice[0]
        if len(choice) == 1 and choice in validInputs:
            done = True
    return choice
def inputNumber(prompt):
    inp = ""
    while not inp.isnumeric():
        inp = input(prompt).strip()
    return int(inp)
def inputYesNo(text):
    while True:
        x=input(text + " [Y/N]").upper()
        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
}
def takeStructureKey():
    inv["StructureKey"] = True
def dropStructureKey():
    inv["StructureKey"] = False
def hasStructureKey():
    return inv["StructureKey"]
def takeCoins(coins):
    inv["Coins"] += coins
def dropCoins(coins):
    inv["Coins"] -= coins
def numCoins():
    return inv["Coins"]
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 2 listings
Main.py
##########################################
# Space Adventure
# by Ben & Shmuel
##########################################
# Imports
import Strings
import Utils
import Inventory as inv
import Player
# Create player object
p = Player.player()
def doWelcome():
    print(Strings.get("Welcome"))
def doStart():
    print(Strings.get("Start"))
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"],
        ["I", "Inventory"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'P': doBoulders()
    elif choice == 'S': doStructure()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
    elif choice == "I":
        inv.display()
        doStart()
def doBoulders():
    p.visitBoulder()
    if p.getBoulderVisits() == 1:
        print(Strings.get("Boulders"))
    elif p.getBoulderVisits() == 3:
        print(Strings.get("BouldersKey"))
        inv.takeStructureKey()
    else:
        print(Strings.get("Boulders2"))
    doStart()
def doStructure():
    print(Strings.get("Structure"))
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStart()
    elif choice == 'D': doStructureDoor()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
def doStructureDoor():
    print(Strings.get("StructureDoor"))
    if inv.hasStructureKey():
        print(Strings.get("StructureDoorKey"))
    else:
        print(Strings.get("StructureDoorNoKey"))
    choices = [["S", "Back to structure"], ["R", "Run!"]]
    if inv.hasStructureKey():
        choices.insert(0, ["U","Unlock the door"])
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStructure()
    elif choice == 'R': doRun()
    elif choice == 'U': doEnterStructure()
def doBeeping():
    pass
def doEnterStructure():
    pass
def doRun():
    print(Strings.get("Run"))
    gameOver()
def gameOver():
    print(Strings.get("GameOver"))
doWelcome()
doStart()
Player.py
############################################
# Player.py
# player class
############################################
class player:
    # Properties
    name = "Adventurer"
    livesLeft = 3
    boulderVisits = 0
    def getName(self):
        return self.name
    def getLivesLeft(self):
        return self.livesLeft
    def died(self):
        if self.livesLeft > 0:
            self.livesLeft-=1
    def isAlive(self):
        return True if self.livesLeft > 0 else False
    def getBoulderVisits(self):
        return self.boulderVisits
    def visitBoulder(self):
        self.boulderVisits += 1
Chapter 17: Color Your World 3 listings
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()
def doWelcome():
    print(Back.YELLOW+Fore.GREEN+Strings.get("Welcome"))
def doStart():
    print(Fore.GREEN+Strings.get("Start"))
    choices = [
        ["P", "Examine pile of boulders"],
        ["S", "Go to the structure"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"],
        ["I", "Inventory"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'P': doBoulders()
    elif choice == 'S': doStructure()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
    elif choice == "I":
        inv.display()
        doStart()
def doBoulders():
    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()
    doStart()
def doStructure():
    print(Fore.GREEN+Strings.get("Structure"))
    choices = [
        ["S", "Back to start"],
        ["D", "Open the door"],
        ["B", "Walk towards the beeping"],
        ["R", "Run!"]
    ]
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStart()
    elif choice == 'D': doStructureDoor()
    elif choice == 'B': doBeeping()
    elif choice == 'R': doRun()
def doStructureDoor():
    print(Fore.GREEN+Strings.get("StructureDoor"))
    if inv.hasStructureKey():
        print(Fore.GREEN+Strings.get("StructureDoorKey"))
    else:
        print(Fore.RED+Strings.get("StructureDoorNoKey"))
    choices = [["S", "Back to structure"], ["R", "Run!"]]
    if inv.hasStructureKey():
        choices.insert(0, ["U","Unlock the door"])
    choice = Utils.getUserChoice(choices)
    if choice == 'S': doStructure()
    elif choice == 'R': doRun()
    elif choice == 'U': doEnterStructure()
def doBeeping():
    pass
def doEnterStructure():
    pass
def doRun():
    print(Fore.GREEN+Strings.get("Run"))
    gameOver()
def gameOver():
    print(Fore.GREEN+Strings.get("GameOver"))
doWelcome()
doStart()
Utils.py (with colorama)
############################################
# Utils.py
# Utility functions
############################################
from colorama import Fore
def getUserChoice(options):
    validInputs=""
    for opt in options:
        validInputs+=opt[0]
        print(Fore.YELLOW+opt[0], "-", opt[1])
    prompt="What do you want to do? [" + validInputs + "]: "
    choice=""
    done=False
    while not done:
        choice=input(prompt).strip().upper()
        if len(choice) > 1:
            choice=choice[0]
        if len(choice) == 1 and choice in validInputs:
            done = True
    return choice
def inputNumber(prompt):
    inp = ""
    while not inp.isnumeric():
        inp = input(prompt).strip()
    return int(inp)
def inputYesNo(text):
    while True:
        x=input(text + " [Y/N]").upper()
        if x in ["Y", "YES"]:
            return True
        elif x in ["N", "NO"]:
            return False
Inventory.py (with colorama)
############################################
# Inventory.py
# Inventory system
############################################
from colorama import Fore
inv = {
    "StructureKey": False,
    "Coins": 0
}
def takeStructureKey():
    inv["StructureKey"] = True
def dropStructureKey():
    inv["StructureKey"] = False
def hasStructureKey():
    return inv["StructureKey"]
def takeCoins(coins):
    inv["Coins"] += coins
def dropCoins(coins):
    inv["Coins"] -= coins
def numCoins():
    return inv["Coins"]
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+"*****************")

Part 3: Hit the Road

Chapter 19: Crazy Driver 1 listing
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 1 listing
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
pygame.init()
clock = pygame.time.Clock()
clock.tick(60)
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 player
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
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))
# Create enemy
hl=IMG_ENEMY.get_width()//2
hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
h=random.randrange(hl, hr)
v=0
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:
    screen.blit(IMG_ROAD, (0,0))
    screen.blit(player.image, player.rect)
    screen.blit(enemy.image, enemy.rect)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
Chapter 21: We Like To Move It 1 listing
Main.py
# Imports
import sys, os, random
import pygame
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
# Game variables
moveSpeed = 5
GAME_ROOT_FOLDER=os.path.dirname(__file__)
IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
pygame.init()
clock = pygame.time.Clock()
clock.tick(60)
pygame.display.set_caption("Crazy Driver")
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"))
screen = pygame.display.set_mode(IMG_ROAD.get_size())
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
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))
hl=IMG_ENEMY.get_width()//2
hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
h=random.randrange(hl, hr)
v=0
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))
while True:
    screen.blit(IMG_ROAD, (0,0))
    screen.blit(player.image, player.rect)
    keys = pygame.key.get_pressed()
    if keys[K_LEFT] and player.rect.left > 0:
        player.rect.move_ip(-moveSpeed, 0)
        if player.rect.left < 0:
            player.rect.left = 0
    if keys[K_RIGHT] and player.rect.right < IMG_ROAD.get_width():
        player.rect.move_ip(moveSpeed, 0)
        if player.rect.right > IMG_ROAD.get_width():
            player.rect.right = IMG_ROAD.get_width()
    screen.blit(enemy.image, enemy.rect)
    enemy.rect.move_ip(0, moveSpeed)
    if (enemy.rect.bottom > IMG_ROAD.get_height()):
        hl=IMG_ENEMY.get_width()//2
        hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
        h=random.randrange(hl, hr)
        v=0
        enemy.rect.center = (h, v)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
Chapter 22: Crash Bang 1 listing
Main.py
# Imports
import sys, os, random
import pygame
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
moveSpeed = 5
maxSpeed = 10
score = 0
GAME_ROOT_FOLDER=os.path.dirname(__file__)
IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
def GameOver():
    pygame.quit()
    sys.exit()
pygame.init()
clock = pygame.time.Clock()
clock.tick(60)
pygame.display.set_caption("Crazy Driver")
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"))
screen = pygame.display.set_mode(IMG_ROAD.get_size())
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
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))
hl=IMG_ENEMY.get_width()//2
hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
h=random.randrange(hl, hr)
v=0
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))
while True:
    pygame.display.set_caption("Crazy Driver - Score " + str(score))
    screen.blit(IMG_ROAD, (0,0))
    screen.blit(player.image, player.rect)
    keys = pygame.key.get_pressed()
    if keys[K_LEFT] and player.rect.left > 0:
        player.rect.move_ip(-moveSpeed, 0)
        if player.rect.left < 0:
            player.rect.left = 0
    if keys[K_RIGHT] and player.rect.right < IMG_ROAD.get_width():
        player.rect.move_ip(moveSpeed, 0)
        if player.rect.right > IMG_ROAD.get_width():
            player.rect.right = IMG_ROAD.get_width()
    screen.blit(enemy.image, enemy.rect)
    enemy.rect.move_ip(0, moveSpeed)
    if (enemy.rect.bottom > IMG_ROAD.get_height()):
        hl=IMG_ENEMY.get_width()//2
        hr=IMG_ROAD.get_width()-(IMG_ENEMY.get_width()//2)
        h=random.randrange(hl, hr)
        v=0
        enemy.rect.center = (h, v)
        score += 1
        if moveSpeed < maxSpeed:
            moveSpeed += 1
    if pygame.sprite.collide_rect(player, enemy):
        GameOver()
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
Chapter 23: Finishing Touches 1 listing
Main.py
# Imports
import sys, os, random, time
import pygame
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
startSpeed = 5
moveSpeed = startSpeed
maxSpeed = 10
score = 0
eNum = -1
paused = False
textFonts = ['comicsansms','arial']
textSize = 48
GAME_ROOT_FOLDER=os.path.dirname(__file__)
IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "Images")
def GameOver():
    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)
    screen.fill(BLACK)
    screen.blit(textGameOver, rectGameOver)
    pygame.display.update()
    player.kill()
    enemy.kill()
    time.sleep(5)
    pygame.quit()
    sys.exit()
pygame.init()
clock = pygame.time.Clock()
clock.tick(60)
pygame.display.set_caption("Crazy Driver")
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")))
screen = pygame.display.set_mode(IMG_ROAD.get_size())
h=IMG_ROAD.get_width()//2
v=IMG_ROAD.get_height() - (IMG_PLAYER.get_height()//2)
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))
while True:
    pygame.display.set_caption("Crazy Driver - Score " + str(score))
    screen.blit(IMG_ROAD, (0,0))
    screen.blit(player.image, player.rect)
    if eNum == -1:
        eNum = random.randrange(0, len(IMG_ENEMIES))
        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
        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))
    keys = pygame.key.get_pressed()
    if paused:
        if not keys[K_SPACE]:
            moveSpeed=tempSpeed
            paused=False
    else:
        if keys[K_LEFT] and player.rect.left > 0:
            player.rect.move_ip(-moveSpeed, 0)
            if player.rect.left < 0:
                player.rect.left = 0
        if keys[K_RIGHT] and player.rect.right < IMG_ROAD.get_width():
            player.rect.move_ip(moveSpeed, 0)
            if player.rect.right > IMG_ROAD.get_width():
                player.rect.right = IMG_ROAD.get_width()
        if keys[K_SPACE]:
            tempSpeed=moveSpeed
            moveSpeed=0
            paused=True
    screen.blit(enemy.image, enemy.rect)
    enemy.rect.move_ip(0, moveSpeed)
    if (enemy.rect.bottom > IMG_ROAD.get_height()):
        enemy.kill()
        eNum = -1
        score += 1
        moveSpeed += 1
        if moveSpeed < maxSpeed:
            moveSpeed += 1
    if eNum >= 0 and pygame.sprite.collide_rect(player, enemy):
        if eNum == 3:
            moveSpeed = startSpeed
        else:
            GameOver()
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
What's Next? 1 listing

In There's a Lot More to Python we suggest that you build a class-based version of Crazy Driver. Here it is to get you started.

Class version of Crazy Driver: Main.py
# Imports
import sys, os, random, time, pickle
import pygame
from pygame.locals import *
class Game():
    # Game Objects - will hold player and enemies. Initialize 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 constants
        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
        @classmethod
        def Save(self, val):
            db = {"highScore": val}
            pickle.dump(db, open(self.SAVE_DATA_FILE, "wb"))
        @classmethod
        def Load(self):
            if os.path.isfile(self.SAVE_DATA_FILE):
                db = pickle.load(open(self.SAVE_DATA_FILE, "rb"))
                self.highScore = db["highScore"]
        @classmethod
        def GetScore(self): return self.score
        @classmethod
        def GetHighScore(self): return self.highScore
        @classmethod
        def GetColor(self, col):
            col = col.lower().strip()
            if col == 'red': return self.RED
            elif col == 'white': return self.WHITE
            elif col == 'black': return self.BLACK
        @classmethod
        def GetEnemy(self): return self.eNum
        @classmethod
        def SetEnemy(self, val): self.eNum = val
        @classmethod
        def GetSpeed(self): return self.moveSpeed
        @classmethod
        def RaiseSpeed(self):
            self.RaisePoints()
            if self.moveSpeed < self.MAX_SPEED:
                self.moveSpeed += 0.5
        @classmethod
        def RaisePoints(self):
            if self.moveSpeed >= self.MAX_SPEED: self.score += 3
            elif self.moveSpeed > (self.startSpeed + self.MAX_SPEED) / 2: self.score += 2
            else: self.score += 1
            if self.score > self.highScore:
                self.highScore = self.score
                self.Save(self.highScore)
        @classmethod
        def ResetSpeed(self): self.moveSpeed = self.startSpeed
        @classmethod
        def PauseToggle(self):
            if self.moveSpeed == 0: self.moveSpeed = self.tempSpeed
            else: self.tempSpeed = self.moveSpeed; self.moveSpeed = 0
        @classmethod
        def IsPaused(self): return self.moveSpeed == 0
        @classmethod
        def GetTextParams(self): return self.TEXT_FONTS, self.TEXT_SIZE_GAME_OVER, self.TEXT_SIZE_SCORE
    # Images
    class Images():
        GAME_ROOT_FOLDER=os.path.dirname(__file__)
        IMAGE_FOLDER=os.path.join(GAME_ROOT_FOLDER, "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 = [
            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"))
        ]
        @classmethod
        def GetImage(self, name, opt = 0):
            name = name.lower().strip()
            if name == 'road': return self.IMG_ROAD
            elif name == 'player': return self.IMG_PLAYER
            elif name == 'enemy': return self.IMG_ENEMIES[opt]
        @classmethod
        def GetEnemyAmt(self): return len(self.IMG_ENEMIES)
    ### Game classes
    # Player
    class Player(pygame.sprite.Sprite):
        def __init__(self, imgs):
            super().__init__()
            h = imgs.GetImage('road').get_width()//2
            v = imgs.GetImage('road').get_height() - (imgs.GetImage('player').get_height()//2)
            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):
            keys = pygame.key.get_pressed()
            if vars.IsPaused():
                if not keys[K_SPACE]: vars.PauseToggle()
            else:
                if keys[K_LEFT] and self.rect.left > 0:
                    self.rect.move_ip(-vars.GetSpeed(), 0)
                    if self.rect.left < 0: self.rect.left = 0
                if keys[K_RIGHT] and self.rect.right < imgs.GetImage('road').get_width():
                    self.rect.move_ip(vars.GetSpeed(), 0)
                    if self.rect.right > imgs.GetImage('road').get_width(): self.rect.right = imgs.GetImage('road').get_width()
                if keys[K_SPACE]: vars.PauseToggle()
        def teleport(self, imgs):
            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))
    # Enemy
    class Enemy(pygame.sprite.Sprite):
        def __init__(self, imgs, vars):
            super().__init__()
            vars.SetEnemy(random.randrange(0, imgs.GetEnemyAmt()))
            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
            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):
            self.rect.move_ip(0, vars.GetSpeed())
            if (self.rect.bottom > imgs.GetImage('road').get_height()):
                self.kill()
                vars.SetEnemy(-1)
                vars.RaiseSpeed()
    # Game init
    def __init__(self):
        self.Variables.Load()
        pygame.init()
        self.clock = pygame.time.Clock()
        self.clock.tick(60)
        pygame.display.set_caption("Crazy Driver")
        self.screen = pygame.display.set_mode(self.Images.GetImage('road').get_size())
        self.gameObjects.add(self.Player(self.Images))
        self.Play()
    def Play(self):
        while True:
            pygame.display.set_caption("Crazy Driver - Score " + str(self.Variables.GetScore()))
            self.screen.blit(self.Images.GetImage('road'), (0,0))
            if self.Variables.GetEnemy() == -1:
                self.gameObjects.add(self.Enemy(self.Images, self.Variables))
            for obj in self.gameObjects:
                self.screen.blit(obj.image, obj.rect)
            for obj in self.gameObjects:
                obj.move(self.Images, self.Variables)
            for obj in self.gameObjects:
                if type(obj) is self.Player:
                    self.gameObjects.remove(obj)
                    if pygame.sprite.spritecollide(obj, self.gameObjects, True):
                        if self.Variables.GetEnemy() == 3:
                            self.Variables.ResetSpeed()
                        elif self.Variables.GetEnemy() == 4:
                            obj.teleport(self.Images)
                        else:
                            self.GameOver()
                        self.Variables.SetEnemy(-1)
                    self.gameObjects.add(obj)
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            pygame.display.update()
    def GameOver(self):
        (font, sizeGameOver, sizeScore) = self.Variables.GetTextParams()
        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)
        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)
        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)
        self.screen.fill(self.Variables.GetColor('black'))
        self.screen.blit(textGameOver, rectGameOver)
        self.screen.blit(textScore, rectScore)
        self.screen.blit(textHighScore, rectHighScore)
        pygame.display.update()
        for obj in self.gameObjects:
            obj.kill()
        time.sleep(5)
        pygame.quit()
        sys.exit()
# Actual class call
Game()
← Back to Captain Code