Created
March 14, 2018 20:32
-
-
Save f4rx/092d7340dddf621a7812a998dc4f34e8 to your computer and use it in GitHub Desktop.
XO
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
| #!/bin/env python3 | |
| class Players: | |
| def __init__(self): | |
| self.players = {0: "X", 1: "O"} | |
| self.player = 0 | |
| def get_player(self): | |
| return self.players[self.player] | |
| def next_player(self): | |
| self.player ^= 1 | |
| class MapXO: | |
| def __init__(self, size = 3): | |
| self.size = size | |
| self.map_xo = [] | |
| for _ in range(size): | |
| self.map_xo.append([]) | |
| for i in range(size): | |
| for _ in range(size): | |
| self.map_xo[i].append(None) | |
| def get(self, x, y): | |
| return self.map_xo[x][y] | |
| def set(self, x, y, player): | |
| if self.get(x,y): | |
| raise ValueError | |
| self.map_xo[x][y] = player | |
| def print_map(self): | |
| print("*" * 8) | |
| for i in range(self.size): | |
| print(self.map_xo[i]) | |
| print("*" * 8) | |
| print() | |
| def check_winner(self): | |
| """ | |
| [ [x,o,-], | |
| [x,o,-], | |
| [x,-,-] | |
| ] | |
| """ | |
| for i in range(self.size): | |
| if self.map_xo[i][0] == self.map_xo[i][1] == self.map_xo[i][2]: | |
| return self.map_xo[i][0] | |
| if self.map_xo[0][i] == self.map_xo[1][i] == self.map_xo[2][i]: | |
| return self.map_xo[0][i] | |
| # FIXME работает только на 3х3 | |
| if self.map_xo[0][0] == self.map_xo[1][1] == self.map_xo[2][2]: | |
| return self.map_xo[0][0] | |
| if self.map_xo[0][2] == self.map_xo[1][1] == self.map_xo[2][0]: | |
| return self.map_xo[0][2] | |
| return None | |
| class Game: | |
| def __init__(self): | |
| self.size = 3 | |
| self.players = Players() | |
| self.map_xo = MapXO(self.size) | |
| self.winner = None | |
| def play(self): | |
| while not self.winner: | |
| self.map_xo.print_map() | |
| print("Ход игрока: ", self.players.get_player()) | |
| user_xy = input("Укажите ваш ход (формат 'x y'): ") | |
| try: | |
| x = int(user_xy.split(" ")[0]) | |
| y = int(user_xy.split(" ")[1]) | |
| except: | |
| print("Неверный формат") | |
| continue | |
| if x < 0 or y < 0 or x >= self.size or y >= self.size: | |
| print("Вы вышли за границы доски") | |
| continue | |
| if self.map_xo.get(x, y): | |
| print("Нельзя походить в одну точку дважды") | |
| continue | |
| self.map_xo.set(x, y, self.players.get_player()) | |
| self._check_winner() | |
| self.players.next_player() | |
| self.map_xo.print_map() | |
| print("У нас победитель `%s`! Поздравляем!!" % self.winner) | |
| def _check_winner(self): | |
| winner = self.map_xo.check_winner() | |
| if winner: | |
| self.winner = winner | |
| game = Game() | |
| game.play() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment