Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Board(object):
- """
- A tictactoe board using coordinates.
- Coordinates start at (0,0) in the top left.
- >>> myboard = Board()
- >>> myboard.set((0,1), 'x')
- >>> myboard.set((0,1), 'foo')
- Traceback (most recent call last):
- ...
- ValueError: state must be one of 'x', 'o', or ' '
- >>> myboard.set((7,1), 'o')
- Traceback (most recent call last):
- ...
- ValueError: coord does not exist
- >>> myboard.get((0,1))
- 'x'
- >>> myboard.get('banana')
- Traceback (most recent call last):
- ...
- ValueError: coord does not exist
- >>> myboard.set((0,0), 'x')
- >>> myboard.has_row()
- []
- >>> myboard.set((0,2), 'x')
- >>> myboard.has_row()
- ['x']
- """
- def __init__(self):
- self.board = {i: " " for i in itertools.product((0,1,2), repeat=2)}
- def set(self, coord, state):
- """
- Set a space on the board to `state`.
- For e.g.: set((0,1), 'x')
- """
- if state not in ('x', 'o', ' '):
- raise ValueError("state must be one of 'x', 'o', or ' '")
- elif coord not in self.board.keys():
- raise ValueError("coord does not exist")
- else:
- self.board[coord] = state
- def get(self, coord):
- """
- Get the state of the space at `coord`.
- """
- try:
- return self.board[coord]
- except KeyError:
- raise ValueError("coord does not exist")
- def filled(self):
- """
- Return amount of spaces filled.
- """
- f = 0
- for v in self.board.itervalues():
- if v != ' ':
- f += 1
- return f
- def has_row(self):
- """
- Return a list of players who have a row of three.
- """
- across = [[i for i in itertools.product([0,1,2], [n])] for n in xrange(3)]
- down = [[(b, a) for a, b in i] for i in across]
- diag = [
- [(0,0), (1,1), (2,2)],
- [(0,2), (1,1), (2,0)],
- ]
- results = []
- for row in itertools.chain(across, down, diag):
- values = [self.board[c] for c in row]
- if values == ['x', 'x', 'x']:
- results.append('x')
- if values == ['o', 'o', 'o']:
- results.append('o')
- return results
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement