Hardware Reference
In-Depth Information
Deining Functions
Although the game works, you will ind it diicult to scale it up to include more loca-
tions and directions, such as going into the cave and then deeper into the cave, espe-
cially if the game relies on input from players to make decisions. You could add more
conditionals by copying and pasting those you have already created but your code will
get messy and out of control very quickly. It will also be diicult to locate any bugs, or
make changes without introducing even more bugs!
he best solution is to create your own functions. Until now you have been using pre-
existing functions from other Python modules such as time and random , but you
can also create your own. Writing your own functions is easy; for example, this is how
you would write a function called multiply that multiplies its two arguments and
returns the result:
def multiply(m, n):
return m * n
Just like the functions you used earlier in this adventure, these can take a number of
arguments and return a result. hey are a very useful way of organising your code. You
can use various ways to reorganise your code into diferent functions. his process is
called refactoring and is a logical process when developing computer programs. One
way of reorganising the adventure game you have created so far is to create and use
two functions: get_input() and handle_room() .hese functions are described in
the following sections.
Refactoring is a way of restructuring code you have already written to make it
more eficient and easy to read, and to avoid bugs. If you ind yourself copying
and pasting large sections of code, this is usually a good indicator that you need
to refactor your code!
The get_input Function
he get_input() function will keep asking the player to enter input (using the text
in the prompt argument) until it matches one of the accepted inputs. For example:
get_input(“Do you want to go left or right? “, [“left”, “right”])
his function will keep asking the player the same question until she types one of the
accepted inputs, which in this case are left and right .
Search WWH ::




Custom Search