Game Development Reference
In-Depth Information
The sonar's X and Y coordinates are 3 and 2. The first treasure chest's X and Y
coordinates (first in the list [[5, 0], [0, 2], [4, 2]] that is) are 5 and 0.
For the X coordinates, 3 - 5 evaluates to -2 , and the absolute value of -2 is 2 .
For the Y coordinates, 2 - 1 evaluates to 1 , and the absolute value of 1 is 1 .
Comparing the two absolute values 2 and 1 , 2 is the larger value and should be the
distance from the sonar device and the treasure chest at coordinates 5, 1. We can look at the
board and see that this algorithm works, because the treasure chest at 5,1 is in the sonar
device's 2nd ring. Let's quickly compare the other two chests to see if his distances work
out correctly also.
Let's find the distance from the sonar device at 3,2 and the treasure chest at 0,2. abs(3
- 0) evaluates to 3 . The abs() function returns the absolute value of the number we
pass to it. abs(2 - 2) evaluates to 0 . 3 is larger than 0 , so the distance from the sonar
device at 3,2 and the treasure chest at 0,2 is 3 . We look at the board and see this is true.
Let's find the distance from the sonar device at 3,2 and the last treasure chest at 4,2. abs
(3 - 4) evaluates to 1. abs(2 - 2) evaluates to 0 . 1 is larger than 0 , so the distance
from the sonar device at 3,2 and the treasure chest at 4,2 is 1 . We look at the board and see
this is true also.
Because all three distances worked out correctly, our algorithm works. The distances
from the sonar device to the three sunken treasure chests are 2 , 3 , and 1 . On each guess, we
want to know the distance from the sonar device to the closest of the three treasure chest
distances. To do this we use a variable called smallestDistance . Let's look at the
code again:
71. smallestDistance = 100 # any chest will be closer
than 100.
72. for cx, cy in chests:
73. if abs(cx - x) > abs(cy - y):
74. distance = abs(cx - x)
75. else:
76. distance = abs(cy - y)
77.
78. if distance < smallestDistance: # we want the
closest treasure chest.
79. smallestDistance = distance
You can also use multiple assignment in for loops. For example, the assignment
statement a, b = [5, 10] will assign 5 to a and 10 to b . Also, the for loop for i
in [0, 1, 2, 3, 4] will assign the i variable the values 0 and 1 and so on for each
iteration.
Search WWH ::




Custom Search