|
| 1 | + |
| 2 | +class ConnectGame: |
| 3 | + |
| 4 | + directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, -1), (-1, 1)] |
| 5 | + white = "O" |
| 6 | + black = "X" |
| 7 | + none = "" |
| 8 | + |
| 9 | + def __init__(self, lines): |
| 10 | + self.board = self.make_board(lines) |
| 11 | + assert len(self.board) > 0 |
| 12 | + |
| 13 | + self.width = len(self.board[0]) |
| 14 | + self.height = len(self.board) |
| 15 | + assert self.width > 0 and self.height > 0 |
| 16 | + |
| 17 | + for l in self.board: |
| 18 | + assert len(l) == self.width |
| 19 | + |
| 20 | + def valid(self, x, y): |
| 21 | + return x >= 0 and x < self.width and y >= 0 and y < self.height |
| 22 | + |
| 23 | + def make_board(self, lines): |
| 24 | + return ["".join(l.split()) for l in lines.splitlines()] |
| 25 | + |
| 26 | + def player_reach_dest(self, player, x, y): |
| 27 | + if player == self.black: |
| 28 | + return x == self.width - 1 |
| 29 | + if player == self.white: |
| 30 | + return y == self.height - 1 |
| 31 | + |
| 32 | + def walk_board(self, player, x, y, visited=[]): |
| 33 | + if (x, y) in visited: |
| 34 | + return False |
| 35 | + |
| 36 | + if (not self.valid(x, y)) or self.board[y][x] != player: |
| 37 | + return False |
| 38 | + |
| 39 | + if self.player_reach_dest(player, x, y): |
| 40 | + return True |
| 41 | + |
| 42 | + for d in self.directions: |
| 43 | + if self.walk_board(player, x + d[0], y + d[1], visited + [(x, y)]): |
| 44 | + return True |
| 45 | + |
| 46 | + def check_player_is_winner(self, player): |
| 47 | + if player == self.black: |
| 48 | + for y in range(self.height): |
| 49 | + if self.walk_board(player, 0, y): |
| 50 | + return True |
| 51 | + if player == self.white: |
| 52 | + for x in range(self.width): |
| 53 | + if self.walk_board(player, x, 0): |
| 54 | + return True |
| 55 | + |
| 56 | + def get_winner(self): |
| 57 | + if self.check_player_is_winner(self.black): |
| 58 | + return self.black |
| 59 | + if self.check_player_is_winner(self.white): |
| 60 | + return self.white |
| 61 | + return self.none |
0 commit comments