Game Development Reference
In-Depth Information
10 - Tic Tac Toe
148. gameIsPlaying = True
The
whoGoesFirst()
function randomly decides who goes first, and returns either the
string
'player'
or the string
'computer'
. On line 147, we tell the player who will go
first. The
gameIsPlayer
variable is what we will use to keep track of whether the game
has been won, lost, tied or if it is the other player's turn.
Running the Player's Turn
150. while gameIsPlaying:
This is a loop that will keep going back and forth between the player's turn and the
computer's turn, as long as
gameIsPlaying
is set to
True
.
151. if turn == 'player':
152. # Player's turn.
153. drawBoard(theBoard)
154. move = getPlayerMove(theBoard)
155. makeMove(theBoard, playerLetter, move)
The turn variable was originally set by
whoGoesFirst()
. It is either set to
'player'
or
'computer'
. If
turn
contains the string
'computer'
, then the condition is
False
and execution will jump down to line 169.
The first thing we do when it is the player's turn (according to the flow chart we drew at
the beginning of this chapter) is show the board to the player. Calling the
drawBoard()
and passing the
theBoard
variable will print the board on the screen. We then let the
player type in his move by calling our
getPlayerMove()
function, and set the move on
the board by calling our
makeMove()
function.
157. if isWinner(theBoard, playerLetter):
158. drawBoard(theBoard)
159. print('Hooray! You have won the game!')
160. gameIsPlaying = False
Now that the player has made his move, our program should check if they have won the
game with this move. If the
isWinner()
function returns
True
, we should show them the
winning board (the previous call to
drawBoard()
shows the board
before
they made the
winning move) and print a message telling them they have won.
Then we set
gameIsPlaying
to
False
so that execution does not continue on to the
computer's turn.