question archive Take a look at this tic tac toe code right here and described the algorithm for it
Subject:Computer SciencePrice: Bought3
Take a look at this tic tac toe code right here and described the algorithm for it. After that, in a separate file, tell me what type of AI algorithm that is used in it. And lastly, in a third file make the Algorithm for the AI in it.
def tic_tac_toe():
board = [' ']*9
while True:
print_board(board)
move = get_move(board)
board[move] = 'X'
if is_winner(board, 'X'):
print_board(board)
print('You win!')
break
if is_full(board):
print_board(board)
print('It's a tie!')
break
move = get_computer_move(board)
board[move] = 'O'
if is_winner(board, 'O'):
print_board(board)
print('You lose!')
break
def is_winner(board, player):
return ((board[0] == player and board[1] == player and board[2] == player) or
(board[3] == player and board[4] == player and board[5] == player) or
(board[6] == player and board[7] == player and board[8] == player) or
(board[0] == player and board[3] == player and board[6] == player) or
(board[1] == player and board[4] == player and board[7] == player) or
(board[2] == player and board[5] == player and board[8] == player) or
(board[0] == player and board[4] == player and board[8] == player) or
(board[2] == player and board[4] == player and board[6] == player))
def is_full(board):
return board.count(' ') == 0
def get_move(board):
while True:
move = int(input('Enter your move (0-8): '))
if move in range(9) and board[move] == ' ':
return move
def get_computer_move(board):
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
if is_winner(board, 'O'):
return i
board[i] = ' '
for i in range(9):
if board[i] == ' ':
board[i] = 'X'
if is_winner(board, 'X'):
return i
board[i] = ' '
if board[4] == ' ':
return 4
for i in [0, 2, 6, 8]:
if board[i] == ' ':
return i
for i in [1, 3, 5, 7]:
if board[i] == ' ':
return i
def print_board(board):
print(' ' + board[0] + ' | ' + board[1] + ' | ' + board[2])
print('-----------')
print(' ' + board[3] + ' | ' + board[4] + ' | ' + board[5])
print('-----------')
print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8])
tic_tac_toe()