[Tutor] programming tic tac toe

Emile van Sebille emile at fenx.com
Thu Aug 21 10:03:50 CEST 2008


Ark wrote:
> Hi.
> I programmed a simple tic tac toe game in python.  I already finished 
> it, but I'm not pleased with the way I used to identify a line.
> I used a list (with lists inside) to represent the board.  And to 
> identify a winning line I used many if's, like this one:
> def line(board):
>     if board[0][0] == board[1][1] == board[2][2]:
>         return True
>     ...
>     ...
>     return False

#Assuming you number the board positions as:
#board = [ [0,1,2],
#          [3,4,5],
#          [6,7,8] ]

#then you could define the winning combinations as:

winners = [ (0,1,2),(3,4,5),(6,7,8), #rows
             (0,3,6),(1,4,7),(2,5,8), #cols
             (0,4,8),(6,4,2)          #diags
             ]

#and return all these combinations from the current board with:

def mapped(board):
     return [ (board[i/3][i%3],board[j/3][j%3],board[k/3][k%3])
              for i,j,k in winners]

#and finally, assuming you're using X's and Y's,
#identify a winning line with:

def line(board):
      if ( ('X','X','X') in mapped(board) or
           ('Y','Y','Y') in mapped(board) ):
          return True
      return False

#now two test cases
board = ([['X','Y','Y'],
           ['Y','X','X'],
           ['Y','X','Y']
          ])

print line(board)

board = ([['X','Y','Y'],
           ['Y','X','X'],
           ['Y','Y','X']
          ])

print line(board)

HTH,

Emile



> It's only an examble, but I did it that way.
> I did not like using all those if's, and I would like to hear 
> suggestions to find a line in the board, maybe a more  intelligent approach.
> I would like a solution using lists because it would be useful for 
> example in C too, but I have been thinking about another way to 
> represent a board.
> 
> Ark
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list