Game Development Reference
In-Depth Information
10 - Tic Tac Toe
The
None
Value
None
is a special value that you can assign to a variable. The
None
value represents the
lack of a value.
None
is the only value of the data type NoneType. (Just like the boolean
data type has only two values, the NoneType data type has only one value,
None
.) It can be
very useful to use the
None
value when you have not set a variables value yet. For
example, say you had a variable named
quizAnswer
which holds the user's answer to
some True-False pop quiz question. You could set
quizAnswer
to
None
if the user
skipped the question or did not answer it. Using
None
would be better because if you set it
to
True
or
False
before assigning the value of the user's answer, it may look like the user
gave an answer the question even though they didn't.
Calls to functions that do not return anything (that is, they exit by reaching the end of the
function and not from a return statement) will evaluate to
None
. The
None
value is written
without quotes and with a capital "N" and lowercase "one".
How the Code Works: Lines 96 to 187
Creating the Computer's Artificial Intelligence
96. def getComputerMove(board, computerLetter):
97. # Given a board and the computer's letter, determine
where to move and return that move.
98. if computerLetter == 'X':
99. playerLetter = 'O'
100. else:
101. playerLetter = 'X'
The
getComputerMove()
function is where our AI will be coded. The parameters
are a Tic Tac Toe board (in the
board
parameter) and which letter the computer is (either
'X'
or
'O'
). The first few lines simply assign the other letter to a variable named
playerLetter
. This lets us use the same code, no matter who is X and who is O. This
function will return the integer that represents which space the computer will move.
Remember how our algorithm works:
First, see if there is a move the computer can make that will win the game. If there is,
take that move. Otherwise, go to the second step.
Second, see if there is a move the player can make that will cause the computer to lose
the game. If there is, we should move there to block the player. Otherwise, go to the third
step.
Third, check if any of the corner spaces (spaces 1, 3, 7, or 9) are free. (We always want
to take a corner piece instead of the center or a side piece.) If no corner piece is free, then