Hardware Reference
In-Depth Information
Listing 3-6 continued
print 'Player',swapPlayer(player_turn),'wins ;
... New Game'
else:
print 'A draw. ... New game'
def generateMove():
global board
moves = list()
for squares in range(0, len(board) ):
if board[squares] == ' ' :
moves.append(squares)
shuffle(moves)
board[moves[0]] = 'O'
print 'My move is ',moves[0] +1
Note here that I have only shown the irst three functions as all the other functions remain
the same. he irst thing to spot is the use of the random library
from random import shuffle
his imports the random function shuffle , which you will use to rearrange a list of valid
moves into a random order so that the game played by the computer varies. he play
function is much as before, but where it difers is when it is player O's move - then the
generateMove() function is called. his function starts of by deining a list called moves ,
which at irst is empty. hen a for loop visits every square on the board, and if a square is
blank it appends the square's number to the moves list. he shuffle function is used on
the list to get it into a random order, and, as you are only interested in using one move you
select the irst number in that list, the one at position zero. Next, the move is actually made,
and the board is changed. Finally the move number is printed out. Note here that the num-
ber printed out is one more than the square's number because, as mentioned before, you are
representing the squares for the user as 1 to 9 whereas the computer sees them as 0 to 8.
Teaching the Computer to Recognize a Winning Move
So whereas Listing 3-6 plays an entertaining game, it is all very hit and miss; when you play
it it feels more like miss than hit. herefore what you want to do is add a bit of strategy to the
computer's play. It would be good if the computer could spot a move that would cause it to
win. his is quite easily achieved by looking at the results of making the move in each blank
square in turn, and seeing if a win results. As you already have a function that checks for a
win this is not too diicult. Similarly, it would be good if the computer could spot that its
opponent is able to make a winning move and if so then move in that place to block them.
Search WWH ::




Custom Search