You are on page 1of 6

21131A4410 | LOKESH DUDDUKURI

WEEK – 06

AIM: Implement Alpha-Beta Pruning


DESCRIPTION:
o Alpha-beta pruning is a modified version of the minimax algorithm. It is an optimization technique for the
minimax algorithm.

o As we have seen in the minimax search algorithm that the number of game states it has to examine are exponential
in depth of the tree. Since we cannot eliminate the exponent, but we can cut it to half. Hence there is a technique
by which without checking each node of the game tree we can compute the correct minimax decision, and this
technique is called pruning. This involves two threshold parameter Alpha and beta for future expansion, so it is
called alpha-beta pruning. It is also called as Alpha-Beta Algorithm.

o Alpha-beta pruning can be applied at any depth of a tree, and sometimes it not only prune the tree leaves but also
entire sub-tree.

PROGRAM:
import math
import
random

depth = 4

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

def
check_winner(board
): # Check rows
for row in board:
if row.count(row[0]) == len(row) and row[0] != ' ':
return True

# Check columns
for col in range(len(board[0])):
if board[0][col] == board[1][col] == board[2][col]
and board[0][col] != ' ':
return True
21131A4410 | LOKESH DUDDUKURI

if board[0][2] == board[1][1] == board[2][0] and board[0][2] != '


':
return True

return False

def game_over(board):
return check_winner(board) or not any(' ' in row for row in board)

def
possible_moves(board)
: moves = []
for i in range(len(board)):
for j in
range(len(board[i])): if
board[i][j] == ' ':
moves.append((i,
j)) return moves

def make_move(board, move,


player): i, j = move
new_board = [row[:] for row in
board] new_board[i][j] = player
return new_board

def evaluate(board):
if check_winner(board):
return 1 if 'X' in board[0] else -
1 else:
return 0

def minimax_alpha_beta(board, depth, alpha, beta,


maximizing_player): if depth == 0 or game_over(board):
return evaluate(board)

if maximizing_player:
max_eval = float('-
inf')
for move in possible_moves(board):
board_copy = make_move(board, move,
'X')
eval = minimax_alpha_beta(board_copy, depth - 1,
alpha, beta, False)
max_eval = max(max_eval,
eval) alpha = max(alpha,
eval)
if beta <=
alpha: break
return
max_eval else:
min_eval = float('inf')
for move in possible_moves(board):
board_copy = make_move(board, move,
21131A4410 | LOKESH DUDDUKURI
'O')
21131A4410 | LOKESH DUDDUKURI

eval = minimax_alpha_beta(board_copy, depth - 1, alpha,


beta,
True) min_eval = min(min_eval,
eval) beta = min(beta, eval)
if beta <=
alpha: break
return min_eval

def find_best_move(board):
best_move = None
max_eval = float('-
inf') alpha = float('-
inf') beta =
float('inf')
for move in possible_moves(board):
board_copy = make_move(board, move,
'X')
eval = minimax_alpha_beta(board_copy, depth, alpha, beta,
False)
if eval > max_eval:
max_eval = eval
best_move =
move
return best_move

def computer_move(board):
move = find_best_move(board)
return make_move(board, move,
'X')

def
user_move(board):
while True:
try:
move = input("Enter your move (row, column), e.g., 1 1:
").split()
move = (int(move[0]),
int(move[1])) if move in
possible_moves(board):
return make_move(board, move,
'O') else:
print("Invalid move. Try again.")
except (ValueError, IndexError):
print("Invalid input. Please enter two integers
separated by a space.")

def play_game():
board = [[' ' for _ in range(3)] for _ in range(3)]
print("Welcome to Tic-Tac-Toe!")
print_board(board)

while not
game_over(board): #
21131A4410 | LOKESH DUDDUKURI
User's move
board = user_move(board)
21131A4410 | LOKESH DUDDUKURI

print_board(board)
if
game_over(board):
break

# Computer's move
print("Computer's move:")
board =
computer_move(board)
print_board(board)

if check_winner(board):
print("Congratulations! You
win!")
else:
print("It's a draw.")

OUTPUT:
Welcome to Tic-Tac-Toe!
| |
| |
| |

Enter your move (row, column), e.g., 1 1: 1 1


| |
|O|
| |

Computer's move:
X| |
|O|
| |

Enter your move (row, column), e.g., 1 1: 2


0 X| |
|O|
O| |

Computer's move:
X|X|
|O|
O| |

Enter your move (row, column), e.g., 1 1: 0


2 X|X|O
|O|
O| |

Congratulations! You win!

You might also like