Game Development Reference
In-Depth Information
10 - Tic Tac Toe
If the human player cannot win in one more move, the for loop will eventually stop and
execution continues on to line 120.
Checking the Corner, Center, and Side Spaces (in that Order)
120. # Try to take one of the corners, if they are free.
121. move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
122. if move != None:
123. return move
Our call to chooseRandomMoveFromList() with the list of [1, 3, 7, 9] will
ensure that it returns the integer for one of the corner spaces. (Remember, the corner spaces
are represented by the integers 1 , 3 , 7 , and 9 .) If all the corner spaces are taken, our
chooseRandomMoveFromList() function will return the None value. In that case,
we will move on to line 125.
125. # Try to take the center, if it is free.
126. if isSpaceFree(board, 5):
127. return 5
If none of the corners are available, we will try to move on the center space if it is free. If
the center space is not free, the execution moves on to line 129.
129. # Move on one of the sides.
130. return chooseRandomMoveFromList(board, [2, 4, 6, 8])
This code also makes a call to chooseRandomMoveFromList() , except we pass it
a list of the side spaces ( [2, 4, 6, 8] ). We know that this function will not return
None , because the side spaces are the only spaces we have not yet checked. This is the end
of the getComputerMove() function and our AI algorithm.
Checking if the Board is Full
132. def isBoardFull(board):
133. # Return True if every space on the board has been
taken. Otherwise return False.
134. for i in range(1, 10):
135. if isSpaceFree(board, i):
136. return False
137. return True
The last function we will write is isBoardFull() , which returns True if the 10-
string list board argument it was passed has an 'X' or 'O' in every index (except for
Search WWH ::




Custom Search