ai
ai
PRACTICAL 1
Aim:- Write a program to implement Tic-Tac-Toe game problem.
Code:-
import random
def drawBoard(board):
print(" ")
print(board[9]," | ",board[8]," | ",board[7])
print(" ")
print(".............")
print(" ")
print(board[6]," | ",board[5]," | ",board[4])
print(" ")
print(".............")
print(board[3]," | ",board[2]," | ",board[1])
print(" ")
print(".............")
def inputPlayerLetter():
letter = ""
while not(letter == 'X' or letter == '0'):
letter = input("Chose your symbol (0/X) : ").upper()
if letter == 'X':
return ["X","0"]
1
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
else:
return ["0","X"]
def whoGoesFirst():
if random.randint(0,1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
return input("Do you want to play again? (yes/no):
").lower().startswith('y')
def makeMove(board,letter,move):
board[move] = letter
def isWinner(bo,le):
return ((bo[7] == le and bo[8] == le and bo[9]== le) or
(bo[4] == le and bo[5] == le and bo[6]== le) or
(bo[1] == le and bo[2] == le and bo[3]== le) or
(bo[7] == le and bo[4] == le and bo[1]== le) or
(bo[8] == le and bo[5] == le and bo[2]== le) or
(bo[9] == le and bo[6] == le and bo[3]== le) or
(bo[7] == le and bo[5] == le and bo[3]== le) or
(bo[9] == le and bo[5] == le and bo[1]== le) )
2
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
def getBoardCopy(board):
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
def isSpaceFree(board,move):
return board[move] == ''
def getPlayerMove(board):
move = ''
while move not in '1 2 3 4 5 6 7 8 9'.split() or not
isSpaceFree(board,int(move)):
move = input("What is your next move ? (1-9) : ")
return int(move)
def chooseRandomMoveFromList(board,movesList):
possibleMoves = []
for i in movesList:
if isSpaceFree(board,i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
3
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
def getComputerMove(board,computerLetter):
if computerLetter == 'X':
playerLetter == '0'
else:
playerLetter == 'X'
for i in range(1,10):
copy = getBoardCopy(board)
if isSpaceFree(copy,i):
makeMove(copy,computerLetter,i)
if isWinner(copy,computerLetter):
return i
for i in range(1,10):
copy = getBoardCopy(board)
if isSpaceFree(copy,i):
makeMove(copy,playerLetter,i)
if isWinner(copy,playerLetter):
return i
move = chooseRandomMoveFromList(board,[1,3,7,9])
if move != None:
return move
if isSpaceFree(board,5):
return 5
return chooseRandomMoveFromList(board,[2,4,6,8])
4
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
def isBoardFull(board):
for i in range(1,10):
if isSpaceFree(board,i):
return False
return True
5
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
drawBoard(theBoard)
print('It is a tie')
break
else:
turn = 'computer'
else:
move = getComputerMove(theBoard,computerLetter)
makeMove(theBoard,computerLetter,move)
if isWinner(theBoard,computerLetter):
drawBoard(theBoard)
print("Computer wins !!! You loose....")
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is Tie')
break
else:
turn = 'player'
if not playAgain():
break
Output:-
6
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
7
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 2
Code:-
def __hash__(self):
return hash(tuple(self.board))
def __str__(self):
return f"{self.board[0:3]}\n{self.board[3:6]}\n{self.board[6:9]}"
def next(self):
next_moves = []
i = self.board.index(0) # Get the position of the empty space (0)
8
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right
for dx, dy in directions:
x, y = self.pos(i)
nx, ny = x + dx, y + dy
if 0 <= nx < 3 and 0 <= ny < 3: # Check boundaries
new_pos = self.sop(nx, ny)
new_board = self.board[:]
new_board[i], new_board[new_pos] = new_board[new_pos],
new_board[i] # Swap the tiles
next_moves.append(Node(new_board, self))
return next_moves
9
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
return
if state not in visited:
visited.add(state)
for next_state in state.next():
if next_state not in visited:
queue.append(next_state)
print("Solution not found.")
def print_path(state):
path = []
while state:
path.append(state)
state = state.prev
path.reverse()
for step in path:
print(step)
print("---------")
10
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
OUTPUT:-
11
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
12
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 3
Aim:- Write a program to implement DFS (for 8 puzzle problem or Water
Jug problem or any AI search problem)
Code:-
class WaterJugState:
def __init__(self, jug1, jug2, prev=None):
self.jug1 = jug1
self.jug2 = jug2
self.prev = prev
def __hash__(self):
return hash((self.jug1, self.jug2))
def __str__(self):
return f"Jug 1: {self.jug1}, Jug 2: {self.jug2}"
# Fill Jug 1
if self.jug1 < max_jug1:
13
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
# Fill Jug 2
if self.jug2 < max_jug2:
next_states.append(WaterJugState(self.jug1, max_jug2, self))
# Empty Jug 1
if self.jug1 > 0:
next_states.append(WaterJugState(0, self.jug2, self))
# Empty Jug 2
if self.jug2 > 0:
next_states.append(WaterJugState(self.jug1, 0, self))
14
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
return next_states
def print_path(state):
path = []
while state:
15
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
path.append(state)
state = state.prev
path.reverse()
for s in path:
print(s)
# Main
if __name__ == "__main__":
max_jug1 = 4 # Capacity of Jug 1
max_jug2 = 3 # Capacity of Jug 2
target = 2 # Target amount to measure
16
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 4
Aim:. Write a program to implement Single Player Game (Using any
Heuristic Function)
Code:
import random
def play_game():
print("Welcome to the Guessing Game!")
target_number = random.randint(1, 100)
low, high = 1, 100
attempts = 0
while True:
guess = heuristic_guess(low, high)
attempts += 1
print(f"I guess {guess}")
if guess == target_number:
print(f"Congratulations! I guessed the number {target_number} in
{attempts} attempts.")
break
elif guess < target_number:
print("Too low!")
low = guess + 1
else:
print("Too high!")
high = guess - 1
if __name__ == "__main__":
play_game()
17
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
Output:
18
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 5
Code:
import heapq
class PuzzleState:
def __init__(self, board, parent=None, g=0):
self.board = board
self.parent = parent
self.g = g # Cost to reach this state from the start
self.h = self.manhattan_distance() # Heuristic value (Manhattan
Distance)
self.f = self.g + self.h # Total cost: f = g + h
def manhattan_distance(self):
distance = 0
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
for i in range(9):
if self.board[i] == 0:
continue
current_pos = (i // 3, i % 3)
19
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
def __hash__(self):
return hash(tuple(self.board)) # To ensure it's hashable for visited set
def get_neighbors(self):
neighbors = []
zero_pos = self.board.index(0)
x, y = zero_pos // 3, zero_pos % 3 # Find the position of 0 (blank
space)
20
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
new_board[zero_pos], new_board[new_pos] =
new_board[new_pos], new_board[zero_pos]
neighbors.append(PuzzleState(new_board, parent=self, g=self.g
+ 1))
return neighbors
def __str__(self):
"""For visualizing the board in a readable way"""
return "\n".join([' '.join(map(str, self.board[i:i+3])) for i in range(0, 9, 3)])
while open_list:
# Pop the state with the lowest f value from the open list
_, current_state = heapq.heappop(open_list)
21
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
return
def print_solution_path(state):
path = []
while state:
path.append(state)
state = state.parent
path.reverse()
22
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
# Main
if __name__ == "__main__":
start_board = [2, 0, 1, 4, 5, 3, 8, 7, 6] # Example start state
goal_board = [1, 2, 3, 4, 5, 6, 7, 8, 0] # Goal state
start_state = PuzzleState(start_board)
goal_state = PuzzleState(goal_board)
Output:
23
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
24
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
25
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
26
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 6
Aim:-Write a program to implement mini-max algorithm for any game
development.
Code:
import math
# Constants for Tic-Tac-Toe
PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
27
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
return True
return False
def is_board_full(board):
return all(cell != EMPTY for row in board for cell in row)
if is_max_turn:
max_eval = -math.inf
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
board[i][j] = PLAYER_X
28
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
def best_move(board):
best_score = -math.inf
move = (-1, -1)
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
board[i][j] = PLAYER_X # Maximize for X
score = minimax(board, 0, False)
board[i][j] = EMPTY
29
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
return move
while True:
# Player O's turn
print("\nPlayer O's turn (minimizing):")
move = best_move(board)
board[move[0]][move[1]] = PLAYER_O
print_board(board)
if is_winner(board, PLAYER_O):
print("\nPlayer O wins!")
break
if is_board_full(board):
print("\nIt's a draw!")
break
30
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
if is_winner(board, PLAYER_X):
print("\nPlayer X wins!")
break
if is_board_full(board):
print("\nIt's a draw!")
break
if __name__ == "__main__":
play_game()
Output:
31
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
32
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
33
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
34
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
35
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 7
Aim: Assume given a set of facts of the form father (name1, name2)
(name1 is the father of name2).
Code:-
father(bob, ann).
father(bob, pat).
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
mother(pam, ann).
mother(liz, pat).
36
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
Output:
37
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 8
Aim: Define a predicate brother(X,Y) which holds iff X and Y are brothers.
Define a predicate cousin(X,Y) which holds if X and Y are cousins.
Define a predicate grandson(X,Y) which holds iff X is a grandson of Y.
Define a predicate descendent(X,Y) which holds iff X is a descendent of Y.
Consider the following genealogical tree: father(a,b). father(a,c).
father(b,d). father(b,e). father(c,f).
Say which answers, and in which order, are generated by your definitions
for the following queries in Prolog:
?- brother(X,Y).
?- cousin(X,Y).
?- grandson(X,Y).
?- descendent(X,Y).
Code:
father(kevin,milu). father(kevin,yash). father(milu,meet). father(milu,raj).
father(yash,jay).
brother(X,Y):-father(K,X),father(K,Y).
cousin(A,B):-father(K,X),father(K,Y),father(X,A),father(Y,B). grandson(X,Y):
father(X,K),father(K,Y).
descendent(X,Y):-father(K,X),father(K,Y).
descendent(X,Y):-father(K,X),father(K,Y),father(X,A),father(Y,B).
Output:
38
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
39
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 9
Aim: Write a program to solve Tower of Hanoi problem using Prolog.
Code:
40
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
auxiliary(Source, Destination) :-
\+ Source = Destination. % Base case: move one disk from source to
destination
hanoi(1, Source, Destination, [move(Source, Destination)]).
41
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
Output:
42
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 10
Aim: Write a program to solve N-Queens problem using Prolog
Code:
% Define the goal state
goal([1, 2, 3, 4, 5, 6, 7, 8, 0]).
% Define the possible moves move([X1, 0, X3, X4, X5, X6, X7, X8, X9], [0,
X1, X3, X4, X5, X6, X7, X8, X9]).
move([X1, X2, 0, X4, X5, X6, X7, X8, X9], [X2, 0, X1, X4, X5, X6, X7, X8,
X9]).
% ... (define other moves here) ...
% Define the solve predicate
solve(Puzzle) :-
depth_first_search(Puzzle,[Puzzle],Moves),
display_moves(Moves).
% Define the depth-first search predicate
depth_first_search(Puzzle,_Visited,[Puzzle]) :- goal(Puzzle).
depth_first_search(Puzzle,Hist,[Puzzle|Moves]) :-
move(Puzzle,Puzzle1),
not(member(Puzzle1,Hist)),
depth_first_search(Puzzle1,[Puzzle1|Hist],Moves).
% Define the display predicate
display_moves([Puzzle]) :- write(Puzzle), nl.
display_moves([Puzzle1,Puzzle2|T]) :-
write(Puzzle1), nl,
display_moves([Puzzle2|T]).
43
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
Output:
44
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 11
Aim: Write a program to solve 8 puzzle problem using Prolog.
Code:
45
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
Output:
46
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
PRACTICAL 12
Aim: Write a program to solve travelling salesman problem using Prolog.
Code:
% Define the distances between cities
distance(city1, city2, 10).
distance(city1, city3, 15).
distance(city2, city3, 20).
% ... (define other distances here) ...
% Define the TSP predicate
tsp(Start, Path, Cost) :-
findall(City, distance(Start, City, _), Cities),
permutation(Cities, Path1),
Path = [Start|Path1],
path_cost(Path, Cost).
% Define the path_cost predicate
path_cost([_], 0).
path_cost([City1,City2|Rest], Cost) :-
distance(City1, City2, Cost1),
path_cost([City2|Rest], Cost2),
Cost is Cost1 + Cost2.
% Define the permutation predicate
permutation([], []). permutation(List, [H|Permutation]) :-
select(H, List, Rest),
permutation(Rest, Permutation).
47
ARTIFICIAL INTELLIGENCE (3170716) 191390107018
Output:
48