0% found this document useful (0 votes)
12 views1 page

Tic-Tac-Toe Minimax in Python

The document contains a Python implementation of a Tic-Tac-Toe game, including functions to print the game board, check for a winner, find empty cells, and use the minimax algorithm to determine the best move. The game allows for two players, 'X' and 'O', with 'O' being the maximizing player. The play_game function initializes the game board for play.

Uploaded by

fukreedits
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views1 page

Tic-Tac-Toe Minimax in Python

The document contains a Python implementation of a Tic-Tac-Toe game, including functions to print the game board, check for a winner, find empty cells, and use the minimax algorithm to determine the best move. The game allows for two players, 'X' and 'O', with 'O' being the maximizing player. The play_game function initializes the game board for play.

Uploaded by

fukreedits
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import math

def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)

def is_winner(board, player):


for row in board:
if all(s == player for s in row): return True
for col in range(3):
if all(board[row][col] == player for row in range(3)): return True
if all(board[i][i] == player for i in range(3)): return True
if all(board[i][2 - i] == player for i in range(3)): return True
return False

def empty_cells(board):
return [(r, c) for r in range(3) for c in range(3) if board[r][c] == " "]

def minimax(board, depth, is_maximizing):


if is_winner(board, "O"): return 1
if is_winner(board, "X"): return -1
if not empty_cells(board): return 0

if is_maximizing:
best = -[Link]
for r, c in empty_cells(board):
board[r][c] = "O"
best = max(best, minimax(board, depth + 1, False))
board[r][c] = " "
return best
else:
best = [Link]
for r, c in empty_cells(board):
board[r][c] = "X"
best = min(best, minimax(board, depth + 1, True))
board[r][c] = " "
return best

def best_move(board):
best_score = -[Link]
move = None
for r, c in empty_cells(board):
board[r][c] = "O"
score = minimax(board, 0, False)
board[r][c] = " "
if score > best_score:
best_score = score
move = (r, c)
return move

def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]

You might also like