class TestIO(unittest.TestCase): def setUp(self): self.cli = CLI() def test_input_difficulty(self): # map each valid input to its expected output valid_data = {} for level in ['Easy', 'Medium', 'Hard']: value = level[0] valid_data[level] = value valid_data[level.upper()] = value valid_data[level.lower()] = value valid_data[level[0]] = value valid_data[level[0].lower()] = value for input_str, return_val in valid_data.items(): with unittest.mock.patch('builtins.input', return_value=input_str): self.assertEqual(self.cli.input_difficulty(), return_val) invalid_data = iter( ['', 'a', ' ', '\n', 0, 'xyz', '5', '$', '__', 'v']) with unittest.mock.patch('builtins.input', return_value=next(invalid_data)): self.assertRaises(SystemExit, self.cli.input_difficulty) def test_input_move(self): valid_data = ['0', '1', '2', '3', '4', '5', '6'] for input_str in valid_data: with unittest.mock.patch('builtins.input', return_value=input_str): self.assertEqual(self.cli.input_move(), int(input_str)) invalid_data = iter( ['', 'a', ' ', '\n', 'three', 'z', '$', '_', '+', 'wetw4t4']) with unittest.mock.patch('builtins.input', return_value=next(invalid_data)): self.assertRaises(SystemExit, self.cli.input_move) def test_output_board(self): empty_board = [[' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ']] self.cli.output_board(empty_board) full_board = [['O', 'O', 'O', 'X', 'O', 'O', 'X'], ['X', 'X', 'X', 'O', 'X', 'X', 'O'], ['O', 'X', 'O', 'O', 'X', 'X', 'X'], ['O', 'O', 'X', 'O', 'X', 'O', 'O'], ['O', 'X', 'O', 'X', 'O', 'X', 'X'], ['X', 'O', 'X', 'X', 'O', 'X', 'O']] self.cli.output_board(full_board) def test_messages(self): self.cli.human_is('player 1') self.cli.human_is('player 2') self.cli.computers_move() self.cli.end_winner('Player 1') self.cli.end_winner('Player 2') self.cli.end_tie() self.cli.thanks()
def main(): cli = CLI() board = Board() cli.begin() difficulty = cli.input_difficulty() if difficulty == 'E': computer_move = MoveDecisionEasy elif difficulty == 'M': computer_move = MoveDecisionMedium elif difficulty == 'H': computer_move = MoveDecisionHard else: print("Unexpected error, exiting") sys.exit() human_is_next = False human_is_player_1 = False if board.human_goes_first(): cli.human_is('player 1') human_is_next = True human_is_player_1 = True else: cli.human_is('player 2') while True: cli.output_board(board.get_board()) end = board.end_of_game() if end[0]: if end[1] == 'Tie': cli.end_tie() break elif end[1] == 'X': cli.end_winner('Player 1') break elif end[1] == 'O': cli.end_winner('Player 2') break if human_is_next: board.move(cli.input_move(), human_is_player_1) human_is_next = False else: cli.computers_move() board.move(computer_move(board.get_board()).move(), (not human_is_player_1)) human_is_next = True cli.thanks()