Game Development Reference
In-Depth Information
15 - Reversi
possible moves that the computer can make. We will select the best move from this list.
219. # randomize the order of the possible moves
220. random.shuffle(possibleMoves)
First, we are going to use the
random.shuffle()
function to randomize the order of
moves in the
possibleMoves
list. Remember that the
random.shuffle()
function
will reorder the items in the list that you pass to it. The function also modifies the list
directly, much like our
resetBoard()
function does with the game board data structure.
We will explain why we want to shuffle the
possibleMoves
list, but first let's look at
our algorithm.
Corner Moves are the Best Moves
222. # always go for a corner if available.
223. for x, y in possibleMoves:
224. if isOnCorner(x, y):
225. return [x, y]
First, we loop through every move in
possibleMoves
and if any of them are on the
corner, we return that as our move. Corner moves are a good idea because once a tile has
been placed on the corner, it can never be flipped over. Since
possibleMoves
is a list of
two-item lists, we use the multiple assignment trick in our
for
loop to set
x
and
y
.
Because we immediately return on finding the first corner move in
possibleMoves
,
if
possibleMoves
contains multiple corner moves we always go with the first one. But
since
possibleMoves
was shuffled on line 220, it is completely random which corner
move is first in the list.
Get a List of the Best Scoring Moves
227. # Go through all the possible moves and remember the
best scoring move
228. bestScore = -1
229. for x, y in possibleMoves:
230. dupeBoard = getBoardCopy(board)
231. makeMove(dupeBoard, computerTile, x, y)
232. score = getScoreOfBoard(dupeBoard)[computerTile]
233. if score > bestScore:
234. bestMove = [x, y]
235. bestScore = score
236. return bestMove