Game Development Reference
In-Depth Information
If there are no corner moves, we will go through the entire list and find out which move
gives us the highest score. The
for
loop will set
x
and
y
to every move in
possibleMoves
.
bestMove
will be set to the highest scoring move we've found so far,
and
bestScore
will be set to the best move's score. When the code in the loop finds a
move that scores higher than
bestScore
, we will store that move and score as the new
values of
bestMove
and
bestScore
.
Simulate All Possible Moves on Duplicate Board Data Structures
In order to figure out the score of the possible move we are currently iterating on, we
first make a duplicate game board data structure by calling
getBoardCopy()
. We want
a copy so we can modify without changing the real game board data structure stored in the
board
variable.
Then we call
makeMove()
, passing the duplicate board instead of the real board.
makeMove()
will handle placing the computer's tile and the flipping the player's tiles on
the duplicate board.
We call
getScoreOfBoard()
with the duplicate board, which returns a dictionary
where the keys are
'X'
and
'O'
, and the values are the scores.
getScoreOfBoard()
does not know if the computer is
'X'
or
'O'
, which is why it returns a dictionary.
By making a duplicate board, we can simulate a future move and test the results of that
move without changing the actual game board data structure. This is very helpful in
deciding which move is the best possible move to make.
Pretend that
getScoreOfBoard()
returns the dictionary
{'X':22, 'O':8}
and
computerTile
is
'X'
. Then
getScoreOfBoard(dupeBoard)
[computerTile]
would evaluate to
{'X':22, 'O':8}['X']
, which would then
evaluate to
22
. If
22
is larger than
bestScore
,
bestScore
is set to
22
and
bestMove
is set to the current
x
and
y
values we are looking at. By the time this
for
loop is finished, we can be sure that
bestScore
is the highest possible score a move can
make, and that move is stored in
bestMove
.
You may have noticed that on line 228 we first set
bestScore
to
-1
. This is so that
the first move we look at in our
for
loop over
possibleMoves
will be set to the first
bestMove
. This will guarantee that
bestMove
is set to one of the moves when we return
it.
Say that the highest scoring move in
possibleMoves
would give the computer a
score of
42
. What if there was more than one move in
possibleMoves
that would give
this score? The
for
loop we use would always go with the first move that scored
42
points, because
bestMove
and
bestScore
only change if the move is greater than the
highest score. A tie will not change
bestMove
and
bestScore
.