Adventure Game 5: Adding New Commands and Tidying Old Ones

We’re going to add two new commands, Look and Items

  • Look will show your current location and objects
  • Items will show the items you’re currently carrying
places = ["A clearing in a forest", "An old wooden cabin", "A dark cave"]
moves = [{"n": 1, "s": 2},           {"s": 0},              {"n": 0}]
objects = {"spanner":0,  "lockpick":0, "spade":2}
location = 0

def print_objects():
    for key, val in objects.items():
        if val == location:
            print(key)

def items():
    print("You are carrying: ")
    for key, val in objects.items():
        if val == 99:
            print(key)


def take_object(noun):
    for key, val in objects.items():
        if key == noun and val == location:
            print("Got it!")
            objects[noun] = 99

def drop_object(noun):
    for key, val in objects.items():
        if key ==noun and val == 99:
            print("Dropped ", noun)
            objects[noun] = location


def Main():
    ans = ""
    global location
    print(places[0])
    print_objects()


    while ans != "bye":
        ans = input("What now?")
        words = ans.split()

        # Check if it's a one word input
        if len(words) == 1:
            if ans == "items":
                items()
            elif ans == "look":
                print(places[location])
                print_objects()
            elif ans in moves[location]:
                location = moves[location].get(ans)
                print(places[location])
                print_objects()
            else:
                print("I can't move that way")
        else:
            verb = words[0] # e.g. Take or Drop
            noun = words[1] # e.g. hammer or spanner

            if verb == "take":
                take_object(noun)

            elif verb == "drop":
                drop_object(noun)

            else:
                print("I don't understand what you mean")

Main()

Exercise

  1. Look at the Main() function. Why is location a global variable?
  2. List the one word commands that are permitted in this program
  3. What does the printobjects() function do?
  4. Look at the items() function. Why does it only print items where val =99?

You’re going to add a help function. If the user enters “help” the program will print the following instructions: “Type n,s,e,w to move north, south, east and west.”

  1. Add an elif statment under the elif ans == “look”: statement to check if the user has entered “help”
  2. Add code to print the help instructions

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.