Hardware Reference
In-Depth Information
Getting the Computer to Play
While you now have the computer keeping track of the game, it is not much more than a
gloriied piece of paper. he fun starts when you get the computer to generate moves in place
of one of the players. here are many levels you can do this at, ranging from the computer
giving you a poor playing opponent to one of the computer being invincible. Of course, play-
ing a computer at each end of this range is not as much fun as playing one somewhere in the
middle. In this section you will look at several ways you can make the computer an increas-
ingly skillful opponent. Because the behaviour that programs like this exhibit often looks like
there is some intelligence at play, this sort of programming is often known as artiicial intel-
ligence, or AI for short. Although I regularly maintain that artiicial intelligence is the ability
some students have of passing exams without actually understanding very much.
The Computer As a Five Year Old
In the irst level of AI, the computer knows the rules but not much else. It can play the game
but has no strategy and can only make a winning move by chance. To do this, the computer
must gather a list of valid moves and choose one at random. Functions to do this are shown
in Listing 3-6.
Listing 3-6 A Computer Opponent Tic-Tac-Toe Game
#!/usr/bin/env python
# Tic-Tac-Toe 6 - play against the computer random move
from random import shuffle
def play() :
global board
print 'Tic-Tac-Toe'
print 'play against the computer AI level 0'
printBoard()
while True :
wipeBoard()
player_turn = 'X'
while checkWin(swapPlayer(player_turn),board) == False;
and canMove() == True :
if player_turn == 'X':
getMove(player_turn)
else:
generateMove()
printBoard()
player_turn = swapPlayer(player_turn)
if checkWin(swapPlayer(player_turn),board):
continued
Search WWH ::




Custom Search