Hardware Reference
In-Depth Information
The handle_room Function
he handle_room() function will contain the main logic for changing locations in
the adventure game. he function will take the current location as its argument, and
then use conditionals to decide what to do based on that location. For most locations,
the function will ask the player to input a direction. he speciic input determines
which location the player will move to next.
Creating a Main Game Loop
Up to this point, you wrote all of your game logic in the while loop. With the follow-
ing code, you move most of the logic into separate functions, avoiding repetitive code.
he new loop calls the handle_room() function to perform a task appropriate for
the current room, and then updates the location variable with the new room. his
is a little more advanced than the code you have written so far. It will require you to
check and double-check that your indentation is correct and you have not made any
syntax errors!
Open a new text editor window and save the ile as AdventureGame2.py in your
Documents directory. Follow the steps below to add functions to your adventure
game.
A
You can download the completed AdventureGame2.py code ile from the
companion website at www.wiley.com/go/adventuresinrp but, as I
mentioned earlier, you will learn more by typing in the code as you read through
the steps.
1. Begin by creating the health point variable as before; it is important to do this at
the start as it is a global variable, meaning it can be accessed by the functions you
will deine:
# Create health points variable
hp = 30
2. Next, deine the irst of the functions, get_input() . he word def introduces
a function deinition. his function will ask for input from the player with the
given prompt, and as it contains a while loop it will keep retrying until the
player types one of the words in the accepted list, left or right . he in keyword
allows you to check easily whether a value is in a list or not.
def get_input(prompt, accepted):
while True:
value = input(prompt).lower()
if value in accepted:
Search WWH ::




Custom Search