Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

# N Queen Problem
print ("Enter the number of queens")
N = int(input())
# here we create a chessboard
# NxN matrix with all elements set to 0
board = [[0]*N for _ in range(N)]
def attack(i, j):
#checking vertically and horizontally
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
#checking diagonally
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)

Enter the number of queens


4
[1, 0, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]
[0, 1, 0, 0]

#N-Queen Problem
N = 8 # (size of the chessboard)

def solveNQueens(board, col):


if col == N:
print(board)
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQueens(board, col + 1):
return True
board[i][col] = 0
return False

def isSafe(board, row, col):


for x in range(col):
if board[row][x] == 1:
return False
for x, y in zip(range(row, -1, -1), range(col, -1, -1)):
if board[x][y] == 1:
return False
for x, y in zip(range(row, N, 1), range(col, -1, -1)):
if board[x][y] == 1:
return False
return True

board = [[0 for x in range(N)] for y in range(N)]


if not solveNQueens(board, 0):
print("No solution found")

[[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0],

# 8 – Puzzle Using A* And SMA*Algorithm


# Python3 program to print the path from root
# node to destination node for N*N-1 puzzle
# algorithm using Branch and Bound
# The solution assumes that instance of
# puzzle is solvable

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 1/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

# Importing copy for deepcopy function


import copy

# Importing the heap functions from python


# library for Priority Queue
from heapq import heappush, heappop

# This variable can be changed to change


# the program from 8 puzzle(n=3) to 15
# puzzle(n=4) to 24 puzzle(n=5)...
n = 3

# bottom, left, top, right


row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]

# A class for Priority Queue


class priorityQueue:

# Constructor to initialize a
# Priority Queue
def __init__(self):
self.heap = []

# Inserts a new key 'k'


def push(self, k):
heappush(self.heap, k)

# Method to remove minimum element


# from Priority Queue
def pop(self):
return heappop(self.heap)

# Method to know if the Queue is empty


def empty(self):
if not self.heap:
return True
else:
return False

# Node structure
class node:

def __init__(self, parent, mat, empty_tile_pos,


cost, level):

# Stores the parent node of the


# current node helps in tracing
# path when the answer is found
self.parent = parent

# Stores the matrix


self.mat = mat

# Stores the position at which the


# empty space tile exists in the matrix
self.empty_tile_pos = empty_tile_pos

# Stores the number of misplaced tiles


self.cost = cost

# Stores the number of moves so far


self.level = level

# This method is defined so that the


# priority queue is formed based on
# the cost variable of the objects
def __lt__(self, nxt):
return self.cost < nxt.cost

# Function to calculate the number of


# misplaced tiles ie. number of non-blank
# tiles not in their goal position
def calculateCost(mat, final) -> int:

count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1

t t
https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 2/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
return count

def newNode(mat, empty_tile_pos, new_empty_tile_pos,


level, parent, final) -> node:

# Copy data from parent matrix to current matrix


new_mat = copy.deepcopy(mat)

# Move tile by 1 position


x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]

# Set number of misplaced tiles


cost = calculateCost(new_mat, final)

new_node = node(parent, new_mat, new_empty_tile_pos,


cost, level)
return new_node

# Function to print the N x N matrix


def printMatrix(mat):

for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")

print()

# Function to check if (x, y) is a valid


# matrix coordinate
def isSafe(x, y):

return x >= 0 and x < n and y >= 0 and y < n

# Print path from root node to destination node


def printPath(root):

if root == None:
return

printPath(root.parent)
printMatrix(root.mat)
print()

# Function to solve N*N - 1 puzzle algorithm


# using Branch and Bound. empty_tile_pos is
# the blank tile position in the initial state.
def solve(initial, empty_tile_pos, final):

# Create a priority queue to store live


# nodes of search tree
pq = priorityQueue()

# Create the root node


cost = calculateCost(initial, final)
root = node(None, initial,
empty_tile_pos, cost, 0)

# Add root to list of live nodes


pq.push(root)

# Finds a live node with least cost,


# add its children to list of live
# nodes and finally deletes it from
# the list.
while not pq.empty():

# Find a live node with least estimated


# cost and delete it from the list of
# live nodes
minimum = pq.pop()

# If minimum is the answer node


if minimum.cost == 0:

# Print the path from root to


# destination;
printPath(minimum)
return

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 3/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
# Generate all possible children
for i in range(4):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]

if isSafe(new_tile_pos[0], new_tile_pos[1]):

# Create a child node


child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)

# Add child to list of live nodes


pq.push(child)

# Driver Code

# Initial configuration
# Value 0 is used for empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]

# Solvable Final configuration


# Value 0 is used for empty space
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]

# Blank tile coordinates in


# initial configuration
empty_tile_pos = [ 1, 2 ]

# Function call to solve the puzzle


solve(initial, empty_tile_pos, final)

output 1
5
2
6
3
0
7 8 4

1 2 3
5 0 6
7 8 4

1 2 3
5 8 6
7 0 4

1 2 3
5 8 6
0 7 4

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 4/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
# Python3 program to find the next optimal move for a player
player, opponent = 'x', 'o'

# This function returns true if there are moves


# remaining on the board. It returns false if
# there are no moves left to play.
def isMovesLeft(board) :

for i in range(3) :
for j in range(3) :
if (board[i][j] == '_') :
return True
return False

# This is the evaluation function as discussed


# in the previous article ( http://goo.gl/sJgv68 )
def evaluate(b) :

# Checking for Rows for X or O victory.


for row in range(3) :
if (b[row][0] == b[row][1] and b[row][1] == b[row][2]) :
if (b[row][0] == player) :
return 10
elif (b[row][0] == opponent) :
return -10

# Checking for Columns for X or O victory.


for col in range(3) :

if (b[0][col] == b[1][col] and b[1][col] == b[2][col]) :

if (b[0][col] == player) :
return 10
elif (b[0][col] == opponent) :
return -10

# Checking for Diagonals for X or O victory.


if (b[0][0] == b[1][1] and b[1][1] == b[2][2]) :

if (b[0][0] == player) :
return 10
elif (b[0][0] == opponent) :
return -10

if (b[0][2] == b[1][1] and b[1][1] == b[2][0]) :

if (b[0][2] == player) :
return 10
elif (b[0][2] == opponent) :
return -10

# Else if none of them have won then return 0


return 0

# This is the minimax function. It considers all


# the possible ways the game can go and returns
# the value of the board
def minimax(board, depth, isMax) :
score = evaluate(board)

# If Maximizer has won the game return his/her


# evaluated score
if (score == 10) :
return score

# If Minimizer has won the game return his/her


# evaluated score
if (score == -10) :
return score

# If there are no more moves and no winner then


# it is a tie
if (isMovesLeft(board) == False) :
return 0

# If this maximizer's move


if (isMax) :
best = -1000

# Traverse all cells


for i in range(3) :
for j in range(3) :

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 5/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 6/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

# Check if cell is empty


if (board[i][j]=='_') :

# Make the move


board[i][j] = player

# Call minimax recursively and choose


# the maximum value
best = max( best, minimax(board,
depth + 1,
not isMax) )

# Undo the move


board[i][j] = '_'
return best

# If this minimizer's move


else :
best = 1000

# Traverse all cells


for i in range(3) :
for j in range(3) :

# Check if cell is empty


if (board[i][j] == '_') :

# Make the move


board[i][j] = opponent

# Call minimax recursively and choose


# the minimum value
best = min(best, minimax(board, depth + 1, not isMax))

# Undo the move


board[i][j] = '_'
return best

# This will return the best possible move for the player
def findBestMove(board) :
bestVal = -1000
bestMove = (-1, -1)

# Traverse all cells, evaluate minimax function for


# all empty cells. And return the cell with optimal
# value.
for i in range(3) :
for j in range(3) :

# Check if cell is empty


if (board[i][j] == '_') :

# Make the move


board[i][j] = player

# compute evaluation function for this


# move.
moveVal = minimax(board, 0, False)

# Undo the move


board[i][j] = '_'

# If the value of the current move is


# more than the best value, then update
# best/
if (moveVal > bestVal) :
bestMove = (i, j)
bestVal = moveVal

print("The value of the best Move is :", bestVal)


print()
return bestMove
# Driver code
board = [
[ 'x', 'o', 'x' ],
[ 'o', 'o', 'x' ],
[ '_', '_', '_' ]
]

bestMove = findBestMove(board)

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 7/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

print("The Optimal Move is :")


print("ROW:", bestMove[0], " COL:", bestMove[1])

The value of the best Move is : 10

The Optimal Move is :


ROW: 2 COL: 2

# Python3 program to demonstrate


# working of Alpha-Beta Pruning

# Initial values of Alpha and Beta


MAX, MIN = 1000, -1000

# Returns optimal value for current player


#(Initially called for root and maximizer)
def minimax(depth, nodeIndex, maximizingPlayer,
values, alpha, beta):

# Terminating condition. i.e


# leaf node is reached
if depth == 3:
return values[nodeIndex]

if maximizingPlayer:

best = MIN

# Recur for left and right children


for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,


False, values, alpha, beta)
best = max(best, val)
alpha = max(alpha, best)

# Alpha Beta Pruning


if beta <= alpha:
break

return best

else:
best = MAX

# Recur for left and


# right children
for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,


True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)

# Alpha Beta Pruning


if beta <= alpha:
break

return best

# Driver Code
if __name__ == "__main__":

values = [3, 5, 6, 9, 1, 2, 0, -1]


print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))

The optimal value is : 5

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 8/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
#SUDOKU SOLVER
# N is the size of the 2D matrix N*N
N = 9

# A utility function to print grid


def printing(arr):
for i in range(N):
for j in range(N):
print(arr[i][j], end = " ")
print()

# Checks whether it will be


# legal to assign num to the
# given row, col
def isSafe(grid, row, col, num):

# Check if we find the same num


# in the similar row , we
# return false
for x in range(9):
if grid[row][x] == num:
return False

# Check if we find the same num in


# the similar column , we
# return false
for x in range(9):
if grid[x][col] == num:
return False

# Check if we find the same num in


# the particular 3*3 matrix,
# we return false
startRow = row - row % 3
startCol = col - col % 3
for i in range(3):
for j in range(3):
if grid[i + startRow][j + startCol] == num:
return False
return True

# Takes a partially filled-in grid and attempts


# to assign values to all unassigned locations in
# such a way to meet the requirements for
# Sudoku solution (non-duplication across rows,
# columns, and boxes) */
def solveSudoku(grid, row, col):

# Check if we have reached the 8th


# row and 9th column (0
# indexed matrix) , we are
# returning true to avoid
# further backtracking
if (row == N - 1 and col == N):
return True

# Check if column value becomes 9 ,


# we move to next row and
# column start from 0
if col == N:
row += 1
col = 0

# Check if the current position of


# the grid already contains
# value >0, we iterate for next column
if grid[row][col] > 0:
return solveSudoku(grid, row, col + 1)
for num in range(1, N + 1, 1):

# Check if it is safe to place


# the num (1-9) in the
# given row ,col ->we
# move to next column
if isSafe(grid, row, col, num):

# Assigning the num in


# the current (row,col)
# position of the grid
# and assuming our assigned
# num in the position
# is correct

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 9/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

grid[row][col] = num

# Checking for next possibility with next


# column
if solveSudoku(grid, row, col + 1):
return True

# Removing the assigned num ,


# since our assumption
# was wrong , and we go for
# next assumption with
# diff num value
grid[row][col] = 0
return False

# Driver Code

# 0 means unassigned cells


grid = [[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0]]

if (solveSudoku(grid, 0, 0)):
printing(grid)
else:
print("no solution exists ")

3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 10/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
#Wumpus Game Using PropositionalModel Checking Algorithm
import random

class WumpusGame(object):

def __init__(self, edges=[]):

# Create arbitrary caves from a list of edges (see the end of the script for example).
if edges:
cave = {}
N = max([edges[i][0] for i in range(len(edges))])
for i in range(N):
exits = [edge[1] for edge in edges if edge[0] == i]
cave[i] = exits

# If no edges are specified, play in the standard cave: a dodecahedron.


else:
cave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1,9,10], 5:[2,9,11],
6: [2,7,12], 7: [3,6,13], 8: [3,10,14], 9: [4,5,15], 10: [4,8,16],
11: [5,12,17], 12: [6,11,18], 13: [7,14,18], 14: [8,13,19],
15: [9,16,17], 16: [10,15,19], 17: [11,20,15], 18: [12,13,20],
19: [14,16,20], 20: [17,18,19]}

self.cave = cave

self.threats = {}

self.arrows = 5

self.arrow_travel_distance = 5 # As in the original game. I don't like this choice:


# a bow should not cover a whole cave.
self.player_pos = -1

"""
HELPER: These methods wrap processes that are useful or called often.
"""

def get_safe_rooms(self):
""" Returns a list containing all numbers of rooms that
do not contain any threats
"""
return list(set(self.cave.keys()).difference(self.threats.keys()))

def populate_cave(self):
""" Drop player and threats into random rooms in the cave.
"""
for threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']:
pos = random.choice(self.get_safe_rooms())
self.threats[pos] = threat
self.player_pos = random.choice(self.get_safe_rooms())

def breadth_first_search(self, source, target, max_depth=5):


""" The game board (whether custom or standard dodecahedron) is an undirected graph.
The rooms are the vertices and the tunnels are the edges of this graph. To find
out whether a target room can be reached from a source room using a given amount
of tunnels, one can do a breadth first search on the underlying undirected graph.

BFS works like this: start with the source vertex, maybe it is already the target?
If not, then go a level deeper and find out, if one of the children (also called
successors) of the source vertex is the wanted target. If not, then for each child,
go a level deeper and find out if one of the grand-children is the wanted target.
If not, then for each grand-child go a level deeper and so on.

The following is a recursive implementation of BFS. You will not find any loops
(for, while). Instead you manage two lists. The first one ('stack') contains all
the vertices of the current depth-level (e.g. all grand children). The second
('visited') contains all vertices that you already checked. Now there are three
possibilites: Either stack is empty, then all vertices have been checked unsuccessfully;
or the target vertex is a member of the stack, then you are happy; or the target is
not a member of the stack, but there are still some vertices that you did not visit,
then you append to the stack, all successors of the members of the stack and the old
stack now belongs to the visited vertices.
"""
# Set up some initial values.
graph = self.cave
depth = 0

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 11/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 12/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
def search(stack, visited, target, depth):
if stack == []: # The whole graph was searched, but target was not found.
return False, -1
if target in stack:
return True, depth
visited = visited + stack
stack = list(set([graph[v][i] for v in stack for i in range(len(graph[v]))]).difference(visited))
depth += 1
if depth > max_depth: # Target is too far away from the source.
return False, depth
else: # Visit all successors of vertices in the stack.
return search(stack, visited, target, depth)

return search([source], [], target, depth)

"""
INPUT / OUTPUT: The player interacts with the game.
"""

def print_warning(self, threat):


""" Called when entering a new room. Shows threats in adjacent rooms.
"""
if threat == 'bat':
print("You hear a rustling.")
elif threat == 'pit':
print("You feel a cold wind blowing from a nearby cavern.")
elif threat == 'wumpus':
print("You smell something terrible nearby.")

def get_players_input(self):
""" Queries input until valid input is given.
"""
while 1: # Query the action.

inpt = input("Shoot or move (S-M)? ")


try: # Ensure that the player choses a valid action (shoot or move)
mode = str(inpt).lower()
assert mode in ['s', 'm', 'q']
break
except (ValueError, AssertionError):
print("This is not a valid action: pick 'S' to shoot and 'M' to move.")

if mode == 'q': # I added a 'quit-button' for convenience.


return 'q', 0

while 1: # Query the target of the action.

inpt = input("Where to? ")


try: # Ensure that the chosen target is convertable to an integer.
target = int(inpt)
except ValueError:
print("This is not even a real number.")
continue # Restart the while loop, to get a valid integer as target.

if mode == 'm':
try: # When walking, the target must be adjacent to the current room.
assert target in self.cave[self.player_pos]
break
except AssertionError:
print("You cannot walk that far. Please use one of the tunnels.")

elif mode == 's':


try: # When shooting, the target must be reachable within 5 tunnels.
bfs = self.breadth_first_search(self.player_pos, target)
assert bfs[0] == True
break
except AssertionError:
if bfs[1] == -1: # The target is outside cave.
print("There is no room with this number in the cave. Your arrow travels randomly.")
target = random.choice(self.cave.keys())
if bfs[1] > self.arrow_travel_distance: # The target is too far.
print("Arrows aren't that croocked.")

return mode, target

"""
CORE / GAME LOGIC
"""

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 13/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 14/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

def enter_room(self, room_number):


""" Controls the process of entering a new room.
"""
print("Entering room {}...".format(room_number))
# Maybe a threat waits in the new room.
if self.threats.get(room_number) == 'bat':
# The bat teleports the player to random empty room
print("You encounter a bat, it transports you to a random empty room.")
new_pos = random.choice(self.get_safe_rooms())
return self.enter_room(new_pos)
elif self.threats.get(room_number) == 'wumpus':
print("Wumpus eats you.")
return -1
elif self.threats.get(room_number) == 'pit':
print("You fall into a pit.")
return -1

# The room is safe; collect information about adjacent rooms.


for i in self.cave[room_number]:
self.print_warning(self.threats.get(i))

# Only if nothing else happens, the player enters the room of his choice.
return room_number

def shoot_room(self, room_number):


""" Controls the process of shooting in a room.
"""
print("Shooting an arrow into room {}...".format(room_number))
# Fire an arrow and see if something is hit by it.
self.arrows -= 1
threat = self.threats.get(room_number)
if threat in ['bat', 'wumpus']:
del self.threats[room_number]
if threat == 'wumpus':
print("Hurra, you killed the wumpus!")
return -1
elif threat == 'bat':
print("You killed a bat.")
elif threat in ['pit', None]:
print("This arrow is lost.")

# If this was your last arrow and it did not hit the wumpus...
if self.arrows < 1: # This (or the updating of self.arrows) seems to be broken...
print("Your quiver is empty.")
return -1

# If you shoot into another room, the Wumpus has a 75% of chance of waking up and moving into an adjacent room.
if random.random() < 0.75:
#print("DEBUG: Wumpus moved.")
for room_number, threat in self.threats.items():
if threat == 'wumpus':
wumpus_pos = room_number
new_pos = random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys())))
del self.threats[room_number]
self.threats[new_pos] = 'wumpus'
if new_pos == self.player_pos: # Wumpus entered players room.
print("Wumpus enters your room and eats you!")
return -1

return self.player_pos

def gameloop(self):

print("HUNT THE WUMPUS")


print("===============")
print()
self.populate_cave()
self.enter_room(self.player_pos)

while 1:

#print("DEBUG: Your quiver holds {} arrows.".format(self.arrows))


#print("DEBUG: Rooms with no threats are: {}.".format(self.get_safe_rooms()))
#print("DEBUG: Threats are located in the following rooms: {}".format(self.threats))

print("You are in room {}.".format(self.player_pos), end=" ")


print("Tunnels lead to: {0} {1} {2}".format(*self.cave[self.player_pos]))

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 15/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory

inpt = self.get_players_input() # Player choses move or shoot.


print() # Visual separation of rounds.
if inpt[0] == 'm': # Move.
target = inpt[1]
self.player_pos = self.enter_room(target)
elif inpt[0] == 's': # Shoot.
target = inpt[1]
self.player_pos = self.shoot_room(target)
elif inpt[0] == 'q': # Quit.
self.player_pos = -1

if self.player_pos == -1: # E.g. Deadly threat, quiver empty, etc.


break # If any of the game loosing conditions are True,
# then player_pos will be -1.

print()
print("Game over!")

if __name__ == '__main__':
# Only executed if you start this script as the main script,
# i.e. you enter 'python path/to/wumpus.py' in a terminal.
# Assuming you saved the script in the directory 'path/to'
# and named it 'wumpus.py'.

# TODO: In the original game you can replay a dungeon (same positions of you and the threats)

WG = WumpusGame()
WG.gameloop()

HUNT THE WUMPUS


===============

Entering room 5...


You are in room 5. Tunnels lead to: 2 9 11
Shoot or move (S-M)? M
Where to? 11

Entering room 11...


You smell something terrible nearby.
You are in room 11. Tunnels lead to: 5 12 17
Shoot or move (S-M)? M
Where to? 5

Entering room 5...


You are in room 5. Tunnels lead to: 2 9 11
Shoot or move (S-M)? S
Where to? 9

Shooting an arrow into room 9...


This arrow is lost.
You are in room 5. Tunnels lead to: 2 9 11
Shoot or move (S-M)? M
Where to? 9

Entering room 9...


You feel a cold wind blowing from a nearby cavern.
You smell something terrible nearby.
You are in room 9. Tunnels lead to: 4 5 15
Shoot or move (S-M)? 5
This is not a valid action: pick 'S' to shoot and 'M' to move.
Shoot or move (S-M)? S
Where to? 5

Shooting an arrow into room 5...


This arrow is lost.
Wumpus enters your room and eats you!

Game over!

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 16/17
12/6/23, 7:19 PM AI LAB OUTPUT - Colaboratory
#Create Naïve Bayes Models
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from pandas import DataFrame
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
# The dataset
iris = datasets.load_iris()
X = iris.data
Y = iris.target
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=1/3)
# Training a Gaussian Naive Bayes classifier
model = GaussianNB()
model.fit(X_train, Y_train)
# Predictions
model_predictions = model.predict(X_test)
print("\n",model_predictions)
print("\n",Y_test)
# Accuracy of prediction
accuracyScore = accuracy_score(Y_test, model_predictions)
print("\naccuracyScore is",accuracyScore )
# Creating a confusion matrix
cm=confusion_matrix(Y_test,model_predictions)
print("\nconfusion matrix",cm)
#implementing Naive Baysian algorithm
# Importing library
import [0
math
0 2 2 1 0 2 1 1 1 0 1 1 2 2 2 2 1 1 0 1 2 1 0 1 0 2 1 2 1 0 0 2 0 2 1 0
import 2random
0 0 2 2 1 1 2 1 0 0 0 2]
import csv
[0 0 2 2 1 0 2 1 1 1 0 1 1 1 2 1 2 1 1 0 1 2 1 0 1 0 2 1 2 1 0 0 2 0 1 1 0
2 0 0 2 2 1 1 2 1 0 0 0 2]
# the categorical class names are changed to numberic data
# eg: accuracyScore is 0.94
yes and no encoded to 1 and 0
def encode_class(mydata):
confusion matrix [[16 0 0]
classes = []
[ 0 17 3]
for[ i
0 in
0 range(len(mydata)):
14]]
if mydata[i][-1] not in classes:
classes.append(mydata[i][-1])
for i in range(len(classes)):
for j in range(len(mydata)):
if mydata[j][-1] == classes[i]:
mydata[j][-1] = i
return mydata

# Splitting the data


def splitting(mydata, ratio):

https://colab.research.google.com/drive/1XhBAcuJN6GBniWc1Dm6cuBOpNadBj0KS#scrollTo=o27iI7j56UGE&printMode=true 17/17

You might also like