Game Development Reference
In-Depth Information
13 - Sonar Treasure Hunt
We will pass the numChests parameter to tell the function how many treasure chests
we want it to generate. We set up a for loop to iterate this number of times, and on each
iteration we append a list of two random integers. The X coordinate can be anywhere from
0 to 59, and the Y coordinate can be from anywhere between 0 and 14. The expression
[random.randint(0, 59), random.randint(0, 14)] that is passed to the
append method will evaluate to something like [2, 2] or [2, 4] or [10, 0] . This
data structure is then returned.
Determining if a Move is Valid
60. def isValidMove(x, y):
61. # Return True if the coordinates are on the board,
otherwise False.
62. return x >= 0 and x <= 59 and y >= 0 and y <= 14
The player will type in X and Y coordinates of where they want to drop a sonar device.
But they may not type in coordinates that do not exist on the game board. The X
coordinates must be between 0 and 59, and the Y coordinate must be between 0 and 14.
This function uses a simple expression that uses and operators to ensure that each
condition is True . If just one is False , then the entire expression evaluates to False .
This Boolean value is returned by the function.
How the Code Works: Lines 64 to 91
Placing a Move on the Board
64. def makeMove(board, chests, x, y):
65. # Change the board data structure with a sonar device
character. Remove treasure chests
66. # from the chests list as they are found. Return
False if this is an invalid move.
67. # Otherwise, return the string of the result of this
move.
68. if not isValidMove(x, y):
69. return False
In our Sonar game, the game board is updated to display a number for each sonar device
dropped. The number shows how far away the closest treasure chest is. So when the player
makes a move by giving the program an X and Y coordinate, we will change the board
based on the positions of the treasure chests. This is why our makeMove() function takes
four parameters: the game board data structure, the treasure chests data structures, and the
X and Y coordinates.
This function will return the False Boolean value if the X and Y coordinates if was
passed do not exist on the game board. If isValidMove() returns False , then
Search WWH ::




Custom Search