0% found this document useful (0 votes)
112 views29 pages

CS1503 AI Lab

Here’s a **short description** for each uploaded file: --- ### ✅ **Linux\_Networking\_Lab\_Assignment.pdf** This document contains a step-by-step guide to performing core Linux networking tasks. It covers commands for IP/MAC address checking, TCP connections, `iperf`, DNS lookup, Wireshark usage, SSH/SCP, Linux bridge creation, Mininet topology simulation, and OpenDaylight SDN integration. --- ### ✅ **CS1503 AI Lab.docx** This is an Artificial Intelligence lab manual with Python programs i

Uploaded by

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

CS1503 AI Lab

Here’s a **short description** for each uploaded file: --- ### ✅ **Linux\_Networking\_Lab\_Assignment.pdf** This document contains a step-by-step guide to performing core Linux networking tasks. It covers commands for IP/MAC address checking, TCP connections, `iperf`, DNS lookup, Wireshark usage, SSH/SCP, Linux bridge creation, Mininet topology simulation, and OpenDaylight SDN integration. --- ### ✅ **CS1503 AI Lab.docx** This is an Artificial Intelligence lab manual with Python programs i

Uploaded by

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

CS1503 Artificial Intelligence Lab Integrated Dept.

of CSE
2023 - 2024

Ex. No. 1 8 PUZZLE PROBLEM Date:

Aim:

To write a python program to solve the 8-puzzle problem, this consists of a


3×3 board with eight numbered tiles and a blank space.

Algorithm:

Step 1: Define a list OPEN. Initially, open consists solely of a single node, the
start node S.

Step 2: If the list is empty, return failure and exit.

Step 3: Remove node n with the smallest value of f(n) from OPEN and move it
to list CLOSED. If node n is a goal state, return success and exit.

Step 4: Expand node n.

Step 5: If any successor to n is the goal node, return success and the solution
by tracing the path from goal node to S. Otherwise, go to Step-06.

Step 6: For each successor node,


Step 6.1: Apply the evaluation function f to the node.
Step 6.2: If the node has not been in either list, add it to OPEN.

Step 7: Go back to Step 2.

Program:
class Solution:
def solve(self, board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = 0
if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return 0

1
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

return self.get_paths(dict)
def get_paths(self, dict):
cnt = 0
while True:
current_nodes = [x for x in dict if dict[x] == cnt]
if len(current_nodes) == 0:
return -1
for node in current_nodes:
next_moves = self.find_next(node)
for move in next_moves:
if move not in dict:
dict[move] = cnt + 1
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return cnt + 1
cnt += 1
def find_next(self, node):
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}
results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0],
new_node[move]

2
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

results.append(tuple(new_node))
return results
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print(ob.solve(matrix))

Output:

Result:

Thus the 8-puzzle problem was written, executed and verified successfully.

Ex. No. 2 To implement Water Jug Problem Date:

Aim:

To write a python program to solve the water jug problem.

3
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Algorithm:

Step 1: Water jug problem is a well-known state space search problem.

Step 2: First we will fill the 4 litre jug completely with water.

Step 3: Then optimal approach would be to empty water from 4-litre jug into 3-
litre.

Step 4: Now, Empty water from 3L.

Step 5: Pour the water from 4L jug into 3L jug now 4L container is completely
empty and 1L water in present in 3L litre jug.

Step 6:- Fill the 4L jug with water completely again.

Step 7:- On transferring water from 4L jug to 3L jug, we will get 2L water in 4L
jug which was our required quantity.

Program:

print("Water Jug Problem")


x=int(input("Enter X:"))
y=int(input("Enter Y:"))
while True:
rno=int(input("Enter the Rule No"))
if rno==1:
if x<4:x=4
if rno==2:
if y<3:y=3
if rno==5:
if x>0:x=0
if rno==6:
if y>0:y=0
if rno==7:
if x+y>= 4 and y>0:x,y=4,y-(4-x)
if rno==8:
if x+y>=3 and x>0:x,y=x-(3-y),3
if rno==9:
if x+y<=4 and y>0:x,y=x+y,0
if rno==10:
if x+y<=3 and x>0:x,y=0,x+y
print("X =" ,x)

4
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

print("Y =" ,y)


if (x==2):
print(" The result is a Goal state")
break
Output:

Water Jug Problem


Enter X:0
Enter Y:0
Enter the Rule No2
X=0
Y=3
Enter the Rule No9
X=3
Y=0
Enter the Rule No2
X=3
Y=3
Enter the Rule No7
X=4
Y=2
Enter the Rule No5
X=0
Y=2
Enter the Rule No9
X=2
Y=0
Enter the Rule No9
X=2
Y=0
Enter the Rule No9
X=2
Y=0
The result is a Goal state.
Result:
Thus the water- jug problem was written, executed and verified successfully.

Ex. No. 3 PATH SEARCH PROBLEM USING Date:


A* SEARCH ALGORITHM

Aim:

To write a python program for a path search problem to find a path from point
A to point B using A* Search Algorithm.

5
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Algorithm:

Step 1: Add start node to list.

Step 2: For all the neighbouring nodes, find the least cost F node.

Step 3: Switch to the closed list.

Step3.1: For 8 nodes adjacent to the current node


Step 3.2: If the node is not reachable, ignore it. Else perform step 3.2.1
or 3.2.2

Step 3.2.1: If the node is not on the open list, move it to the open
list and calculate f, g, h.
Step3.2.2: If the node is on the open list, check if the path it offers
is less than the current path and change to it if it does so.

Step 4: Stop working by either considering step 4.1 or 4.2 .


Step 4.1: The destination is reached.
Step 4.2: The destination is not reached going through all possible
points.

Program:

def aStarAlgo(start_node, stop_node):


open_set = set(start_node)
closed_set = set()
g = {} #store distance from starting node
parents = {}# parents contains an adjacency map of all nodes
#ditance of starting node from itself is zero
g[start_node] = 0
#start_node is root node i.e it has no parent nodes
#so start_node is set to its own parent node
parents[start_node] = start_node
while len(open_set) > 0:
n = None
#node with lowest f() is found
for v in open_set:
if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):
n=v
if n == stop_node or Graph_nodes[n] == None:
pass
else:

6
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

for (m, weight) in get_neighbors(n):


#nodes 'm' not in first and last set are added to first
#n is set its parent
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m] = n
g[m] = g[n] + weight
#for each node m,compare its distance from start
i.e g(m) to the
#from start through n node
else:
if g[m] > g[n] + weight:
#update g(m)
g[m] = g[n] + weight
#change parent of m to n
parents[m] = n
#if m in closed set,remove and add to
open
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
print('Path does not exist!')
return None
# if the current node is the stop_node
# then we begin reconstructin the path from it to the start_node
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
print('Path found: {}'.format(path))
return path
# remove n from the open_list, and add it to closed_list
# because all of his neighbors were inspected
open_set.remove(n)
closed_set.add(n)
print('Path does not exist!')
return None
#define fuction to return neighbor and its distance
#from the passed node
def get_neighbors(v):

7
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
#for simplicity we ll consider heuristic distances given
#and this function returns heuristic distance for all nodes
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
}
return H_dist[n]
#Describe your graph here
Graph_nodes = {
'A': [('B', 2), ('E', 3)],
'B': [('C', 1),('G', 9)],
'C': None,
'E': [('D', 6)],
'D': [('G', 1)],
}
aStarAlgo('A', 'G')

Output:

Path found: [‘A’, ‘E’, ‘D’, ‘G’ ]

Result:

Thus the A* searching problem was written, executed and verified


successfully.
Ex. No. 4 HILL CLIMBING SEARCH ALGORITHM Date:

Aim:

To write a python program to implement Hill Climbing Search Algorithm, to


find the solution for a Travelling Salesman Problem.

Algorithm:

8
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Algorithm for Simple Hill Climbing:

Step 1: Evaluate the initial state, if it is goal state then return success and
Stop.

Step 2: Loop Until a solution is found or there is no new operator left to apply.

Step 3: Select and apply an operator to the current state.

Step 4: Check new state:


Step 4.1: If it is goal state, then return success and quit.
Step 4.2: Else if it is better than the current state then assign new state
as a current state.
Step 4.3: Else if not better than the current state, then return to step2.

Step 5: Exit.

Algorithm for Steepest-Ascent hill climbing:

Step 1: Evaluate the initial state, if it is goal state then return success and
stop, else make current state as initial state.

Step 2: Loop until a solution is found or the current state does not change.

Step 3: Let SUCC be a state such that any successor of the current state will
be better than it.

Step 4: For each operator that applies to the current state:


Step 4.1: Apply the new operator and generate a new state.
Step 4.2: Evaluate the new state.
Step 4.3: If it is goal state, then return it and quit, else compare it to the
SUCC.
Step 4.4: If it is better than SUCC, then set new state as SUCC.
Step 4.5: If the SUCC is better than the current state, then set current
state to SUCC.

Step 5: Exit.

Program:

import random
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []

9
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
solution.append(randomCity)
cities.remove(randomCity)

return solution

def routeLength(tsp, solution):


routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength

def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours

def getBestNeighbour(tsp, neighbours):


bestRouteLength = routeLength(tsp, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
return bestNeighbour, bestRouteLength

def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength =
getBestNeighbour(tsp, neighbours)

10
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

while bestNeighbourRouteLength < currentRouteLength:


currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength =
getBestNeighbour(tsp, neighbours)

return currentSolution, currentRouteLength

def main():
tsp = [
[0, 400, 500, 300],
[400, 0, 300, 500],
[500, 300, 0, 400],
[300, 500, 400, 0]
]

print(hillClimbing(tsp))

if __name__ == "__main__":
main()

Output:

([1, 2, 3, 0], 1400)

Result:

Thus the Hill Climbing problem was written, executed and verified
successfully.
Create a First Order Logic solver.

Ex no: 5 Create a First Order Logic solver Date:

Aim:

11
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

To Create a first order logic solver using python

Algorithm:

Step 1: Define the necessary functions:parse_fol(statement).

Step 2: Takes a FOL statement as input and extracts the predicates and their
arguments using regular expressions.

Step 3: Returns the list of predicates and arguments.


evaluate_fol(statement, facts):

Step 4: Takes a FOL statement and a dictionary of facts as input.

Step 5: Evaluates the FOL statement by parsing it using parse_fol.

Step 6: Checks if the predicates in the statement exist in the facts, performs
argument substitution, and adds any new predicates to the facts with an
empty list as the value.

Step 7: Create an initial dictionary of facts with some pre-defined predicates


and empty lists as values.

Step 8: Call evaluate_fol(statement, facts) with the desired FOL statement and
the facts dictionary.

Step 9: Print the updated facts dictionary.

Program:

import re
# Function to parse a FOL statement into predicates and arguments
def parse_fol(statement):
pattern = r'([A-Za-z]+\([^)]*\))'
predicates = re.findall(pattern, statement)
arguments = [re.findall(r'\w+', pred) for pred in predicates]
return predicates, arguments
# Function to evaluate a FOL statement
def evaluate_fol(statement, facts):
predicates, arguments = parse_fol(statement)
for pred, args in zip(predicates, arguments):
pred_parts = pred.split('(')
pred_name = pred_parts[0]

12
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

pred_args = pred_parts[1].rstrip(')').split(',')
if pred_name in facts:
fact_args = facts[pred_name]
if len(args) == len(fact_args):
substitution = {arg: fact_arg for arg, fact_arg in zip(args, fact_args)}
substituted_pred_args = [substitution.get(arg, arg) for arg in
pred_args]
substituted_pred = f"{pred_name}
({','.join(substituted_pred_args)})"
if substituted_pred not in facts:
facts[substituted_pred] = []
else:
facts[pred] = []
# Example usage
facts = {
'Person(John)': [],
'Person(Mary)': [],
'Likes(John, IceCream)': [],
'Likes(Mary, Chocolate)': []
}
statement = 'Likes(x, IceCream)'
evaluate_fol(statement, facts)
print(facts)

Output:

{
'Person(John)': [],
'Person(Mary)': [],
'Likes(John, IceCream)': [],
'Likes(Mary, Chocolate)': [],
'Likes(x, IceCream)': []
}

Result:

Thus the first order logic problem was written, executed and verified
successfully.

Ex. No.6 Develop a Forward Chaining Inference Engine Date:

Aim:

13
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

To write a python program to Develop a Forward Chaining Inference Engine.

Algorithm:

Step 1: Implement a function to check if a rule is applicable based on the


current facts.

Step 2: Implement a function to apply a rule by adding its conclusion to the


facts if the rule is applicable.

Step 3: Implement the main forward chaining inference engine function.

Step 4: Inside the inference engine function, iterate until no new facts can be
inferred.

Step 5: Set a flag to track if a new fact was added in the current iteration.
Step 6: Iterate over each rule.

Step 7: Check if the rule is applicable.

Step 8: If the rule is applicable and its conclusion is not already a fact.

Step 9: Apply the rule by adding its conclusion to the facts.

Step 10: Set the flag to indicate that a new fact was added.
Step 11: Print the applied rule and the updated facts.

Step 12: If no new fact was added in the iteration, break the loop.

Step 13: Call the forward chaining inference engine function with the initial
rules and facts.

Program:

# Define the rules


rules = [
{
'name': 'Rule 1',
'conditions': ['A'],
'conclusion': 'B'
},
{

14
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

'name': 'Rule 2',


'conditions': ['B'],
'conclusion': 'C'
},{

'name': 'Rule 3',


'conditions': ['C'],
'conclusion': 'D'
},{
'name': 'Rule 4',
'conditions': ['E', 'F'],
'conclusion': 'A'
}
]

# Define the facts


facts = ['E', 'F']
# Function to check if a rule is applicable
def is_rule_applicable(rule, facts):
for condition in rule['conditions']:
if condition not in facts:
return False
return True
# Function to apply a rule
def apply_rule(rule, facts):
if is_rule_applicable(rule, facts) and rule['conclusion'] not in facts:
facts.append(rule['conclusion'])
return True
return False # Main forward chaining inference engine
def forward_chaining_inference_engine(rules, facts):
while True:
new_fact_added = False
for rule in rules:
if apply_rule(rule, facts):
new_fact_added = True
print(f"Applied rule: {rule['name']}")
print(f"Facts: {facts}")
if not new_fact_added:
break # Run the forward chaining inference engine
forward_chaining_inference_engine(rules, facts)

Output:

Applied rule: Rule 4

15
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Facts: ['E', 'F', 'A']


Applied rule: Rule 1
Facts: ['E', 'F', 'A', 'B']
Applied rule: Rule 2
Facts: ['E', 'F', 'A', 'B', 'C']
Applied rule: Rule 3
Facts: ['E', 'F', 'A', 'B', 'C', 'D']

Result:

Thus the forward chaining inference engine problem was written, executed
and verified successfully.

Ex. No.7 Simple Agent for the Vacuum-Cleaner world problem


Date:

Aim:

16
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

To develop a Simple Agent for the Vacuum-Cleaner world problem using


python

Algorithm:

Step 1: Define the Vacuum Cleaner Agent class with the following methods:

● __init__: Initialize the agent's location.


● perceive: Accept the current room's location and status (clean or dirty)
as input and print the percept.
● clean: Accept the current room's location as input, clean the room, and
return True.
● choose_action: Accept the current room's location and status as input
and return an action based on the percept. If the room is dirty, return
'clean'; otherwise, return 'move' to switch to the other room or
'move_back' to go back to the original room.
● act: Accept the chosen action as input and perform the corresponding
action, i.e., change the agent's location if it's a movement action.
Step 2: Initialize the agent.

Step 3: Define the initial state of the rooms, represented by a list of Boolean
values (True for clean, False for dirty).

Step 4: Repeat the following steps until all rooms are clean:

● Get the current location of the agent.


● Perceive the current room's status (clean or dirty) using the perceive
method.
● Choose an action based on the current percept using the choose_action
method.
● If the chosen action is 'clean', use the clean method to clean the current
room and update its status to True.
● If the chosen action is 'move' or 'move_back', use the act method to
change the agent's location accordingly.
Step 5: The agent will continue cleaning and moving between rooms until all
rooms are clean. The program terminates when all rooms have been cleaned.

Program

class VacuumCleanerAgent:
def __init__(self):
self.location = 0 # 0 represents Room A, and 1 represents Room B

17
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

def perceive(self, location, status):


# location: The current room (0 for Room A, 1 for Room B)
# status: The cleanliness status (True for clean, False for dirty)
print(f"Perceiving Room {chr(ord('A') + location)} - Status: {'Clean' if
status else 'Dirty'}")

def clean(self, location):


# Clean the room
print(f"Cleaning Room {chr(ord('A') + location)}")
return True

def choose_action(self, location, status):


# Choose the action based on the current percept
if status == False: # If the room is dirty, clean it
return 'clean'
else: # If the room is clean, move to the other room
return 'move' if location == 0 else 'move_back'

def act(self, action):


# Perform the action
if action == 'move':
self.location = 1
print("Moving to Room B")
elif action == 'move_back':
self.location = 0
print("Moving back to Room A")

def main():
agent = VacuumCleanerAgent()

# Define the initial state of the rooms (True represents clean, False
represents dirty)
rooms = [True, False]

# Run the agent until all rooms are clean


while not all(rooms):
current_location = agent.location
agent.perceive(current_location, rooms[current_location])
action = agent.choose_action(current_location, rooms[current_location])

if action == 'clean':
rooms[current_location] = agent.clean(current_location)
elif action == 'move' or action == 'move_back':

18
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

agent.act(action)

if __name__ == "__main__":
main()

Result:

Thus the Simple Agent for the Vacuum-Cleaner world problem was written,
executed and verified successfully.

Ex. No.8 Create a Tic Tac Toe Game program


Date:

19
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Aim:

To Create a Tice Tac Toe Game program using python.

Algorithm:

Step 1: Create a 3x3 grid to represent the Tic Tac Toe board.

Step 2: Define a function print_board(board) to display the current state of the


board.

Step 3: Define a function check_winner(board) to check if any player has won


the game. The function checks for winning conditions in rows, columns, and
diagonals.

Step 4: Define a function play_game() to handle the main game logic.

Step 5: Inside the play_game() function: a. Initialize the board and set the
current player as "X". b. Run a loop until the game is over.

Step 6: Print the board using print_board(board).

Step 7: Prompt the current player to enter the row and column for their move.

Step 8: Validate the move and update the board with the player's mark.

Step 9: Increment the move counter.

Step 10: Check if the current player has won using check_winner(board).

Step 11: If there is a winner, print the board and the winning player.

Step 12: Break the loop and end the game.

Step 13: Check if the game is a draw (moves == 9). 1. If it is a draw, print the
board and announce the draw. 2. Break the loop and end the game.

Step 14: Switch the current player to the other player ("X" to "O" or vice
versa).

Step 15: Call the play_game() function to start the Tic Tac Toe game.

Program:

20
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

# Function to print the Tic Tac Toe board


def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
# Function to check if any player has won the game
def check_winner(board):
# Check rows
for row in board:
if row[0] == row[1] == row[2] != " ":
return row[0]
# Check columns
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] != " ":
return board[0][col]
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != " ":
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != " ":
return board[0][2]
return None
# Function to play the Tic Tac Toe game
def play_game():
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
current_player = "X"
moves = 0
while True:
print_board(board)
# Get player's move
while True:
row = int(input("Enter the row (0-2): "))
col = int(input("Enter the column (0-2): "))
if 0 <= row <= 2 and 0 <= col <= 2 and board[row][col] == " ":
board[row][col] = current_player
break
else:
print("Invalid move. Try again.")
moves += 1
# Check if the current player has won
winner = check_winner(board)
if winner:
print_board(board)
print(f"Player {winner} wins!")
break

21
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

# Check if the game is a draw


if moves == 9:
print_board(board)
print("It's a draw!")
break
# Switch to the other player
current_player = "O" if current_player == "X" else "X"
# Play the Tic Tac Toe game
play_game()

Output:

| |
-----------
| |
-----------
| |

Enter the row (0-2): 1


Enter the column (0-2): 1
| |
-----------
|X|
-----------
| |

Enter the row (0-2): 0


Enter the column (0-2): 0
O| |
-----------
|X|
-----------
| |

Enter the row (0-2): 1


Enter the column (0-2): 0
O| |
-----------
X|X|
-----------
| |

Enter the row (0-2): 0


Enter the column (0-2): 1

22
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

O|X|
-----------
X|X|
-----------
| |

Enter the row (0-2): 0


Enter the column (0-2): 2
O|X|O
-----------
X|X|
-----------
| |

Enter the row (0-2): 2


Enter the column (0-2): 0
O|X|O
-----------
X|X|
-----------
X| |

Player X wins!

Result:

Thus the Tic Tac Toe game problem was written, executed and verified
successfully.

Ex. No.9 Simulation of Turtle moving Date:

Aim:

To create a simulation of turtle moving using python.

Algorithm:

23
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Step 1: Define the initial position and heading of the turtle.

Step 2: Define a list of movement commands, where each command consists


of a keyword (e.g., 'forward', 'backward', 'right', 'left') and a value
representing the distance or angle.

Step 3: Iterate over each movement command.


Step 4: If the command is 'forward', update the turtle's position by moving it
forward by the given distance in the current heading direction.

Step 5: If the command is 'backward', update the turtle's position by moving it


backward by the given distance in the current heading direction.

Step 6: If the command is 'right', update the turtle's heading by turning it right
by the given angle.

Step 7: If the command is 'left', update the turtle's heading by turning it left by
the given angle.

Step 8: After executing all the movement commands, display the final position
and heading of the turtle.

Program:

import turtle
# Create a turtle object
my_turtle = turtle.Turtle()
# Move the turtle forward
my_turtle.forward(100)
# Rotate the turtle left by 90 degrees
my_turtle.left(90)
# Move the turtle forward again
my_turtle.forward(100)
# Rotate the turtle right by 45 degrees
my_turtle.right(45)
# Move the turtle backward
my_turtle.backward(100)
# Hide the turtle
my_turtle.hideturtle()
# Close the turtle graphics window
turtle.done()

Output:

24
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Result:

Thus the Turtle moving problem was written, executed and verified
successfully.

Ex No: 10 Simulation of Game playing Date:

Aim:

To create the simulation of game playing using python program

Algorithm:

Step 1: Create a function to initialize the game board.

25
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

Step 2: Create a function to print the current state of the board.

Step 3: Create a function to check if the board is full.

Step 4: Create a function to make a move on the board.

Step 5: Create a function to check for a winner.

Step 6: Simulate the game playing.

Step 7: Initialize the game board.

Step 8: Set the current player as Player 1.

Step 9: Repeat the following steps until the game ends.

Step 10: Print the current state of the board.

Step 11: Prompt the current player to enter their move (row and column).

Step 12: Make the move on the board if it is valid.

Step 13: Check if the current player wins.

Step 14: If there is a winner, print the winner and end the game.

Step 15: Check if the board is full.

Step 16: If the board is full, print that it's a draw and end the game.

Step 17: Switch to the next player.

Step 18: End the game.

Program:

# Define the game rules and logic


def initialize_board():
# Create an empty game board
return [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]

26
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

def print_board(board):
# Print the current state of the game board
for row in board:
print(row)
def is_board_full(board):
# Check if the game board is full
for row in board:
if 0 in row:
return False
return True
def make_move(board, row, col, player):
# Make a move on the game board
if board[row][col] == 0:
board[row][col] = player
return True
else:
return False
def check_winner(board):
# Check if there is a winner
for i in range(3):
# Check rows
if board[i][0] == board[i][1] == board[i][2] != 0:
return board[i][0]
# Check columns
if board[0][i] == board[1][i] == board[2][i] != 0:
return board[0][i]
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != 0:
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != 0:
return board[0][2]
# No winner
return 0
# Simulate the game playing
# Initialize the game board
board = initialize_board()
current_player = 1
# Main game loop
while True:
# Print the current state of the board
print_board(board)
# Prompt the current player to make a move
row = int(input("Enter the row (0-2): "))
col = int(input("Enter the column (0-2): "))

27
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

# Make the move


if make_move(board, row, col, current_player):
# Check if the current player wins
winner = check_winner(board)
if winner != 0:
print("Player", winner, "wins!")
break
# Check if the game is a draw
if is_board_full(board):
print("It's a draw!")
break
# Switch to the next player
current_player = 2 if current_player == 1 else 1
else:
print("Invalid move. Try again.")

Output:

[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Enter the row (0-2): 1
Enter the column (0-2): 1
[0, 0, 0]
[0, 1, 0]
[0, 0, 0]
Enter the row (0-2): 0
Enter the column (0-2): 0
[2, 0, 0]
[0, 1, 0]
[0, 0, 0]
Enter the row (0-2): 1
Enter the column (0-2): 2
[2, 0, 0]
[0, 1, 1]
[0, 0, 0]
Enter the row (0-2): 2
Enter the column (0-2): 2
[2, 0, 0]
[0, 1, 1]
[0, 0, 2]
Enter the row (0-2): 2
Enter the column (0-2): 0
[2, 0, 0]

28
CS1503 Artificial Intelligence Lab Integrated Dept. of CSE
2023 - 2024

[0, 1, 1]
[1, 0, 2]
Enter the row (0-2): 0
Enter the column (0-2): 2
[2, 0, 1]
[0, 1, 1]
[1, 0, 2]
Enter the row (0-2): 0
Enter the column (0-2): 1
[2, 2, 1]
[0, 1, 1]
[1, 0, 2]
Enter the row (0-2): 1
Enter the column (0-2): 0
[2, 2, 1]
[1, 1, 1]
[1, 0, 2]
Player 1 wins!

Result:

Thus the Simulation of Game playing problem was written, executed and
verified successfully.

29

You might also like