Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. class Board(object):
  2. """
  3. A tictactoe board using coordinates.
  4.  
  5. Coordinates start at (0,0) in the top left.
  6.  
  7. >>> myboard = Board()
  8.  
  9. >>> myboard.set((0,1), 'x')
  10. >>> myboard.set((0,1), 'foo')
  11. Traceback (most recent call last):
  12. ...
  13. ValueError: state must be one of 'x', 'o', or ' '
  14. >>> myboard.set((7,1), 'o')
  15. Traceback (most recent call last):
  16. ...
  17. ValueError: coord does not exist
  18.  
  19. >>> myboard.get((0,1))
  20. 'x'
  21. >>> myboard.get('banana')
  22. Traceback (most recent call last):
  23. ...
  24. ValueError: coord does not exist
  25.  
  26. >>> myboard.set((0,0), 'x')
  27. >>> myboard.has_row()
  28. []
  29. >>> myboard.set((0,2), 'x')
  30. >>> myboard.has_row()
  31. ['x']
  32. """
  33.  
  34. def __init__(self):
  35. self.board = {i: " " for i in itertools.product((0,1,2), repeat=2)}
  36.  
  37. def set(self, coord, state):
  38. """
  39. Set a space on the board to `state`.
  40.  
  41. For e.g.: set((0,1), 'x')
  42. """
  43. if state not in ('x', 'o', ' '):
  44. raise ValueError("state must be one of 'x', 'o', or ' '")
  45. elif coord not in self.board.keys():
  46. raise ValueError("coord does not exist")
  47. else:
  48. self.board[coord] = state
  49.  
  50. def get(self, coord):
  51. """
  52. Get the state of the space at `coord`.
  53. """
  54. try:
  55. return self.board[coord]
  56. except KeyError:
  57. raise ValueError("coord does not exist")
  58.  
  59. def filled(self):
  60. """
  61. Return amount of spaces filled.
  62. """
  63. f = 0
  64.  
  65. for v in self.board.itervalues():
  66. if v != ' ':
  67. f += 1
  68.  
  69. return f
  70.  
  71. def has_row(self):
  72. """
  73. Return a list of players who have a row of three.
  74. """
  75. across = [[i for i in itertools.product([0,1,2], [n])] for n in xrange(3)]
  76. down = [[(b, a) for a, b in i] for i in across]
  77. diag = [
  78. [(0,0), (1,1), (2,2)],
  79. [(0,2), (1,1), (2,0)],
  80. ]
  81.  
  82. results = []
  83.  
  84. for row in itertools.chain(across, down, diag):
  85. values = [self.board[c] for c in row]
  86.  
  87. if values == ['x', 'x', 'x']:
  88. results.append('x')
  89. if values == ['o', 'o', 'o']:
  90. results.append('o')
  91.  
  92. return results
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement