We added objects to the game in the last lesson. Now we’re going to add code to allow the user to take and drop objects
Copy and paste the following code 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?")
words = ans.split()
# Check if it's a move
if len(words) == 1:
if 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":
for key, val in objects.items():
if key == noun and val == location:
print("Got it!")
objects[noun] = 99
if verb == "drop":
for key, val in objects.items():
if key ==noun and val == 99:
print("Dropped ", noun)
objects[noun] = location
Main()
Exercise
- Run the game. Take the spanner and drop it in the cave. Check that everything is working correctly.
- Add a spoon to the list of objects. Place the spoon in the cave. Check that you can Take it and Drop it.
- What happens if you enter “take elephant?”
- Look at the line
words = ans.split()
in the Main() function. What does it do? (try experimenting with the code in IDLE if you’re unsure) - Look at the if statement in the Main() function:
if len(words) == 1:
Why was that code included? - Look at the statement
if verb == "take":
What do key and val mean in the for loop? - What is the purpose of the for loop?
- What is the purpose of the line
'objects[noun] == 99'
- Look at the
if verb = "drop"
statement. Why does the for loop check if key = noun and val == 99?