Game Development Reference
In-Depth Information
10 - Tic Tac Toe
We want to check if the computer won with its last move. The reason we call
drawBoard()
here is because the player will want to see what move the computer made
to win the game. We then set
gameIsPlaying
to
False
so that the game does not
continue. Notice that lines 174 to 177 are almost identical to lines 157 to 160.
178. else:
179. if isBoardFull(theBoard):
180. drawBoard(theBoard)
181. print('The game is a tie!')
182. break
These lines of code are identical to the code on lines 162 to 165. The only difference is
this is a check for a tied game after the computer has moved.
183. else:
184. turn = 'player'
If the game is neither won nor tied, it then becomes the player's turn. There are no more
lines of code inside the
while
loop, so execution would jump back to the
while
statement on line 150.
186. if not playAgain():
187. break
These lines of code are located immediately after the while-block started by the
while
statement on line 150. Remember, we would only exit out of that
while
loop if it's
condition (the
gameIsPlaying
variable) was
False
.
gameIsPlaying
is set to
False
when the game has ended, so at this point we are going to ask the player if they
want to play again.
Remember, when we evaluate the condition in this
if
statement, we call the
playAgain()
function which will let the user type in if they want to play or not.
playAgain()
will return
True
if the player typed something that began with a
'y'
like
'yes'
or
'y'
. Otherwise
playAgain()
will return
False
.
If
playAgain()
returns
False
, then the if statement's condition is
True
(because of
the
not
operator that reverses the Boolean value) and we execute the break statement. That
breaks us out of the
while
loop that was started on line 142. But there are no more lines of
code after that while-block, so the program terminates.