Game Development Reference
In-Depth Information
13 - Sonar Treasure Hunt
theChests a list of three treasure chests at random places on the board.
previousMoves A list of all the XY moves that the player has made in the game.
Displaying the Game Status for the Player
179. while sonarDevices > 0:
180. # Start of a turn:
181.
182. # show sonar device/chest status
183. if sonarDevices > 1: extraSsonar = 's'
184. else: extraSsonar = ''
185. if len(theChests) > 1: extraSchest = 's'
186. else: extraSchest = ''
187. print('You have %s sonar device%s left. %s
treasure chest%s remaining.' % (sonarDevices,
extraSsonar, len(theChests), extraSchest))
This while loop executes as long as the player has sonar devices remaining. We want
to print a message telling the user how many sonar devices and treasure chests are left. But
there is a problem. If there are two or more sonar devices left, we want to print '2 sonar
devices' . But if there is only one sonar device left, we want to print '1 sonar
device' left. We only want the plural form of devices if there are multiple sonar devices.
The same goes for '2 treasure chests' and '1 treasure chest' .
Notice on lines 183 through 186 that we have code after the if and else statements'
colon. This is perfectly valid Python. Instead of having a block of code after the statement,
instead you can just use the rest of the same line to make your code more concise. (Of
course, this means you can only have one line of code for the if-block and else-block.) This
applies to any statement that uses colons, including while and for loops.
So we have two string variables named extraSsonar and extraSchest , which are
set to ' ' (space) if there are multiple sonar devices or treasures chests. Otherwise, they
are blank. We use them in the while statement on line 187.
Getting the Player's Move
189. x, y = enterPlayerMove()
190. previousMoves.append([x, y]) # we must track all
moves so that sonar devices can be updated.
191.
192. moveResult = makeMove(theBoard, theChests, x, y)
193. if moveResult == False:
194. continue
Line 189 uses the multiple assignment trick. enterPlayerMove() returns a two-item
 
Search WWH ::




Custom Search