0% found this document useful (0 votes)
8 views8 pages

Ass1 10

Uploaded by

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

Ass1 10

Uploaded by

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

Name Ojas khawas

SRN No 202100264
Roll no 10
Division / Batch C-1
Assignment no 01
Subject AI LAB
topic Implement non-AI techniques
Problem Statement: Implement Non-AI Techniques for the following problems

1. TIC TAC TOE

CODE:

import random
from time import sleep
computerMove = 'X'
userMove = 'O'
flag = 0
class Magic():
def init (self) -> None:
self.board = ['_','_','_','_','_','_','_','_','_']
self.magicSquare = [2,7,6,9,5,1,4,3,8,]
self.remainingmoves = [2,7,6,9,5,1,4,3,8,]
self.humanMoves = [0]
self.machineMoves = [0]
pass

def showBoard(self):
a=0
for i in range(3):
print(self.board[a], self.board[a+1], self.board[a+2] )
a+=3

def showMagicSquare(self):
a=0
print("\n")
print("Remaining Positions: ")
for i in range(3):
print(self.magicSquare[a], self.magicSquare[a+1], self.magicSquare[a+2] )
a+=3
umove = int(input("\n Enter your Move: "))
return umove

def humanMove(self,vertex):
if vertex not in self.humanMoves or vertex not in self.machineMoves:
self.board[self.magicSquare.index(vertex)] = userMove
self.magicSquare[self.magicSquare.index(vertex)] = '-'
self.humanMoves.append(vertex)
self.remainingmoves.remove(vertex)
else: print("Move not Valid")
return
def machineMove(self,vertex):
if vertex not in self.humanMoves or vertex not in self.machineMoves:
global flag

if len(self.humanMoves) > 2:
l=1
h=len(self.humanMoves)-1
if 15-(self.humanMoves[l]+self.humanMoves[h]) in self.remainingmoves:
vertex = 15-(self.humanMoves[l]+self.humanMoves[h])
flag = 0
if len(self.machineMoves) > 2:
l=1
h=len(self.machineMoves)-1
if 15-(self.machineMoves[l]+self.machineMoves[h]) in
self.remainingmoves:
vertex = 15-(self.machineMoves[l]+self.machineMoves[h])
flag = 1

self.board[self.magicSquare.index(vertex)] = computerMove
self.magicSquare[self.magicSquare.index(vertex)] = '-'
self.machineMoves.append(vertex)
self.remainingmoves.remove(vertex)
return

if name == ' main ':


obj = Magic()
ch = input("Who will play first ( H=Human / M=Machine ): ")

while(1):
if ch in ['H' , 'h']:
userMove = "X"
computerMove = "O"
umove = obj.showMagicSquare()
obj.humanMove(umove)
obj.showBoard()
obj.machineMove(random.choice(obj.remainingmoves))
print("\nMachine turn")
sleep(1)
obj.showBoard()
if flag == 1:
print("Machine Won")
exit(0)

if ch in ['M' , 'm']:
print("\nMachine turn")
obj.machineMove(random.choice(obj.remainingmoves))
obj.showBoard()
if flag == 1:
print("Machine Won")
exit(0)
umove = obj.showMagicSquare()
sleep(1)
obj.humanMove(umove)
obj.showBoard()
OUTPUT:
2. N QUEENS

CODE:
def print_solution(board):
for row in board:
print(" ".join(row))
print("\n")

def is_safe(board, row, col, n):


# Check this row on the left side
for i in range(col):
if board[row][i] == 'Q':
return False

# Check upper diagonal on left side


for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 'Q':
return False

# Check lower diagonal on left side


for i, j in zip(range(row, n, 1), range(col, -1, -1)):
if board[i][j] == 'Q':
return False

return True

def solve_nqueens(board, col, n):


if col == n:
print_solution(board)
return

for i in range(n):
if is_safe(board, i, col, n):
board[i][col] = 'Q'
solve_nqueens(board, col + 1, n)
board[i][col] = '.' # backtrack

def main():
n = int(input("Enter the size of the chessboard (N): "))

# Initialize the chessboard


board = [['.' for _ in range(n)] for _ in range(n)]

solve_nqueens(board, 0, n)
if name == " main ":
main()

OUTPUT:
3. MAGIC SQUARE

CODE:
def is_magic_square(square):
target_sum = sum(square[0])

# Check rows
if any(sum(row) != target_sum for row in square):
return False

# Check columns
if any(sum(col) != target_sum for col in zip(*square)):
return False

# Check main diagonal


if sum(square[i][i] for i in range(len(square))) != target_sum:
return False

# Check secondary diagonal


if sum(square[i][len(square) - i - 1] for i in range(len(square))) != target_sum:
return False

return True

def generate_magic_square(n):
if n % 2 == 0:
raise ValueError("Only odd-sized magic squares are supported")

magic_square = [[0] * n for _ in range(n)]

i, j = 0, n // 2

for num in range(1, n**2 + 1):


magic_square[i][j] = num
i -= 1
j += 1

if num % n == 0:
i += 2
j -= 1
elif i < 0:
i=n-1
elif j == n:
j=0

return magic_square
def print_magic_square(square):
# Calculate the width needed for each cell
cell_width = len(str(len(square) ** 2)) + 2

for row in square:


print(" ".join(f"{num:>{cell_width}}" for num in row))

# Get user input for the size of the magic square


try:
n = int(input("Enter the size of the magic square (odd number): "))
if n % 2 == 0:
raise ValueError("Only odd-sized magic squares are supported")
except ValueError:
print("Invalid input. Please enter an odd number.")
exit()

# Generate and print the magic square


magic_square = generate_magic_square(n)

print("\nGenerated Magic Square:")


print_magic_square(magic_square)

OUTPUT:

You might also like