0% found this document useful (0 votes)
10 views3 pages

Al 3

The document contains a Python implementation of a Tic Tac Toe game using the A* algorithm for AI moves. It defines a class that manages the game board, player moves, and checks for wins or draws. The AI uses a heuristic to determine the best move based on the current state of the game board.

Uploaded by

motenancy7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Al 3

The document contains a Python implementation of a Tic Tac Toe game using the A* algorithm for AI moves. It defines a class that manages the game board, player moves, and checks for wins or draws. The AI uses a heuristic to determine the best move based on the current state of the game board.

Uploaded by

motenancy7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 3

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 :-

You might also like