The program is becoming very complicated. We need to apply structured programming techniques to make it easier to follow. According to the specification this means:
“Using modularised programming, clear, well documented interfaces (local variables, parameters) and return values.”
Copy 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 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 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":
take_object(noun)
elif verb == "drop":
drop_object(noun)
else:
print("I don't understand what you mean")
Main()
Exercise
- Copy the code into an IDE and run it. Check that it works
- Give an example of a local variable in the code.
- Give an example of a global variable.
- Give an example of a parameter.
- How many functions have parameters passed to them?
- What are the advantages of the modular approach?
- Add a function eat_object(noun). The function will print “I can’t eat” + noun.
- Add code to the Main method to call the eat_object() function