| 41 | |
| 42 | |
| 43 | class TTTBoard: |
| 44 | def __init__(self): |
| 45 | """Create a new, blank tic-tac-toe board.""" |
| 46 | # Map of space numbers: 1|2|3 |
| 47 | # -+-+- |
| 48 | # 4|5|6 |
| 49 | # -+-+- |
| 50 | # 7|8|9 |
| 51 | # Keys are 1 through 9, the values are X, O, or BLANK. |
| 52 | self.spaces = {} |
| 53 | for space in ALLspaces: |
| 54 | self.spaces[space] = BLANK # All spaces start as blank. |
| 55 | |
| 56 | def getBoardStr(self): |
| 57 | """Return a text-representation of the board.""" |
| 58 | return ''' |
| 59 | {}|{}|{} 1 2 3 |
| 60 | -+-+- |
| 61 | {}|{}|{} 4 5 6 |
| 62 | -+-+- |
| 63 | {}|{}|{} 7 8 9'''.format(self.spaces['1'], self.spaces['2'], |
| 64 | self.spaces['3'], self.spaces['4'], self.spaces['5'], |
| 65 | self.spaces['6'], self.spaces['7'], self.spaces['8'], |
| 66 | self.spaces['9']) |
| 67 | |
| 68 | def isValidSpace(self, space): |
| 69 | """Returns True if the space on the board is a valid space |
| 70 | number and the space is blank.""" |
| 71 | return space in ALLspaces and self.spaces[space] == BLANK |
| 72 | |
| 73 | def isWinner(self, player): |
| 74 | """Return True if player is a winner on this TTTBoard.""" |
| 75 | # Shorter variable names used here for readablility: |
| 76 | s, p = self.spaces, player |
| 77 | # Check for 3 marks across 3 rows, 3 columns, and 2 diagonals. |
| 78 | return ((s['1'] == s['2'] == s['3'] == p) or # Across top |
| 79 | (s['4'] == s['5'] == s['6'] == p) or # Across middle |
| 80 | (s['7'] == s['8'] == s['9'] == p) or # Across bottom |
| 81 | (s['1'] == s['4'] == s['7'] == p) or # Down left |
| 82 | (s['2'] == s['5'] == s['8'] == p) or # Down middle |
| 83 | (s['3'] == s['6'] == s['9'] == p) or # Down right |
| 84 | (s['3'] == s['5'] == s['7'] == p) or # Diagonal |
| 85 | (s['1'] == s['5'] == s['9'] == p)) # Diagonal |
| 86 | |
| 87 | def isBoardFull(self): |
| 88 | """Return True if every space on the board has been taken.""" |
| 89 | for space in ALLspaces: |
| 90 | if self.spaces[space] == BLANK: |
| 91 | return False # If any space is blank, return False. |
| 92 | return True # No spaces are blank, so return True. |
| 93 | |
| 94 | def updateBoard(self, space, player): |
| 95 | """Sets the space on the board to player.""" |
| 96 | self.spaces[space] = player |
| 97 | |
| 98 | |
| 99 | class MiniTTTBoard(TTTBoard): |