ASSIGNMENT -3
import numpy as np
import heapq
class TicTacToeAStar:
def __init__(self):
self.board = np.full((3, 3), ' ')
self.player = 'X' # Human
self.ai = 'O' # AI
def print_board(self):
for row in self.board:
print('|'.join(row))
print('-' * 5)
def is_winner(self, player):
for row in self.board:
if np.all(row == player):
return True
for col in self.board.T:
if np.all(col == player):
return True
if np.all(np.diag(self.board) == player) or np.all(np.diag(np.fliplr(self.board)) ==
player):
return True
return False
def is_draw(self):
return np.all(self.board != ' ')
def get_valid_moves(self):
return [(r, c) for r in range(3) for c in range(3) if self.board[r, c] == ' ']
def heuristic(self, board, player):
if self.is_winner(self.ai):
return 10
elif self.is_winner(self.player):
return -10
return 0
def a_star_move(self):
moves = self.get_valid_moves()
pq = [] # Priority Queue
for move in moves:
temp_board = self.board.copy()
temp_board[move] = self.ai
h = self.heuristic(temp_board, self.ai)
heapq.heappush(pq, (-h, move)) # Maximize heuristic
if pq:
best_move = heapq.heappop(pq)[1]
self.board[best_move] = self.ai
def play(self):
while True:
self.print_board()
if self.is_winner(self.player):
print("You win!")
break
elif self.is_winner(self.ai):
print("AI wins!")
break
elif self.is_draw():
print("It's a draw!")
break
# Human move
r, c = map(int, input("Enter row and column (0-2): ").split())
if self.board[r, c] == ' ':
self.board[r, c] = self.player
else:
print("Invalid move, try again.")
continue
# AI move
self.a_star_move()
if __name__ == "__main__":
game = TicTacToeAStar()
game.play()
Output :-