Hardware Reference
In-Depth Information
else:
randomMove()
def win_block(): #move to win or block
global board
testBoard = board
players = ['O','X']
moveMade = False
for moveTry in players:
for square in range(0, len(board) ) :
if testBoard[square] == ' ' and moveMade == False:
testBoard[square] = moveTry
if checkWin(moveTry,testBoard):
board[square] = 'O'
moveMade = True
print 'My move is ',square + 1
else:
testBoard[square] = ' ' # retract move
return moveMade
You will see that the name is changed, as is the code in the generateMove() function. All
the other functions remain unchanged. he main addition to the function is the extra list
named players , which contains the two symbols to use. hen the extra for loop selects
one of these symbols on each pass by the variable moveTry .
he section “Errors” at the start of this chapter discusses logical errors; developing the win_
block function initially produced one of these errors. When I wrote the irst draft of this
function, the loop that changed what symbol was being used was placed on the other side of
the next for loop. his actually appeared to work until I spotted that sometimes the pro-
gram would ignore a winning move in favor of blocking the opponent. It turned out that this
was because each square was being tested irst - for the computer's symbol and then for the
opponent's. his meant that if the computer found a blocking move irst it would choose
that. herefore, I needed to move the for moveTry statement to its current position so
that all the winning moves were scanned before the blocking moves were looked at.
Adding Some Strategy
At this point the game is being played with a modicum of intelligence but still no strategy. You
need to devise a playing strategy to use. A strong one but by no means the only one is shown in
Figure 3-2, which shows the sort of choices that are made when picking a move. Basically after
checking for a winning or blocking move, if there are corners free, then pick one, or if the centre
is free, pick it; inally, if none of the previous conditions applies, pick one of the sides.
Search WWH ::




Custom Search