Hardware Reference
In-Depth Information
print
print
if __name__ == '__main__':
printBoard()
his makes the board look a whole lot better by emphasising the blank squares.
Checking for a Win
Next you need a function that checks if the board shows a win for a player. With an eye on
what is needed later on, you need to write it so that you pass into the function the player's
symbol that you want to test for. Also you need a list of the squares that constitute a win. In
fact there are eight ways to win, so you need a new concept - a list of lists. To see how this
works, look at Listing 3-3.
Listing 3-3 Checking the Tic-Tac-Toe Board for a Win
#!/usr/bin/env python
# Tic-Tac-Toe 3 - check for win
board = [ 'O', 'X', ' ', 'O', ' ', 'X', 'O', 'X', 'X' ]
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 checkWin(player):
win = False
for test in wins :
print test
count = 0
for squares in test :
if board[squares] == player :
count +=1
if count == 3 :
win = True
return win
if __name__ == '__main__':
print 'Checking board for X'
if checkWin('X'):
print 'Game over X wins'
print 'Checking board for O'
if checkWin('O'):
print 'Game over O wins'
 
Search WWH ::




Custom Search