class GameController: def __init__(self): self.game = Game() self.view = GameView() def run(self): print(self.view.intro()) while (True): players = input(self.view.number_of_players()) if players == "1": self.play(HumanController(player=1), ComputerController(player=2)) elif players == "2": self.play(HumanController(player=1), HumanController(player=2)) else: print(self.view.number_of_players_error()) continue break self.play_again() def play_again(self): resp = input(self.view.play_again) if resp.lower() != 'n': self.game = Game() print(self.view.newlines()) self.run() def play(self, player1, player2): self.display_board() for i in range(9): if i % 2 == 0: player1.move(self.game) else: player2.move(self.game) self.display_board() if self.game.is_won(): return self.game_results(player1, player2) def game_results(self, player1, player2): if self.game.winner: if player1.marker == self.game.winner: print(self.view.win_player(player=1)) elif player2.marker == self.game.winner: print(self.view.win_player(player=2)) else: print(self.view.draw()) def display_board(self): print(self.view.board(self.game.board))
class TestGameView(unittest.TestCase): def setUp(self): self.view = GameView() def test_board(self): board = [1, 'O', 'O', 'X', 5, 'X', 7, 8, 9] self.assertEqual( self.view.board(board), ''' ╔═══╦═══╦═══╗ ║ 1 ║ O ║ O ║ ╠═══╬═══╬═══╣ ║ X ║ 5 ║ X ║ ╠═══╬═══╬═══╣ ║ 7 ║ 8 ║ 9 ║ ╚═══╩═══╩═══╝ ''') def test_new_lines(self): self.assertEqual(self.view.newlines(), '\n') self.assertEqual(self.view.newlines(3), '\n\n\n') def test_win_player(self): self.assertEqual(self.view.win_player(1), 'Player 1 won!') self.assertEqual(self.view.win_player(2), 'Player 2 won!') def test_next_move(self): self.assertEqual(self.view.next_move(1, 1), 'Player 1: 1') self.assertEqual(self.view.next_move(1, 5), 'Player 1: 5') self.assertEqual(self.view.next_move(2, 6), 'Player 2: 6')