Game Development Reference
In-Depth Information
13 - Sonar Treasure Hunt
The for loop for cx, cy in chests: combines both of these principles.
Because chests is a list where each item in the list is itself a list of two integers, the first
of these integers is assigned to cx and the second integer is assigned to cy . So if chests
has the value [[5, 0], [0, 2], [4, 2]] , on the first iteration through the loop,
cx will have the value 5 and cy will have the value 0 .
Line 73 determines which is larger: the absolute value of the difference of the X
coordinates, or the absolute value of the difference of the Y coordinates. ( abs(cx - x)
< abs(cy - y) seems like much easier way to say that, doesn't it?). The if-else
statement assigns the larger of the values to the distance variable.
So on each iteration of the for loop, the distance variable holds the distance of a
treasure chest's distance from the sonar device. But we want the shortest (that is, smallest)
distance of all the treasure chests. This is where the smallestDistance variable comes
in. Whenever the distance variable is smaller than smallestDistance , then the
value in distance becomes the new value of smallestDistance .
We give smallestDistance the impossibly high value of 100 at the beginning of
the loop so that at least one of the treasure chests we find will be put into
smallestDistance . By the time the for loop has finished, we know that
smallestDistance holds the shortest distance between the sonar device and all of the
treasure chests in the game.
81. if smallestDistance == 0:
82. # xy is directly on a treasure chest!
83. chests.remove([x, y])
84. return 'You have found a sunken treasure chest!'
The only time that smallestDistance is equal to 0 is when the sonar device's XY
coordinates are the same as a treasure chest's XY coordinates. This means the player has
correctly guessed the location of a treasure chest. We should remove this chest's two-
integer list from the chests data structure with the remove() list method.
The remove() List Method
The remove() list method will remove the first occurrence of the value passed as a
parameter from the list. For example, try typing the following into the interactive shell:
>>> x = [42, 5, 10, 42, 15, 42]
>>> x.remove(10)
>>> x
[42, 5, 42, 15, 42]
Search WWH ::




Custom Search