Game Development Reference
In-Depth Information
15 - Reversi
Asking the Player to Play Again
152. def playAgain():
153. # This function returns True if the player wants to
play again, otherwise it returns False.
154. print('Do you want to play again? (yes or no)')
155. return input().lower().startswith('y')
We have used the
playAgain()
in our previous games. If the player types in
something that begins with
'y'
, then the function returns
True
. Otherwise the function
returns
False
.
Placing Down a Tile on the Game Board
158. def makeMove(board, tile, xstart, ystart):
159. # Place the tile on the board at xstart, ystart, and
flip any of the opponent's pieces.
160. # Returns False if this is an invalid move, True if
it is valid.
161. tilesToFlip = isValidMove(board, tile, xstart,
ystart)
makeMove()
is the function we call when we want to place a tile on the board and flip
the other tiles according to the rules of Reversi. This function modifies the
board
data
structure that is passed as a parameter directly. Changes made to the
board
variable
(because it is a list) will be made to the global scope as well. Most of the work is done by
isValidMove()
, which returns a list of XY coordinates (in a two-item list) of tiles that
need to be flipped. (Remember, if the the
xstart
and
ystart
arguments point to an
invalid move, then
isValidMove()
will return the Boolean value
False
.)
163. if tilesToFlip == False:
164. return False
165.
166. board[xstart][ystart] = tile
167. for x, y in tilesToFlip:
168. board[x][y] = tile
169. return True
If the return value of
isValidMove()
was
False
, then
makeMove()
will also
return
False
.
Otherwise,
isValidMove()
would have returned a list of spaces on the board to put
down our tiles (the
'X'
or
'O'
string in tile). Line 166 sets the space that the player has
moved on, and the
for
loop after that sets all the tiles that are in
tilesToFlip
.