Game Development Reference
In-Depth Information
13 - Sonar Treasure Hunt
Creating a New Game Board
40. def getNewBoard():
41. # Create a new 60x15 board data structure.
42. board = []
43. for x in range(60): # the main list is a list of 60
lists
44. board.append([])
At the start of each new game, we will need a fresh board data structure. The board
data structure is a list of lists of strings. The first list represents the X coordinate. Since our
game's board is 60 characters across, this first list needs to contain 60 lists. So we create a
for loop that will append 60 blank lists to it.
45. for y in range(15): # each list in the main list
has 15 single-character strings
46. # use different characters for the ocean to
make it more readable.
47. if random.randint(0, 1) == 0:
48. board[x].append('~')
49. else:
50. board[x].append('`')
But board is more than just a list of 60 blank lists. Each of the 60 lists represents the Y
coordinate of our game board. There are 15 rows in the board, so each of these 60 lists must
have 15 characters in them. We have another for loop to add 15 single-character strings
that represent the ocean. The "ocean" will just be a bunch of '~' and '`' strings, so we
will randomly choose between those two. We can do this by generating a random number
between 0 and 1 with a call to random.randint() . If the return value of
random.randint() is 0 , we add the '~' string. Otherwise we will add the '`'
string.
This is like deciding which character to use by tossing a coin. And since the return value
from random.randint() will be 0 about half the time, half of the ocean characters will
be '~' and the other half will be '`' . This will give our ocean a random, choppy look to
it.
Remember that the board variable is a list of 60 lists that have 15 strings. That means
to get the string at coordinate 26, 12, we would access board[26][12] , and not board
[12][26] . The X coordinate is first, then the Y coordinate.
Here is the picture to demonstrate the indexes of a list of lists named x . The red arrows
point to indexes of the inner lists themselves. The image is also flipped on its side to make
it easier to read:
Search WWH ::




Custom Search