This is used in a text-based game to determine if a different room has been entered in order to run a function. It is learning exercise so I am sure the code is not optimal. The whole thing is started by running the code on the last line.
def runner(map, start):
next = start
while True:
room = map[next]
print "\n--------"
next = room()
runner(ROOMS, 'central_corridor')
Here is the ROOMS dictionary that is being used as a argument in the runner function:
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
So, more specifically, my question is how is this while loop being used to run the function of the next room if the next room has been entered within the game? I sense the answer lies with the next iterator contained in the while loop.
The code would be much simpler to understand if we rename the variables. Never name variables map
or next
since doing so shadows the builtins of the same name.
Here is what the same code might look like after renaming map
and next
:
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
def runner(visit, start):
room = start
while True:
action = visit[room]
print "\n--------"
room = action()
runner(ROOMS, 'central_corridor')
The visit
variable is a dict which maps rooms to actions (which are functions). The return value of an action is a room.
So
action = visit[room]
looks up the action that occurs when you visit a room, and
room = action()
sets room
to the value of the next room after action
has been performed.