An Unbeatable TicTacToe AI in Python using minimax algorithm
This is a command-line TicTacToe game written in Python where the player faces an unbeatable AI.
This packet that I have submitted contains the source code for a TicTacToe game with an unbeatable AI.
The AI is implemented with the concept of minimax tree where the AI either wins or draws the match.
def MiniMaxAB(board, depth, alpha, beta, player):
row = -1
col = -1
if depth == 0 or gameWon(board):
return [row, col, getScore(board)]
else:
for cell in emptyCells(board):
setMove(board, cell[0], cell[1], player)
score = MiniMaxAB(board, depth - 1, alpha, beta, -player)
if player == X:
if score[2] > alpha:
alpha = score[2]
row = cell[0]
col = cell[1]
else:
if score[2] < beta:
beta = score[2]
row = cell[0]
col = cell[1]
setMove(board, cell[0], cell[1], EMPTY)
if alpha >= beta:
break
if player == X:
return [row, col, alpha]
else:
return [row, col, beta]
By using this snippet of code the AI decides where to place its move so that it would beneficial for it.
The entire code has been given in the project file along with some output screenshots
Project Files
| .. | ||
| This directory is empty. | ||