Adventure Game 2: Add Objects

Now we have the locations sorted, we need to add objects to the game. These will be things such as keys and chests. Later on we’ll add code so that the player can use these objects

Note how I’m only using 3 locations while I write this game. It’s always a good idea to keep things simple. Get the mechanics of the game working first, and then expand it.

Copy and paste the code below into your IDE.

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 Main():
    ans = ""
    global location
    print(places[0])
    print_objects()


    while ans != "bye":
        ans = input("What now?")
        if ans in moves[location]:
            location = moves[location].get(ans)
            print(places[location])
            print_objects()
        else:
            print("I can't move that way")


Main()

Exercise

  1. Look at the objects dictionary `objects = {“spanner”:0, “lockpick”:0, “spade”:2}`. What do the keys in the dictionary represent? (hint: the key is the part before the colon:)
  2. What do the values in the dictionary represent?
  3. Add “rope” to the list of objects. Place it in the cave.
  4. Add “torch” to the list of objects. Place it in the cabin.
  5. Run the code and check the objects are where you think they should be.
  6. Look at the print_objects() function. Explain how it works

Extension

  1. Draw your own map for a game. Implement it. Modify the code so that you are using your map.
  2. Add your own objects to the map.
  3. Add code so that if the user types “l” (for look) the game prints out the current location and a list of objects.

Leave a Comment