Game Development Reference
In-Depth Information
13 - Sonar Treasure Hunt
204. print('You have found all the sunken treasure
chests! Congratulations and good game!')
205. break
Remember that the
makeMove()
function modifies the
theChests
list we send it.
Because
theChests
is a list, any changes made to it inside the function will persist after
execution returns from the function.
makeMove()
removes items from
theChests
when
treasure chests are found, so eventually (if the player guesses correctly) all of the treasure
chests will have been removed. (Remember, by "treasure chest" we mean the two-item lists
of the XY coordinates inside the
theChests
list.)
When all the treasure chests have been found on the board and removed from
theChests
, the
theChests
list will have a length of
0
. When that happens, we display a
congratulations to the player, and then execute a
break
statement to break out of this
while
loop. Execution will then move down to line 209 (the first line after the while-
block.)
Checking if the Player has Lost
207. sonarDevices -= 1
This is the last line of the
while
loop that started on line 179. We decrement the
sonarDevices
variable because the player has used one. If the player keeps missing the
treasure chests, eventually
sonarDevices
will be reduced to
0
. After this line, execution
jumps back up to line 179 so we can re-evaluate the
while
statement's condition (which is
sonarDevices > 0
). If
sonarDevices
is
0
, then the condition will be
False
and
execution will continue outside the while-block on line 209.
But until then, the condition will remain
True
and the player can keep making guesses.
209. if sonarDevices == 0:
210. print('We\'ve run out of sonar devices! Now we
have to turn the ship around and head')
211. print('for home with treasure chests still out
there! Game over.')
212. print(' The remaining chests were here:')
213. for x, y in theChests:
214. print(' %s, %s' % (x, y))
Line 209 is the first line outside the
while
loop. By this point the game is over. But how
do we tell if the player won or not? The only two places where the program execution would
have left the
while
loop is on line 179 if the condition failed. In that case,
sonarDevices
would be
0
and the player would have lost.