xonecas.io
373
Ti

tictactoe / files

tictactoe / tic_tac_tow.py

5.4 KB
1#!/usr/bin/env python3
2
3import random
4
5
6class TicTacToe():
7
8    class InvalidPlay(Exception):
9        """Error for when the Player chooses an invalid move"""
10        pass
11
12    AI = 1
13    PLAYER = 2
14    SYMBOLS = {0: '-', 1: 'O', 2: 'X', }
15
16    def __init__(self):
17        self.board = [[0] * 3 for i in [0] * 3]
18        # Simple heads or tails, over 5.0 goes the player
19        self.current_player = (
20            self.PLAYER if random.random() >= 0.5 else self.AI)
21        self.total_moves = 0
22
23    def printBoard(self):
24        symbols_to_print = ''
25        for i, n in enumerate(self.board):
26            for j, m in enumerate(n):
27                symbols_to_print = symbols_to_print + self.SYMBOLS[m]
28                if j < 2:
29                    symbols_to_print = symbols_to_print + '|'
30                else:
31                    symbols_to_print = symbols_to_print + '\n'
32        print('\n' + symbols_to_print + '\n')
33
34    def checkForRoom(self):
35        foundRoom = False
36
37        for i, _ in enumerate(self.board):
38            for j, m in enumerate(self.board[i]):
39                if m == 0:
40                    foundRoom = True
41                    break
42            if foundRoom:
43                break
44
45        return foundRoom
46
47    def checkForWinner(self):
48        board = self.board
49        # Check horizontals, then verticals, then diag:
50        if (
51            board[0][0] != 0 and board[0][0] == board[0][1] == board[0][2] or
52            board[1][0] != 0 and board[1][0] == board[1][1] == board[1][2] or
53            board[2][0] != 0 and board[2][0] == board[2][1] == board[2][2] or
54            board[0][0] != 0 and board[0][0] == board[1][0] == board[2][0] or
55            board[0][1] != 0 and board[0][1] == board[1][1] == board[2][1] or
56            board[0][2] != 0 and board[0][2] == board[1][2] == board[2][2] or
57            board[0][0] != 0 and board[0][0] == board[1][1] == board[2][2] or
58            board[2][0] != 0 and board[2][0] == board[1][1] == board[0][2]
59        ):
60            return True
61        return False
62
63    def minimax_calculation(self, depth=2):
64        x = -1
65        y = -1
66        # -1 for loss, 0 ties, 1 wins
67        score = -2
68        best_score = -1  # Start loosing
69
70        if self.checkForRoom():
71            for i, _ in enumerate(self.board):
72                for j, m in enumerate(self.board[i]):
73                    if m == 0:
74                        self.board[i][j] = self.current_player
75
76                        if self.current_player == self.AI:
77                            # Maximing value
78                            self.current_player = self.PLAYER
79                            score, x, y = self.minimax_calculation(depth - 1)
80                            if best_score < score:
81                                best_score = score
82                                x = i
83                                y = j
84                        else:
85                            # Minimizing value
86                            self.current_player = self.AI
87                            score, x, y = self.minimax_calculation(depth - 1)
88                            if best_score > score:
89                                best_score = score
90                                x = i
91                                y = j
92                        self.board[i][j] = m
93            if self.checkForWinner():
94                return (1 if self.current_player == self.AI else -1), x, y
95        else:
96            return 0, x, y
97
98        return best_score, x, y
99
100    def loop(self):
101        game_running = True
102
103        while(game_running):
104            self.printBoard()
105
106            # game needs at least 5 moves to be a winner
107            if self.total_moves >= 5:
108                game_won = self.checkForWinner()
109                if game_won:
110                    winner = ('You' if self.PLAYER == self.current_player
111                              else 'The AI')
112                    print('\nGameOver')
113                    print(f"{winner} won in {self.total_moves} moves\n")
114                    game_running = False
115                    break
116
117            if not self.checkForRoom():
118                print('\nGameOver, You tied')
119                game_running = False
120                break
121
122            self.current_player = (self.PLAYER if
123                                   self.current_player == self.AI else self.AI)
124            try:
125                if self.current_player == self.PLAYER:
126                    player_coords_input = input(
127                        '\nEnter a row and column, separeted by a comma\n\n')
128                    i, j = [int(s) - 1 for s in player_coords_input.split(',')]
129                    allowed_indexes = (0, 1, 2)
130
131                    if (i in allowed_indexes and j in allowed_indexes and
132                            self.board[i][j] == 0):
133                        self.board[i][j] = self.PLAYER
134                    else:
135                        raise self.InvalidPlay()
136                else:
137                    print('AI is making their move...')
138                    _, i, j = self.minimax_calculation()
139                    print(f'Done: {i}, {j}')
140                    self.current_player = self.AI
141                    self.board[i][j] = self.AI
142            except self.InvalidPlay:
143                print('\nInvalid coordenates, please choose a valid spot\n\n')
144                self.current_player = self.AI
145                self.loop()
146                break
147
148            self.total_moves = self.total_moves + 1
149
150
151if __name__ == '__main__':
152    game = TicTacToe()
153    game.loop()