Game Development Reference
In-Depth Information
13 - Sonar Treasure Hunt
How the Code Works: Lines 94 to 162
The last few functions we need are to let the player enter their move on the game board,
ask the player if he wants to play again (this will be called at the end of the game), and print
the instructions for the game on the screen (this will be called at the beginning of the
game).
Getting the Player's Move
94. def enterPlayerMove():
95. # Let the player type in her move. Return a two-item
list of int xy coordinates.
96. print('Where do you want to drop the next sonar
device? (0-59 0-14) (or type quit)')
97. while True:
98. move = input()
99. if move.lower() == 'quit':
100. print('Thanks for playing!')
101. sys.exit()
This function collects the XY coordinates of the player's next move. It has a while loop
so that it will keep asking the player for her next move. The player can also type in quit
in order to quit the game. In that case, we call the sys.exit() function which
immediately terminates the program.
103. move = move.split()
104. if len(move) == 2 and move[0].isdigit() and move
[1].isdigit() and isValidMove(int(move[0]), int(move
[1])):
105. return [int(move[0]), int(move[1])]
106. print('Enter a number from 0 to 59, a space, then
a number from 0 to 14.')
Assuming the player has not typed in 'quit' , we call the split() method on move
and set the list it returns as the new value of move . What we expect move to be is a list of
two numbers. These numbers will be strings, because the split() method returns a list of
strings. But we can convert these to integers with the int() function.
If the player typed in something like '1 2 3' , then the list returned by split()
would be ['1', '2', '3'] . In that case, the expression len(move) == 2 would
be False and the entire expression immediately evaluates to False (because of
expression short-circuiting.)
If the list returned by split() does have a length of 2 , then it will have a move [0] and
move[1] . We call the string method isdigit() on those strings. isdigit() will
Search WWH ::




Custom Search