Game Development Reference
In-Depth Information
13 - Sonar Treasure Hunt
The numbers on the first line which mark the tens position all have nine spaces in
between them, and there are thirteen spaces in front of the 1. We are going to create a string
with this line and store it in a variable named hline .
13. # print the numbers across the top
14. print(hline)
15. print(' ' + ('0123456789' * 6))
16. print()
To print the numbers across the top of the sonar board, we first print the contents of the
hline variable. Then on the next line, we print three spaces (so that this row lines up
correctly), and then print the string
'012345678901234567890123456789012345678901234567890123456789'
But this is tedious to type into the source, so instead we type ( '0123456789' * 6 )
which evaluates to the same string.
Drawing the Rows of the Ocean
18. # print each of the 15 rows
19. for i in range(15):
20. # single-digit numbers need to be padded with an
extra space
21. if i < 10:
22. extraSpace = ' '
23. else:
24. extraSpace = ''
25. print('%s%s %s %s' % (extraSpace, i, getRow
(board, i), i))
Now we print the each row of the board, including the numbers down the side to label
the Y-axis. We use the for loop to print rows 0 through 14 on the board, along with the
row numbers on either side of the board.
We have a small problem. Numbers with only one digit (like 0, 1, 2, and so on) only take
up one space when we print them out, but numbers with two digits (like 10, 11, and 12)
take up two spaces. This means the rows might not line up and would look like this:
8 ~~`~`~~```~``~~``~~~``~~`~`~~`~`~```~```~~~```~~~~~~`~`~~~~` 8
9 ```~``~`~~~`~~```~``~``~~~```~````~```~`~~`~~~~~`~``~~~~~``` 9
10 `~~~~```~`~````~`~`~~``~`~~~~`~``~``~```~~```````~`~``~````` 10
11 ~~`~`~~`~``~`~~~````````````````~~`````~`~~``~`~~~~`~~~`~~`~ 11
The solution is easy. We just add a space in front of all the single-digit numbers. The if-
else statement that starts on line 21 does this. We will print the variable extraSpace
when we print the row, and if i is less than 10 (which means it will have only one digit),
Search WWH ::




Custom Search