Game Development Reference
In-Depth Information
How the Code Works: Lines 83 to 94
Choosing a Move from a List of Moves
83. def chooseRandomMoveFromList(board, movesList):
84. # Returns a valid move from the passed list on the
passed board.
85. # Returns None if there is no valid move.
86. possibleMoves = []
87. for i in movesList:
88. if isSpaceFree(board, i):
89. possibleMoves.append(i)
The
chooseRandomMoveFromList()
function will be of use to us when we are
implementing the code for our AI. The first parameter
board
is the 10-string list that
represents a Tic Tac Toe board. The second parameter movesList is a list of integers that
represent possible moves. For example, if
movesList
is
[1, 3, 7, 9]
, that means
we should return the number for one of the corner spaces on the board.
The
chooseRandomMoveFromList()
function will then choose one of those moves
from the
possibleMoves
list. It also makes sure that the move that it chooses is not
already taken. To do this, we create a blank list and assign it to
possibleMoves
. The
for
loop will go through the list of moves passed to this function in
movesList
. If that
move is available (which we figure out with a call to
isSpaceFree()
), then we add it to
possibleMoves
with the
append()
method.
91. if len(possibleMoves) != 0:
92. return random.choice(possibleMoves)
93. else:
94. return None
At this point, the
possibleMoves
list has all of the moves that were in
movesList
that are also free spaces on the board represented by
board
. If the list is not empty, then
there is at least one possible move that can be made on the board.
This list might be empty. For example, if
movesList
was
[1, 3, 7, 9]
but the
board represented by the
board
parameter had all the corner spaces already taken, the
possibleMoves
list would have been empty.
If
possibleMoves
is empty, then
len(possibleMoves)
will evaluate to
0
and
the code in the else-block will execute. Notice that it returns something called
None
.