[Tutor] programming tic tac toe
bob gailer
bgailer at gmail.com
Thu Aug 21 20:17:10 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
> 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.
I tend to think in terms of classes and lists. So I wrote the following.
A bit messy and complex, but easy to follow.
# tic tac toe
class Cell:
player = None
def __eq__(self, other):
return self.player and other.player and self.player == other.player
class Line:
def __init__(self, *x):
self.cells = [cells[y] for y in x]
def winner(self):
return self.cells[0] == self.cells[1] == self.cells[2]
cells = [Cell() for row in range(9)]
rows = [Line(0,3,6), Line(1,4,7), Line(2,5,8)]
cols = [Line(0,1,2), Line(3,4,5), Line(6,7,8)]
diags = [Line(0,4,8), Line(2,4,6)]
lines = rows + cols + diags
# in lieu of playing a game I just tested with a blank board and then
with a row of X's
for line in lines:
if line.winner():
print "winner"
break
else:
print "no winner"
# Mark row 1 all X
for cell in rows[1].cells:
cell.player = 'X'
for line in lines:
if line.winner():
print "winner"
bresk
else:
print "no winner"
--
Bob Gailer
Chapel Hill NC
919-636-4239
When we take the time to be aware of our feelings and
needs we have more satisfying interatctions with others.
Nonviolent Communication provides tools for this awareness.
As a coach and trainer I can assist you in learning this process.
What is YOUR biggest relationship challenge?
More information about the Tutor
mailing list