-
Notifications
You must be signed in to change notification settings - Fork 5
/
tictactoe.py
198 lines (159 loc) · 4.58 KB
/
tictactoe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""
Tic Tac Toe Player
"""
from copy import deepcopy
X = "X"
O = "O"
EMPTY = None
BOARD_SIZE = 3 # board size, e.g. 3 x 3 grid
INF = 2 # utility is either -1, 0, 1
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
X_count = sum(row.count(X) for row in board)
O_count = sum(row.count(O) for row in board)
return X if X_count == O_count else O
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
result = set()
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == EMPTY:
result.add((i, j))
return result
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
if action is None:
return board
(i, j) = action
if i not in range(BOARD_SIZE):
raise ValueError(f"i must be [0, {BOARD_SIZE})")
elif j not in range(BOARD_SIZE):
raise ValueError(f"j must be [0, {BOARD_SIZE})")
elif board[i][j] != EMPTY:
raise ValueError(f"({i}, {j}) has been taken by player {board[i][j]}")
else:
new_board = deepcopy(board)
new_board[i][j] = player(board)
return new_board
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
# check horizontally
for row in board:
if row.count(X) == BOARD_SIZE:
return X
elif row.count(O) == BOARD_SIZE:
return O
# check vertically
for col in zip(*board):
if col.count(X) == BOARD_SIZE:
return X
elif col.count(O) == BOARD_SIZE:
return O
# check diagonally
center = board[BOARD_SIZE // 2][BOARD_SIZE // 2]
if center == EMPTY:
return None
# left diagonal
left_win = True
for i in range(BOARD_SIZE):
if board[i][i] != center:
left_win = False
# right diagonal
right_win = True
for i in range(BOARD_SIZE):
if board[i][-(i + 1)] != center:
right_win = False
return center if left_win or right_win else None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
# someone has won the game
if winner(board):
return True
for row in board:
for cell in row:
if cell == EMPTY:
# there is at least 1 empty cell
return False
# no empty cell
return True
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
player = winner(board)
if player == X:
return 1
elif player == O:
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
best_action = None
# assign statistically best first move
if board == initial_state():
return (0, 0)
# max player chooses move that maximizes the min values in next step
if player(board) == X:
best_value = -INF
for action in actions(board):
value = min_value(result(board, action))
# found killer move, return immediately
if value == 1:
return action
elif best_value < value:
best_value, best_action = value, action
# min player chooses move that minimizes the max values in next step
else:
best_value = INF
for action in actions(board):
value = max_value(result(board, action))
# found killer move, return immediately
if value == -1:
return action
elif best_value > value:
best_value, best_action = value, action
return best_action
def max_value(board):
"""
Returns the highest value for the current player.
"""
if terminal(board):
return utility(board)
v = -INF
for action in actions(board):
v = max(v, min_value(result(board, action)))
# found killer move, prune other actions
if v == 1:
break
return v
def min_value(board):
"""
Returns the smallest value for the current player.
"""
if terminal(board):
return utility(board)
v = INF
for action in actions(board):
v = min(v, max_value(result(board, action)))
# found killer move, prune other actions
if v == -1:
break
return v