Experiment-3
Develop an intelligent decision-making agent for board games
such as Chess and Tic Tac-Toe that can analyze game states and
determine optimal moves to compete effectively against human or
computer players.
import math
# Initialize the board
board = [' ' for _ in range(9)]
# Print the board
def print_board():
for row in [board[i*3:(i+1)*3] for i in range(3)]:
print('| ' + ' | '.join(row) + ' |')
# Check for a winner
def is_winner(brd, player):
win_conditions = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
[0, 4, 8], [2, 4, 6] # Diagonals
]
return any(all(brd[i] == player for i in combo) for combo in win_conditions)
# Check for a tie
def is_board_full(brd):
return ' ' not in brd
# Minimax algorithm
def minimax(brd, depth, is_maximizing):
if is_winner(brd, 'O'):
return 1
if is_winner(brd, 'X'):
return -1
if is_board_full(brd):
return 0
if is_maximizing:
best_score = -math.inf
for i in range(9):
if brd[i] == ' ':
brd[i] = 'O'
score = minimax(brd, depth + 1, False)
brd[i] = ' '
best_score = max(score, best_score)
return best_score
else:
best_score = math.inf
for i in range(9):
if brd[i] == ' ':
brd[i] = 'X'
score = minimax(brd, depth + 1, True)
brd[i] = ' '
best_score = min(score, best_score)
return best_score
# Get best move for AI
def get_best_move():
best_score = -math.inf
move = -1
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
score = minimax(board, 0, False)
board[i] = ' '
if score > best_score:
best_score = score
move = i
return move
# Main game loop
def play_game():
print("Welcome to Tic-Tac-Toe! You are X, AI is O.")
print_board()
while True:
# Human move
user_move = int(input("Enter your move (0-8): "))
if board[user_move] != ' ':
print("Invalid move. Try again.")
continue
board[user_move] = 'X'
print_board()
if is_winner(board, 'X'):
print("You win!")
break
elif is_board_full(board):
print("It's a tie!")
break
# AI move
ai_move = get_best_move()
board[ai_move] = 'O'
print("AI has made its move:")
print_board()
if is_winner(board, 'O'):
print("AI wins!")
break
elif is_board_full(board):
print("It's a tie!")
break
# Run the game
play_game()
Out put: Welcome to Tic-Tac-Toe! You are X, AI is O.
| | | |
| | | |
| | | |
Enter your move (0-8): 5
| | | |
| | |X|
| | | |
AI has made its move:
| | |O|
| | |X|
| | | |
Enter your move (0-8): 3
| | |O|
|X| |X|
| | | |
AI has made its move:
| | |O|
|X|O|X|
| | | |
Enter your move (0-8): 1
| |X|O|
|X|O|X|
| | | |
AI has made its move:
|O|X|O|
|X|O|X|
| | | |
Enter your move (0-8): 2
Invalid move. Try again.