Hardware Reference
In-Depth Information
result in a move, a list of all the centre squares is passed. Of course, there is only one centre
square, so it is a short list, but the important thing is that it is a list, and the same logic can
operate on it all the same. Finally a list of squares in the middle of each row is passed to the
prefMove() function. his works just like the randomMove() function, which is no longer
needed, in that it examines the state of the board for each square in the list, and compiles a
list of free squares - that is, ones without symbols already in them. hen prefMove shules
the list and chooses the irst element. his produces a good game but one that is possible to
beat if the random moves chosen are not the right ones. Nevertheless, it is fun to play and
good practice in developing the playing strategy even further.
Reining the Computer's Strategy
Because the game of tic-tac-toe is relatively short, it turns out that the irst move the com-
puter makes is vital in its success, so in this next version you reine the move choice for the
irst move only. Basically, if the human player opened by playing a corner, the computer
must respond with the opposite corner if it is to prevent the human from winning. As it is,
sometimes this happens by the random choice of corner, but not always. Also, if the human
opens with a middle row square, the response should be an adjacent corner square. he
whole listing, with all the functions in it this time, is shown in Listing 3-10.
Listing 3-10 An Improved Computer Playing Strategy
#!/usr/bin/env python
# Tic-Tac-Toe 10 - play against the computer AI level 3
from random import shuffle
board = [ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]
wins = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], ;
[1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]
def play() :
global board
print 'Tic-Tac-Toe'
print 'play against the computer AI level 3'
printBoard()
while True :
wipeBoard()
move = 0
player_turn = 'X'
while checkWin(swapPlayer(player_turn),board) == ;
False and canMove() == True :
if player_turn == 'X':
getMove(player_turn)
move +=1
Search WWH ::




Custom Search