[Tutor] programming tic tac toe
Alan Gauld
alan.gauld at btinternet.com
Thu Aug 21 07:53:50 CEST 2008
"Ark" <cloudneozero at gmail.com> wrote
> 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
> 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.
Given that there are always 3x3 cells on an oxo board and
therefore only 8 possible winning lines hard coding is probably
a reasonable approach. You could make it into a single boolean
condition which would be slightly less typing and slightly faster
but otherwise what you have is fine I think:
def line(board):
return board[0][0] == board[0][1] == board[0][2] or
board[1][0] == board[1][1] == board[1][2] or
...
board[2][0] == board[1][1] == board[[0][2]
But I'm not sure its that much nicer! :-)
For the more general case of an NxN board then you
should probably consider using a loop and relative
indexing but for 3x3 hard coded is better IMHO.
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list