Created
March 6, 2017 19:14
-
-
Save nsaphra/f386c35a1d8bd3a564c28d3aa236e8ab to your computer and use it in GitHub Desktop.
recurse center interview code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class NoughtsAndCrosses: | |
| NOUGHT = "O" | |
| CROSS = "X" | |
| EMPTY = " " | |
| STALEMATE = "Nobody" | |
| def __init__(self): | |
| self.board = [[self.EMPTY] * 3, [self.EMPTY] * 3, [self.EMPTY] * 3] | |
| def print_board(self): | |
| print(" 0 1 2") | |
| print("0 " + " ".join(self.board[0])) | |
| print("1 " + " ".join(self.board[1])) | |
| print("2 " + " ".join(self.board[2])) | |
| def is_stalemate(self): | |
| for row in self.board: | |
| for cell in row: | |
| if cell == self.EMPTY: | |
| return False | |
| return True | |
| def is_victory(self, user): | |
| for idx in range(3): | |
| # check horizontal | |
| if user == self.board[idx][0] and user == self.board[idx][1] and user == self.board[idx][2]: | |
| return True | |
| # check vertical | |
| if user == self.board[0][idx] and user == self.board[1][idx] and user == self.board[2][idx]: | |
| return True | |
| # check diagonal | |
| if user == self.board[1][1]: | |
| if user == self.board[0][0] and user == self.board[2][2]: | |
| return True | |
| if user == self.board[0][2] and user == self.board[2][0]: | |
| return True | |
| return False | |
| def next_user_move(self): | |
| while 1: | |
| s = raw_input("Enter the next row and column digits: ") | |
| if len(s) != 2: | |
| print("Input should be in the form of 2 digits, e.g. '02'.") | |
| continue | |
| try: | |
| row = int(s[0]) | |
| col = int(s[1]) | |
| except ValueError: | |
| print("Input should be in the form of 2 digits, e.g. '02'.") | |
| continue | |
| if row > 2 or col > 2: | |
| print("Coordinates must be digits 0, 1, or 2.") | |
| continue | |
| if self.board[row][col] != self.EMPTY: | |
| print("Coordinates must be to an empty cell.") | |
| continue | |
| return (row, col) | |
| def next_turn_result(self, user): | |
| assert(user == self.NOUGHT or user == self.CROSS) | |
| (row, col) = self.next_user_move() | |
| self.board[row][col] = user | |
| self.print_board() | |
| if self.is_victory(user): | |
| return user | |
| if self.is_stalemate(): | |
| return self.STALEMATE | |
| return self.EMPTY | |
| def next_turn_ends(self, user): | |
| result = game.next_turn_result(user) | |
| if result is game.EMPTY: | |
| return False | |
| print(result + " is the winner.") | |
| return True | |
| if __name__ == '__main__': | |
| game = NoughtsAndCrosses() | |
| game.print_board() | |
| while 1: | |
| if game.next_turn_ends(game.NOUGHT): | |
| break | |
| if game.next_turn_ends(game.CROSS): | |
| break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment