0% found this document useful (0 votes)
6 views7 pages

Artificial Intelligence

codes

Uploaded by

Hardik Singla
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)
6 views7 pages

Artificial Intelligence

codes

Uploaded by

Hardik Singla
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/ 7

DIGITAL ASSIGNMENT - 1

Artificial Intelligence
Fall Semester 2024-25

Submitted to : Dr. MOHANA CM

Submitted by:
Hardik Singla
22BBS0203
Implementation of Missionaries and Cannibals
Problem
Code :
class State:
def __init__(self, M, C, B):
self.M = M
self.C = C
self.B = B

def __eq__(self, other):


return self.M == other.M and self.C == other.C and self.B == other.B

def __hash__(self):
return hash((self.M, self.C, self.B))

class Node:
def __init__(self, state, path):
self.state = state
self.path = path

def is_valid_state(M, C):


if M < 0 or C < 0 or M > 3 or C > 3:
return False
if M > 0 and M < C:
return False
if M < 3 and (3 - M) < (3 - C):
return False
return True

def is_goal_state(M, C, B):


return M == 0 and C == 0 and B == 0

def contains_state(arr, s):


return any(state == s for state in arr)

def print_solution(path):
for state in path:
print(f"Missionaries: {state.M}, Cannibals: {state.C}, Boat: {'Left'
if state.B == 1 else 'Right'}")

def dfs():
initial_state = State(3, 3, 1)
stack = [Node(initial_state, [initial_state])]
visited = set()
while stack:
current_node = stack.pop()
current_state = current_node.state

if is_goal_state(current_state.M, current_state.C, current_state.B):


print_solution(current_node.path)
return

visited.add(current_state)

successors = []
if current_state.B == 1:
moves = [(-1, 0), (-2, 0), (0, -1), (0, -2), (-1, -1)]
else:
moves = [(1, 0), (2, 0), (0, 1), (0, 2), (1, 1)]

for move in moves:


new_state = State(current_state.M + move[0], current_state.C +
move[1], 1 - current_state.B)
if is_valid_state(new_state.M, new_state.C) and new_state not in
visited:
new_path = current_node.path + [new_state]
stack.append(Node(new_state, new_path))

dfs()

Sample i/o:
Implementation of TikTacToe
Code:
import math

def print_board(board):
print("---------")
for row in board:
print("| " + " | ".join(row) + " |")
print("---------")

def check_win(board, player):


win_conditions = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0], board[1][0], board[2][0]],
[board[0][1], board[1][1], board[2][1]],
[board[0][2], board[1][2], board[2][2]],
[board[0][0], board[1][1], board[2][2]],
[board[2][0], board[1][1], board[0][2]],
]
return [player, player, player] in win_conditions

def check_full(board):
return all(cell != ' ' for row in board for cell in row)

def get_available_moves(board):
return [(r, c) for r in range(3) for c in range(3) if board[r][c] == ' ']

def make_move(board, row, col, player):


board[row][col] = player

def minimax(board, depth, is_maximizing):


if check_win(board, 'O'):
return 1
if check_win(board, 'X'):
return -1
if check_full(board):
return 0

if is_maximizing:
best_score = -math.inf
for row, col in get_available_moves(board):
board[row][col] = 'O'
score = minimax(board, depth + 1, False)
board[row][col] = ' '
best_score = max(score, best_score)
return best_score
else:
best_score = math.inf
for row, col in get_available_moves(board):
board[row][col] = 'X'
score = minimax(board, depth + 1, True)
board[row][col] = ' '
best_score = min(score, best_score)
return best_score

def system_move(board):
best_score = -math.inf
best_move = None
for row, col in get_available_moves(board):
board[row][col] = 'O'
score = minimax(board, 0, False)
board[row][col] = ' '
if score > best_score:
best_score = score
best_move = (row, col)
return best_move

def play_game():
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'

while True:
print_board(board)

if current_player == 'X':
print("Your turn! Enter your move (row and column) as 'row col':")
try:
row, col = map(int, input().split())
except ValueError:
print("Invalid input. Please enter numbers separated by
space.")
continue

if row < 0 or row > 2 or col < 0 or col > 2 or board[row][col] !=


' ':
print("Invalid move. Try again.")
continue

make_move(board, row, col, current_player)


else:
print("System's turn:")
row, col = system_move(board)
make_move(board, row, col, current_player)

if check_win(board, current_player):
print_board(board)
if current_player == 'X':
print("Congratulations, you win!")
else:
print("System wins!")
break

if check_full(board):
print_board(board)
print("It's a tie!")
break

# Switch player
current_player = 'O' if current_player == 'X' else 'X'

if __name__ == "__main__":
play_game()
Sample i/o:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy