Artificial Intelligence
Artificial Intelligence
Artificial Intelligence
Fall Semester 2024-25
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 __hash__(self):
return hash((self.M, self.C, self.B))
class Node:
def __init__(self, state, path):
self.state = state
self.path = path
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
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)]
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_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] == ' ']
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 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: