Adi 2

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Assignment No.

2
Name: Omkar Bhausaheb Mane
Roll no.: A-67
Subject: Artificial Intelligence

Code:
from collections import deque
import random

EMPTY = '-'
X = 'X'
O = 'O'
WIN_COMBINATIONS = [
[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)]
]

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

def check_winner(board):
for combination in WIN_COMBINATIONS:
symbols = [board[row][col] for row, col in combination]
if symbols == [X, X, X]:
return X
elif symbols == [O, O, O]:
return O
return None

def get_possible_moves(board):
moves = []
for row in range(3):
for col in range(3):
if board[row][col] == EMPTY:
moves.append((row, col))
return moves

def bfs_tic_tac_toe():
start_state = [['-' for _ in range(3)] for _ in range(3)]
queue = deque([(start_state, X)])

while queue:
current_state, current_player = queue.popleft()
print_board(current_state)

if current_player == X:
winner = check_winner(current_state)
if winner:
print(f"Player {winner} wins!")
break
elif all(all(cell != EMPTY for cell in row) for row in current_state):
print("It's a draw!")
break
else:
possible_moves = get_possible_moves(current_state)
print("Available moves:", possible_moves)
row, col = map(int, input("Enter your move (row col): ").split())
if (row, col) in possible_moves:
current_state[row][col] = X
queue.append((current_state, O))
else:
print("Invalid move! Try again.")
queue.append((current_state, X))
else:
winner = check_winner(current_state)
if winner:
print(f"Player {winner} wins!")
break
elif all(all(cell != EMPTY for cell in row) for row in current_state):
print("It's a draw!")
break
else:
possible_moves = get_possible_moves(current_state)
row, col = random.choice(possible_moves)
print(f"Computer plays at ({row}, {col})")
current_state[row][col] = O
queue.append((current_state, X))

bfs_tic_tac_toe()

Output:
---
---
---

Available moves: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Enter your move (row col): 1 1
---
-X-
---

Computer plays at (0, 2)


--O
-X-
---

Available moves: [(0, 0), (0, 1), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]
Enter your move (row col): 2 0
--O
-X-
X--

Computer plays at (0, 0)


O-O
-X-
X--

Available moves: [(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]
Enter your move (row col): 0 1
OXO
-X-
X--

Computer plays at (1, 2)


OXO
-XO
X--

Available moves: [(1, 0), (2, 1), (2, 2)]


Enter your move (row col): 2 1
OXO
-XO
XX-

Player X wins!

You might also like