import operator, random #Board: #[[1,2,3], # [4,5,6], # [7,8,9]] X=0 X=1 class Board: def __init__(self, size): """Size is in cols/rows""" self.size=size self.board=[map(lambda x: x+1, list(range(size)))] self.boardDict={} for i in range(size-1): self.board.append(map(lambda x: x+size, self.board[-1])) for i in range(size**2): i=i+1 self.boardDict[i]='\x00' # for i in (1,6,7): # self.boardDict[i]="o" # for i in (3,5,7): # self.boardDict[i]="x" for i in range(9): self.setSpace(i+1, random.choice(['x', 'o'])) def setSpace(self, space, char): if space in self.boardDict.keys(): self.boardDict[space]=char else: return -1 def displayBoard(self): for row in self.board: print map(lambda x: self.boardDict[x], row) def isComplete(self): _board=[] for row in self.board: _col=[] for col in row: _col.append(ord(self.boardDict[col])) _board.append(_col) # print "Check: " + self._check(_board) # if self._check(_board) == 'x' or self._check(_board) == 'o': k=self.boardDict.values() while len(k) != 0: print "%s %s %s" % (k.pop(0),k.pop(0),k.pop(0)) return self._check(_board) def _reverse(self, r): r.reverse() def _check(self, _board): winner=None for row in _board: if reduce(operator.and_, row) != 0: winner=reduce(operator.and_, row) if winner != 104: return chr(winner) for row in zip(*_board): if reduce(operator.and_, row) != 0: winner=reduce(operator.and_, row) if winner != 104: return chr(winner) # for i in range(self.size): if reduce(operator.and_, map(lambda y: _board[y][y], range(self.size))) != 0: winner=reduce(operator.and_, map(lambda y: _board[y][y], range(self.size))) if winner != 104: return chr(winner) map(self._reverse, _board) if reduce(operator.and_, map(lambda y: _board[y][y], range(self.size))) != 0: winner=reduce(operator.and_, map(lambda y: _board[y][y], range(self.size))) map(self._reverse, _board) if winner != 104: return chr(winner) if 0 not in self.boardDict.values(): return -1 return winner # reduce(operator.and_, somedict.values) is not 0: