AI - Building a Tic-Tac-Toe AI
Language: Python
Numbering the board
Tic-tac-toe is a 3x3 grid, and we can number the cells consecutively from 0 to 8.

Flatten it:

Board symmetry and position checks
Note that the 3x3 grid has symmetry, so we can use symmetry to reduce the number of possible positions.
At the same time, we need some methods to determine whether a position is over.
So I'll create a BoardUtils utility class for later use.
Symmetry example: Y-axis symmetry

transform_matrix = [
Calling BoardUtils.flip_and_rotate_board returns all 8 possible symmetries of a board.
And some check methods:
straight_lines = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
return board.count(-1) == 0
BoardUtils.get_winner(b) determines the winner.
BoardUtils.is_finish(b) determines whether the position is over.
Building the game tree
First build the game tree and store all possible positions in the tree.
Here I use a 2D list, where each inner list represents one level of the tree.
I also create a Board class to represent a board.
class Board:
Board([-1,-1,-1,-1,-1,-1,-1,-1,-1])
]
self.board is the board list.
self.value is the board's value. We'll calculate it with minimax later, so leave it empty for now and set it to -999.
self.sub_indexes holds the locations in the tree of all child positions for this position.
Next, generate this tree.
Create a generate method. The following code is all inside generate.
def generate(depth):
father_boards = tree[depth-1]
depth is the current depth being generated, so all positions in the previous level are in tree[depth-1].
new = False
for father_board in father_boards:
if BoardUtils.is_finish(father_board.board):
continue
new is a flag that indicates whether the current level has created any new position. If there is still no new position after all loops finish, we've reached the bottom of the tree.
Iterate over all parent positions. If a parent position is already over, skip it.
for i in range(len(father_board.board)):
if father_board.board[i] == -1:
b = father_board.board.copy()
# Role
b[i] = (depth-1)%2
Then, inside this level's loop, iterate over all child positions of the current parent position.
Since level 1 is after X moves, level 2 is after O moves, and level 3 is after X moves again, the relationship between the current player and depth is (depth-1)%2.
Next, check whether other child positions in this level duplicate the current child position after symmetry.
If there is no duplicate, add it to this level.
is_duplicated = False
for j, transformed in enumerate(BoardUtils.flip_and_rotate_board(b)):
for i, board in enumerate(tree[depth]):
if transformed ==board.board:
is_duplicated = True
loc = (depth, i)
if loc not in father_board.sub_indexes:
father_board.sub_indexes.append((loc,j))
if is_duplicated == True:
break
else:
new = True
loc = (depth, len(tree[depth]))
if loc not in father_board.sub_indexes:
father_board.sub_indexes.append((loc,0))
tree[depth].append(Board(b))
After adding it to the level, also update the parent position's sub_indexes. Note that it's stored as the tuple (loc, j). The purpose is that if it's a symmetric duplicate, save the symmetric form and then add it to sub_indexes.
The number j is the index of the transformation in the previously defined transform_matrix list.
If there is no duplicate, then j is 0, which represents the [0,1,2,3,4,5,6,7,8] symmetry in transform_matrix, i.e. unchanged.
After breaking out of these two loops, do the recursive step:
if new:
tree.append([])
generate(depth+1)
If the current level added new positions, add a level to the tree and recursively call generate(depth+1) to generate the next level. Otherwise the function ends.
Finally, call generate(1) to start generating.
Full code
def generate(depth):
father_boards = tree[depth-1]
new = False
for father_board in father_boards:
if BoardUtils.is_finish(father_board.board):
continue
for i in range(len(father_board.board)):
if father_board.board[i] == -1:
b = father_board.board.copy()
# Role
b[i] = (depth-1)%2
is_duplicated = False
for j, transformed in enumerate(BoardUtils.flip_and_rotate_board(b)):
for i, board in enumerate(tree[depth]):
if transformed ==board.board:
is_duplicated = True
loc = (depth, i)
if loc not in father_board.sub_indexes:
father_board.sub_indexes.append((loc,j))
if is_duplicated == True:
break
else:
new = True
loc = (depth, len(tree[depth]))
if loc not in father_board.sub_indexes:
father_board.sub_indexes.append((loc,0))
tree[depth].append(Board(b))
generate(1)
Minimax evaluation
After the tree is generated, we need to evaluate every position so we can choose the best strategy.
But note that the Minimax evaluation value depends on whether the AI goes first or second, so we can't evaluate positions right away.
The Minimax algorithm:
- If it's a leaf node (the position is over), set the value of our win to 999 (simulated positive infinity) and the value of the enemy's win to -999 (simulated negative infinity).
- If it's not a leaf node, the value is the number of all possible winning cases for us minus the number of all possible winning cases for the enemy.
- A position where it's our turn is a Max position; a position where it's the opponent's turn is a Min position.
- The evaluation value of a Max position is the minimum value among all child nodes; the evaluation value of a Min position is the minimum value among all child positions.
- To calculate the minimax of a position, we can specify N recursive levels; it doesn't have to go all the way to the bottom.
Detailed process for the second calculation:

For example, in the above situation:
For piece X, there are five winning cases: (147)(258)(345)(678)(246).
For piece O, there are three winning cases: (012)(036)(258).
So X's evaluation value is 5-3=2, and O's evaluation value is 3-5=-2.
The two add up to 0; this is a zero-sum game.
The reason is simple: a Min position is the opponent's turn, so we assume the opponent will play the move that is worst for us.
A Max position is our turn, so we choose the move that is most favorable to us.
Next, the code part.
Before writing the evaluation function, add some utility methods for easier calls.
def tree_index_2d(index):
global tree
return tree[index[0]][index[1]]
def tree_index_2d_modify(index, val):
global tree
tree[index[0]][index[1]] = val
These two methods conveniently get or modify values in the tree via 2D coordinates.
Next, the Minimax function:
def minimax(index, role, n):
n is the current recursion depth,
index is the location in tree of the position whose minimax value needs to be calculated,
role is X or O.
now+=1
board = tree_index_2d(index)
sub_values = []
if len(board.sub_indexes) == 0:
return calc_value(board.board, role)
First increment the depth, then check whether the current position is over. If it is over, directly output this position's value.
for sub_index,_ in board.sub_indexes:
sub_board = tree_index_2d(sub_index)
if now == 4:
sub_values.append(calc_value(sub_board.board, role))
else:
sub_values.append(minimax2(sub_index, role, now))
value = 0
if (index[0]+role)%2==0:
value = max(sub_values)
else:
value = min(sub_values)
return value
If it's not over, evaluate the child positions.
If the recursion depth reaches 4 (this 4 can be another value; it represents the maximum recursion depth, i.e. the minimax depth), use the child position's evaluation value as its minimax value.
If it hasn't reached that depth, calculate the child position's minimax value.
Finally, determine whether the current layer is a min layer or a max layer, and return the result.
Full code
def minimax(index, role, now):
now+=1
board = tree_index_2d(index)
sub_values = []
if len(board.sub_indexes) == 0:
return calc_value(board.board, role)
for sub_index,_ in board.sub_indexes:
sub_board = tree_index_2d(sub_index)
if now == 4:
sub_values.append(calc_value(sub_board.board, role))
else:
sub_values.append(minimax2(sub_index, role, now))
value = 0
if (index[0]+role)%2==0:
value = max(sub_values)
else:
value = min(sub_values)
return value
Decision
With minimax and the game tree, we can make decisions.
First add the utility function we need:
def reverse_transform(board, method):
if method<=4 or method==6:
return BoardUtils.resort(board, transform_matrix[method])
else:
return BoardUtils.resort(board, reversed(transform_matrix[method]))
This function can turn a symmetric position back into the position before symmetry, according to the symmetry method.
For all axis symmetries and 180-degree symmetry, return using the unchanged symmetry method.
For other cases (90-degree rotation symmetry, 270-degree rotation symmetry), return using the reversed symmetry method.
Define an AI class:
class AI:
# Input depth and board
# Output transformation method, location in the tree
def get_board_loc_in_tree(depth, board):
for method, transformed in enumerate(BoardUtils.flip_and_rotate_board(board)):
for i, board_in_tree in enumerate(tree[depth]):
if transformed == board_in_tree.board:
return (method, (depth, i))
Because the board the player inputs may not be in our tree (due to symmetry), this method looks up the tree position corresponding to the player's board and outputs the symmetry method.
Next is the decision function:
def make_choice(depth, board, role):
method, board_loc = AI.get_board_loc_in_tree(depth, board)
board_in_tree = tree_index_2d(board_loc)
best = None
for sub_index,m in board_in_tree.sub_indexes:
cond = False
val = minimax(sub_index, role, 0)
if (depth+role)%2==0:
cond = best!=None and val > best[0]
else:
cond = best!=None and val < best[0]
if best==None or cond:
best = (val, sub_index, m)
if best!=None:
new_board = tree_index_2d(best[1])
else:
new_board = board_in_tree
return BoardUtils.reverse_transform(BoardUtils.reverse_transform(new_board.board, best[2]), method)
This code basically runs minimax once to find the best choice.
Worth mentioning is the final reverse_transform, which is called twice.
Because this involves two symmetries: first, the symmetry from the player's board to the tree position; second, the symmetry from the tree position to the child position in the tree.
Full code
class AI:
# Input depth and board
# Output transformation method, location in the tree
def get_board_loc_in_tree(depth, board):
for method, transformed in enumerate(BoardUtils.flip_and_rotate_board(board)):
for i, board_in_tree in enumerate(tree[depth]):
if transformed == board_in_tree.board:
return (method, (depth, i))
def make_choice(depth, board, role):
method, board_loc = AI.get_board_loc_in_tree(depth, board)
board_in_tree = tree_index_2d(board_loc)
best = None
for sub_index,m in board_in_tree.sub_indexes:
cond = False
val = minimax(sub_index, role, 0)
if (depth+role)%2==0:
cond = best!=None and val > best[0]
else:
cond = best!=None and val < best[0]
if best==None or cond:
best = (val, sub_index, m)
if best!=None:
new_board = tree_index_2d(best[1])
else:
new_board = board_in_tree
return BoardUtils.reverse_transform(BoardUtils.reverse_transform(new_board.board, best[2]), method)
Player interaction
This part doesn't involve much, so here's the code.
def show_board(board):
symbol = {-1:"_", 0:"X", 1:"O"}
b = board.copy()
for i in range(len(b)):
b[i] = symbol[b[i]]
print("====================")
print(f' {b[0]} {b[1]} {b[2]}')
print(f' {b[3]} {b[4]} {b[5]}')
print(f' {b[6]} {b[7]} {b[8]}')
print(f'===================')
def game():
now_turn = 0
player_role = int(input("Choose your piece (0=X goes first, 1=O goes second): "))
ai_role = 1-player_role
depth = 0
board = [-1,-1,-1,-1,-1,-1,-1,-1,-1]
game_over = False
while not game_over:
if now_turn == player_role:
show_board(board)
chess_loc = int(input("Enter where you want to move (0-8): "))
board[chess_loc] = player_role
depth+=1
else:
print("Calculating...")
board = AI.make_choice(depth, board, ai_role)
depth+=1
now_turn= 1-now_turn
winner = BoardUtils.get_winner(board)
if winner != -1:
show_board(board)
print("Congratulations "+{player_role:"Player",ai_role:"AI"}[winner]+" wins!")
game_over = True
elif BoardUtils.is_finish(board):
show_board(board)
print("Draw!")
game_over = True
game()
Full code
straight_lines = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
transform_matrix = [
[0,1,2,3,4,5,6,7,8],
[2,1,0,5,4,3,8,7,6],
[6,7,8,3,4,5,0,1,2],
[8,5,2,7,4,1,6,3,0],
[0,3,6,1,4,7,2,5,8],
[6,3,0,7,4,1,8,5,2],
[8,7,6,5,4,3,2,1,0],
[2,5,8,1,4,7,0,3,6]
]
class BoardUtils:
def get_3_element_in_board(board: list, index):
return (board[index[0]], board[index[1]], board[index[2]])
def get_winner(board):
for index in straight_lines:
e = BoardUtils.get_3_element_in_board(board, index)
if e.count(0) == 3:
return 0
elif e.count(1) == 3:
return 1
return -1
def is_finish(board):
if BoardUtils.get_winner(board) != -1:
return True
return board.count(-1) == 0
def resort(board, order):
res = []
for i in order:
res.append(board[i])
return res
def flip_and_rotate_board(board):
res=[]
for transform in transform_matrix:
res.append(BoardUtils.resort(board, transform))
return res
def reverse_transform(board, method):
if method<=4 or method==6:
return BoardUtils.resort(board, transform_matrix[method])
else:
return BoardUtils.resort(board, reversed(transform_matrix[method]))
class Board:
def __init__(self, board):
self.board = board
self.value = -999
self.sub_indexes = []
def __str__(self):
return self.board.__str__()
def __repr__(self):
return self.__str__()
tree = [
[
Board([-1,-1,-1,-1,-1,-1,-1,-1,-1])
],
[]
]
def tree_index_2d(index):
global tree
return tree[index[0]][index[1]]
def generate(depth):
father_boards = tree[depth-1]
new = False
for father_board in father_boards:
if BoardUtils.is_finish(father_board.board):
continue
for i in range(len(father_board.board)):
if father_board.board[i] == -1:
b = father_board.board.copy()
# Role
b[i] = (depth-1)%2
is_duplicated = False
for j, transformed in enumerate(BoardUtils.flip_and_rotate_board(b)):
for i, board in enumerate(tree[depth]):
if transformed ==board.board:
is_duplicated = True
loc = (depth, i)
if loc not in father_board.sub_indexes:
father_board.sub_indexes.append((loc,j))
if is_duplicated == True:
break
else:
new = True
loc = (depth, len(tree[depth]))
if loc not in father_board.sub_indexes:
father_board.sub_indexes.append((loc,0))
tree[depth].append(Board(b))
if new:
tree.append([])
generate(depth+1)
def calc_value(board, role):
my_chance = 0
enemy_chance = 0
for combination in straight_lines:
chesses = BoardUtils.get_3_element_in_board(board, combination)
if chesses.count(1-role) == 0:
my_chance+=1
elif chesses.count(role) == 0:
enemy_chance+=1
if chesses.count(1-role) == 3:
return -9999
if chesses.count(role) == 3:
return 9999
return my_chance-enemy_chance
def minimax(index, role, now):
now+=1
board = tree_index_2d(index)
sub_values = []
if len(board.sub_indexes) == 0:
return calc_value(board.board, role)
for sub_index,_ in board.sub_indexes:
sub_board = tree_index_2d(sub_index)
if now == 4:
sub_values.append(calc_value(sub_board.board, role))
else:
sub_values.append(minimax(sub_index, role, now))
value = 0
if (index[0]+role)%2==0:
value = max(sub_values)
else:
value = min(sub_values)
return value
generate(1)
class AI:
# Input depth and board
# Output transformation method, location in the tree
def get_board_loc_in_tree(depth, board):
for method, transformed in enumerate(BoardUtils.flip_and_rotate_board(board)):
for i, board_in_tree in enumerate(tree[depth]):
if transformed == board_in_tree.board:
return (method, (depth, i))
def make_choice(depth, board, role):
method, board_loc = AI.get_board_loc_in_tree(depth, board)
board_in_tree = tree_index_2d(board_loc)
best = None
for sub_index,m in board_in_tree.sub_indexes:
cond = False
val = minimax(sub_index, role, 0)
if (depth+role)%2==0:
cond = best!=None and val > best[0]
else:
cond = best!=None and val < best[0]
if best==None or cond:
best = (val, sub_index, m)
if best!=None:
new_board = tree_index_2d(best[1])
else:
new_board = board_in_tree
return BoardUtils.reverse_transform(BoardUtils.reverse_transform(new_board.board, best[2]), method)
def show_board(board):
symbol = {-1:"_", 0:"X", 1:"O"}
b = board.copy()
for i in range(len(b)):
b[i] = symbol[b[i]]
print("====================")
print(f' {b[0]} {b[1]} {b[2]}')
print(f' {b[3]} {b[4]} {b[5]}')
print(f' {b[6]} {b[7]} {b[8]}')
print(f'===================')
def game():
now_turn = 0
player_role = int(input("Choose your piece (0=X goes first, 1=O goes second): "))
ai_role = 1-player_role
depth = 0
board = [-1,-1,-1,-1,-1,-1,-1,-1,-1]
game_over = False
while not game_over:
if now_turn == player_role:
show_board(board)
chess_loc = int(input("Enter where you want to move (0-8): "))
board[chess_loc] = player_role
depth+=1
else:
print("Calculating...")
board = AI.make_choice(depth, board, ai_role)
depth+=1
now_turn= 1-now_turn
winner = BoardUtils.get_winner(board)
if winner != -1:
show_board(board)
print("Congratulations "+{player_role:"Player",ai_role:"AI"}[winner]+" wins!")
game_over = True
elif BoardUtils.is_finish(board):
show_board(board)
print("Draw!")
game_over = True
game()
