Game Theory Lab Experiment 10
Game Theory Lab Experiment 10
def print_board():
# Print the board in a 3x3 format
for row in [board[i*3:(i+1)*3] for i in range(3)]:
print('|'.join(row))
print('-' * 5)
def is_draw(board):
# Check if the board is full (draw)
return ' ' not in board
if is_maximizing:
best_score = -float('inf')
for i in range(9):
if board[i] == ' ':
board[i] = 'X'
score = minimax(board, depth + 1, False)
board[i] = ' '
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
score = minimax(board, depth + 1, True)
board[i] = ' '
best_score = min(score, best_score)
return best_score
def best_move():
# Find the best move for the computer (X)
best_score = -float('inf')
move = -1
for i in range(9):
if board[i] == ' ':
board[i] = 'X'
score = minimax(board, 0, False)
board[i] = ' '
if score > best_score:
best_score = score
move = i
return move
def player_move():
# Get the player's move
move = int(input("Enter your move (1-9): ")) - 1
if board[move] == ' ':
board[move] = 'O'
else:
print("Invalid move!")
player_move()
# Game loop
while True:
print_board()
# Player's move
player_move()
if is_winner(board, 'O'):
print("You win!")
break
if is_draw(board):
print("It's a draw!")
break
# Computer's move
board[best_move()] = 'X'
if is_winner(board, 'X'):
print_board()
print("Computer wins!")
break
if is_draw(board):
print_board()
print("It's a draw!")
break
Output -