|
| 1 | +import math |
| 2 | +import random |
| 3 | + |
| 4 | + |
| 5 | +class Player(): |
| 6 | + def __init__(self, player): |
| 7 | + self.player = player |
| 8 | + |
| 9 | + def get_move(self, game): |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +class Human(Player): |
| 14 | + def __init__(self, player): |
| 15 | + super().__init__(player) |
| 16 | + |
| 17 | + def get_move(self, game): |
| 18 | + valid_square = False |
| 19 | + val = None |
| 20 | + while not valid_square: |
| 21 | + square = input(self.player + ' turn. Please introduce a move (1-9): ') |
| 22 | + try: |
| 23 | + val = int(square) - 1 |
| 24 | + if val not in game.remaining_moves(): |
| 25 | + raise ValueError |
| 26 | + valid_square = True |
| 27 | + except ValueError: |
| 28 | + print('Invalid square. Try again.') |
| 29 | + return val |
| 30 | + |
| 31 | + |
| 32 | +class RandomComputer(Player): |
| 33 | + def __init__(self, player): |
| 34 | + super().__init__(player) |
| 35 | + |
| 36 | + def get_move(self, game): |
| 37 | + square = random.choice(game.remaining_moves()) |
| 38 | + return square |
| 39 | + |
| 40 | + |
| 41 | +class SmartComputer(Player): |
| 42 | + def __init__(self, player): |
| 43 | + super().__init__(player) |
| 44 | + |
| 45 | + def get_move(self, game): |
| 46 | + if len(game.remaining_moves()) == 9: |
| 47 | + square = random.choice(game.remaining_moves()) |
| 48 | + else: |
| 49 | + square = self.minimax(game, self.player)['position'] |
| 50 | + return square |
| 51 | + |
| 52 | + def minimax(self, state, player): |
| 53 | + max_player = self.player |
| 54 | + min_player = '0' if player == 'X' else 'X' |
| 55 | + |
| 56 | + # checking if the previous move is winner |
| 57 | + if state.actual_winner == min_player: |
| 58 | + return {'position': None, |
| 59 | + 'score': 1 * (state.number_null_squares() + 1) if min_player == max_player |
| 60 | + else -1 * (state.number_null_squares() + 1)} |
| 61 | + elif not state.null_squares(): |
| 62 | + return {'position': None, 'score': 0} |
| 63 | + |
| 64 | + if player == max_player: |
| 65 | + best = {'position': None, 'score': -math.inf} |
| 66 | + else: |
| 67 | + best = {'position': None, 'score': math.inf} |
| 68 | + |
| 69 | + for possible_move in state.remaining_moves(): |
| 70 | + state.make_a_move(possible_move, player) |
| 71 | + sim_score = self.minimax(state, min_player) |
| 72 | + |
| 73 | + # undo move |
| 74 | + state.board[possible_move] = ' ' |
| 75 | + state.actual_winner = None |
| 76 | + sim_score['position'] = possible_move |
| 77 | + |
| 78 | + if player == max_player: |
| 79 | + if sim_score['score'] > best['score']: |
| 80 | + best = sim_score |
| 81 | + else: |
| 82 | + if sim_score['score'] < best['score']: |
| 83 | + best = sim_score |
| 84 | + return best |
0 commit comments