This has been shamelessly borrowed from Chris Luce, as he showed them in one of my
tutorials last week.
This example shows a Tic Tac Toe board, to see if there is a win in a
board, or if it’s a cats game.
def printBoard ( board ):
for i in range ( 0 , len ( board )):
for j in range ( 0 , len ( board [ 0 ])):
print board [ i ][ j ],
print
def checkWinner ( board ):
#check columns for winner
for i in range ( 0 , len ( board )):
if board [ 0 ][ i ] == " X " and board [ 1 ][ i ] == " X " and board [ 2 ][ i ] == " X " :
return " X "
elif board [ 0 ][ i ] == " O " and board [ 1 ][ i ] == " O " and board [ 2 ][ i ] == " O " :
return " O "
#check rows for winner
for i in range ( 0 , len ( board [ 0 ])):
if board [ i ][ 0 ] == " X " and board [ i ][ 1 ] == " X " and board [ i ][ 2 ] == " X " :
return " X "
elif board [ i ][ 0 ] == " O " and board [ i ][ 1 ] == " O " and board [ i ][ 2 ] == " O " :
return " O "
if board [ 0 ][ 0 ] == " X " and board [ 1 ][ 1 ] == " X " and board [ 2 ][ 2 ] == " X " :
return " X "
elif board [ 0 ][ 0 ] == " O " and board [ 1 ][ 1 ] == " O " and board [ 2 ][ 2 ] == " O " :
return " O "
if board [ 0 ][ 2 ] == " X " and board [ 1 ][ 1 ] == " X " and board [ 2 ][ 0 ] == " X " :
return " X "
elif board [ 0 ][ 2 ] == " O " and board [ 1 ][ 1 ] == " O " and board [ 2 ][ 0 ] == " O " :
return " O "
board = []
board . append ([ ' X ' , ' O ' , ' X ' ])
board . append ([ ' X ' , ' X ' , ' O ' ])
board . append ([ ' O ' , ' O ' , ' X ' ])
printBoard ( board )
winner = checkWinner ( board )
if winner == " X " or winner == " O " :
print " The winner is " , winner
else :
print " Cat ' s game "
This example uses a 2 dimensional list, which you may find helpful to understand for your
assignment.