0% found this document useful (0 votes)
33 views

Game Theory Lab Experiment 10

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Game Theory Lab Experiment 10

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment 10

Name: Rohit Negi


ID: 21106053

Aim: To solve Tic-Tac-Toe Using Game Theory Concepts


Code -
# Define the board as a 3x3 grid
board = [' ' for _ in range(9)] # A list to hold 'X', 'O', or ' '

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_winner(board, player):


# Check if the player has won (3 in a row horizontally, vertically, or
diagonally)
win_conditions = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), # Horizontal
(0, 3, 6), (1, 4, 7), (2, 5, 8), # Vertical
(0, 4, 8), (2, 4, 6) # Diagonal
]
for condition in win_conditions:
if board[condition[0]] == board[condition[1]] == board[condition[2]]
== player:
return True
return False

def is_draw(board):
# Check if the board is full (draw)
return ' ' not in board

def minimax(board, depth, is_maximizing):


# Minimax algorithm: find the best move for both players
if is_winner(board, 'X'):
return 1 # Maximizing player wins
if is_winner(board, 'O'):
return -1 # Minimizing player wins
if is_draw(board):
return 0 # Draw

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 -

You might also like