Hardware Reference
In-Depth Information
Flow diagrams are a bit out of favor nowadays, but as their name implies, they are good for
showing the low of an algorithm and the decisions that have to be made. One problem is
that it can be much harder, with today's programming languages and structures, to translate
the low directly into code. However, for beginners I still feel there is great merit in these
diagrams, especially relatively short low diagrams. Anything in a diamond requires a deci-
sion, and there are two or more possible changes in the low depending on that decision.
Now these sorts of statements are ine when you are describing the strategy to another
human being, but when you write code you have to be more speciic. he way I have decided
to implement this is to write a function that is given a list of possible moves; the function
will check this list to see if the board is free to take one or more of these moves, and
pick a random move from the list if it is. Most of the logic to do this was used in the
randomMove() function. he new functions to do this are shown in Listing 3-9.
Listing 3-9 An Intelligent Move Strategy
def generateMove():
if win_block():
pass
elif prefMove([0,2,6,8]): # corners
pass
elif prefMove([5]): # centre
pass
else:
prefMove([1,3,5,7]) # middle row
def prefMove(moves):
global board
moved = False
move = list()
for potential in moves:
if board[potential] == ' ':
move.append(potential)
if len(move) != 0:
shuffle(move)
board[move[0]] = 'O'
print 'My move is ',move[0] + 1
moved = True
return moved
Again I have only shown the functions that have changed. he big change this time is the
prefMove() function. his is passed a list of preferred moves from the generateMoves()
function; notice this is a list, and it is given in square brackets inside the curved brackets.
After the win_block() function is called, a list of all the corners is passed. If that does not
 
Search WWH ::




Custom Search