Game Development Reference
In-Depth Information
index
0
, which is just a placeholder that we ignore). If there is at least one space in
board
that is set to a single space
' '
then it will return
False
.
The
for
loop will let us check spaces 1 through 9 on the Tic Tac Toe board. (Remember
that
range(1, 10)
will make the
for
loop iterate over the integers
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
, and
9
.) As soon as it finds a free space in the board (that is, when
isSpaceFree
(board, i)
returns
True
), the
isBoardFull()
function will return
False
.
If execution manages to go through every iteration of the loop, we will know that none of
the spaces are free. So at that point, we will execute
return True
.
The Start of the Game
140. print('Welcome to Tic Tac Toe!')
Line 140 is the first line that isn't inside of a function, so it is the first line of code that is
executed when we run this program.
142. while True:
143. # Reset the board
144. theBoard = [' '] * 10
This
while
loop has
True
for the condition, so that means we will keep looping in this
loop until we encounter a
break
statement. Line 144 sets up the main Tic Tac Toe board
that we will use, named
theBoard
. It is a 10-string list, where each string is a single
space ' '. Remember the little trick using the multiplication operator with a list to replicate
it:
[' '] * 10
. That evaluates to
[' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ']
, but is shorter for us to type
[' '] * 10
.
Deciding the Player's Mark and Who Goes First
145. playerLetter, computerLetter = inputPlayerLetter()
The
inputPlayerLetter()
function lets the player type in whether they want to be
X or O. The function returns a 2-string list, either
['X', 'O']
or
['O', 'X']
. We use
the multiple assignment trick here that we learned in the Hangman chapter. If
inputPlayerLetter()
returns
['X', 'O']
, then
playerLetter
is set to 'X' and
computerLetter
is set to 'O'. If
inputPlayerLetter()
returns
['O', 'X']
,
then
playerLetter
is set to 'O' and
computerLetter
is set to 'X'.
146. turn = whoGoesFirst()
147. print('The ' + turn + ' will go first.')