xonecas.io
373
Ti

tictactoe / commit 8cb74c4

naive implementation of minimax (alpha beta trees)

xonecas2020-08-12 8cb74c4f1cb02525f8cd137047108802004efaed parent a17b37a

1 file changed

tic_tac_tow.py+87−69
@@ -5,10 +5,6 @@ import random
55
66 class TicTacToe():
77
8- class NoPlayableRoom(Exception):
9- """Error for when the AI has no valid moves"""
10- pass
11-
128 class InvalidPlay(Exception):
139 """Error for when the Player chooses an invalid move"""
1410 pass
@@ -20,7 +16,8 @@ class TicTacToe():
2016 def __init__(self):
2117 self.board = [[0] * 3 for i in [0] * 3]
2218 # Simple heads or tails, over 5.0 goes the player
23- self.who_next = self.PLAYER if random.random() >= 0.5 else self.AI
19+ self.current_player = (
20+ self.PLAYER if random.random() >= 0.5 else self.AI)
2421 self.total_moves = 0
2522
2623 def printBoard(self):
@@ -36,73 +33,69 @@ class TicTacToe():
3633
3734 def checkForRoom(self):
3835 foundRoom = False
39- coords = None
4036
4137 for i, _ in enumerate(self.board):
4238 for j, m in enumerate(self.board[i]):
4339 if m == 0:
4440 foundRoom = True
45- coords = (i, j)
4641 break
4742 if foundRoom:
4843 break
4944
50- return foundRoom, coords
51-
52- def AIPlay(self):
53- isThereRoom = self.checkForRoom()
54-
55- if isThereRoom[0]:
56- print('AI is making their move...')
57- i = isThereRoom[1][0]
58- j = isThereRoom[1][1]
59- self.board[i][j] = self.AI
60- else:
61- raise self.NoPlayableRoom()
62-
63- def PlayerPlay(self):
64- isThereRoom = self.checkForRoom()
65-
66- if isThereRoom[0]:
67- player_coords_input = (
68- input('\nEnter a row and column, separeted by a comma\n\n'))
69- i, j = [int(s) - 1 for s in player_coords_input.split(',')]
70- allowed_indexes = (0, 1, 2)
71-
72- if (i in allowed_indexes and j in allowed_indexes and
73- self.board[i][j] == 0):
74- self.board[i][j] = self.PLAYER
75- else:
76- raise self.InvalidPlay()
77- else:
78- raise self.NoPlayableRoom()
79-
80- def makePlay(self):
81- self.choose_next_move()
82- if self.who_next == self.PLAYER:
83- self.PlayerPlay()
84- else:
85- self.AIPlay()
86-
87- def choose_next_move(self):
88- self.who_next = self.PLAYER if self.who_next == self.AI else self.AI
45+ return foundRoom
8946
9047 def checkForWinner(self):
9148 board = self.board
92- # game needs at least 5 moves to be a winner
93- if self.total_moves >= 5:
94- # Check horizontals, then verticals, then diag:
95- if board[0][0] == board[0][1] == board[0][2] or\
96- board[1][0] == board[1][1] == board[1][2] or\
97- board[2][0] == board[2][1] == board[2][2] or\
98- board[0][0] == board[1][0] == board[2][0] or\
99- board[0][1] == board[1][1] == board[2][1] or\
100- board[0][2] == board[1][2] == board[2][2] or\
101- board[0][0] == board[1][1] == board[2][2] or\
102- board[2][0] == board[1][1] == board[0][2]:
103-
104- return True, self.who_next
105- return False, None
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
10699
107100 def loop(self):
108101 game_running = True
@@ -110,22 +103,47 @@ class TicTacToe():
110103 while(game_running):
111104 self.printBoard()
112105
113- game_won, winner_index = self.checkForWinner()
114- winner = 'You' if self.PLAYER == winner_index else 'The AI'
115- if game_won:
116- print(
117- f"\nGame Over. {winner} won in {self.total_moves} moves\n")
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')
118119 game_running = False
119120 break
120121
122+ self.current_player = (self.PLAYER if
123+ self.current_player == self.AI else self.AI)
121124 try:
122- self.makePlay()
123- except self.NoPlayableRoom:
124- print('\nGame over')
125- game_running = False
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
126142 except self.InvalidPlay:
127143 print('\nInvalid coordenates, please choose a valid spot\n\n')
144+ self.current_player = self.AI
128145 self.loop()
146+ break
129147
130148 self.total_moves = self.total_moves + 1