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

Assignment Kirolosmaged 202100238 AI

The document contains source code for two problems - 8-puzzle and Connect Four. The 8-puzzle code includes functions to generate possible moves from a starting board configuration, calculate a heuristic value for each possible move, and search through the problem space until it finds the goal configuration. The Connect Four code defines functions to create a game board, make moves, check for a win condition horizontally, vertically and diagonally, and contains a main function to run a game between two players until there is a winner.

Uploaded by

kirolos maged
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)
24 views8 pages

Assignment Kirolosmaged 202100238 AI

The document contains source code for two problems - 8-puzzle and Connect Four. The 8-puzzle code includes functions to generate possible moves from a starting board configuration, calculate a heuristic value for each possible move, and search through the problem space until it finds the goal configuration. The Connect Four code defines functions to create a game board, make moves, check for a win condition horizontally, vertically and diagonally, and contains a main function to run a game between two players until there is a winner.

Uploaded by

kirolos maged
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: Kirolos Maged Wadie

Id: 202100238

Q1 : source code : 8-puzzle

import numpy as np
import math
import time

# start = np.array([1,2,3,5,6,0,7,8,4]).reshape(3,3) #--->>> Hard array to solve


start = np.array([1,2,3,0,4,6,7,5,8]).reshape(3,3) #--->>> Easy array than above
one to solve

goal = np.array([1,2,3,4,5,6,7,8,0]).reshape(3,3) #--->>> Goal state to achieve

def actions_array(array):
goal = np.array([1,2,3,4,5,6,7,8,0]).reshape(3,3)
possible_actions = []
new_arrays = {}
for i in range(len(array)):
for j in range(len(array)):
if array[i][j] == 0:

#for moving up
if i > 0:
up_array = array.copy()
up_array[i][j], up_array[i-1][j] = up_array[i-1][j],
up_array[i][j]
if not np.array_equal(up_array, start):
new_arrays["up"] = up_array

#for moving down


if i < len(array) - 1:
down_array = array.copy()
down_array[i][j], down_array[i+1][j] = down_array[i+1][j],
down_array[i][j]
if not np.array_equal(down_array, start):
new_arrays["down"] = down_array

#for moving right


if j < len(array) - 1:
right_array = array.copy()
right_array[i][j], right_array[i][j+1] = right_array[i][j+1],
right_array[i][j]
if not np.array_equal(right_array, start):
new_arrays["right"] = right_array

#for moving left


if j > 0 :
left_array = array.copy()
left_array[i][j], left_array[i][j-1] = left_array[i][j-1],
left_array[i][j]
if not np.array_equal(left_array, start):
new_arrays["left"] = left_array

return new_arrays

#H value by calculating number of misplaced tiles


def h_value(array):

s = sum(abs((val-1)%3 - i%3) + abs((val-1)//3 - i//3)


for i, val in enumerate(array.reshape(1,9)[0]) if val)

return s

def main():
run = True
prev_step = []
array = start.copy()
ola = None
count = 0

tic = time.time()
while run:

h={}

if ola is not None:


array = ola

act = actions_array(array)
for keys, values in act.items():
h[keys]=h_value(values)

#find the smallest h value and its key in the dict


new_dic = dict(sorted(h.items(), key=lambda item: item[1]))
res = list(new_dic.items())[0]
r, v = res[0], res[1]

if not prev_step:
prev_step.append(['start_array', array])

else:
for i in range(len(prev_step)):
if np.array_equal(act[r], prev_step[i][1]):
#check if the 2nd value in dic is = to the lowest or not
#we are taking only the top two smallest
new_h = list(new_dic.items())[1]
r, v = new_h[0], new_h[1]

if np.array_equal(act[r], goal):
print("\n")
print('''Problem Solved !. Steps included are : \n''')

prev_step.append([res[0], act[r]])
for i in prev_step:
print(i[0])
print(i[1])
print("\n")
run = False
toc = time.time()
print("Total number of steps: " + str(count))
print("Total amount of time in search: " + str(toc - tic) + "
second(s)")

else:
prev_step.append([r, act[r]])
ola = act[r]
# prev_step[res[0]] = act[res[0]]
count+=1
main()

output:
Q2 : connect four

def create_board():
return [[0 for _ in range(7)] for _ in range(6)]

def print_board(board):
for row in board[::-1]:
print("|", end="")
for cell in row:
print(" {} ".format(cell or " "), end="")
print("|")
print("+---" * 7 + "+")

def is_valid_move(board, col):


return board[5][col] == 0

def make_move(board, col, player):


for row in board:
if row[col] == 0:
row[col] = player
return

def check_win(board, player):


for row in range(6):
for col in range(7):
if (
check_horizontal(board, row, col, player)
or check_vertical(board, row, col, player)
or check_diagonal(board, row, col, player)
):
return True
return False

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


return (
col < 4
and board[row][col] == player
and board[row][col + 1] == player
and board[row][col + 2] == player
and board[row][col + 3] == player
)

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


return (
row < 3
and board[row][col] == player
and board[row + 1][col] == player
and board[row + 2][col] == player
and board[row + 3][col] == player
)

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


return (
check_up_right_diagonal(board, row, col, player)
or check_down_right_diagonal(board, row, col, player)
)

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


return (
row < 3
and col < 4
and board[row][col] == player
and board[row + 1][col + 1] == player
and board[row + 2][col + 2] == player
and board[row + 3][col + 3] == player
)

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


return (
row > 2
and col < 4
and board[row][col] == player
and board[row - 1][col + 1] == player
and board[row - 2][col + 2] == player
and board[row - 3][col + 3] == player
)

def main():
board = create_board()
player_turn = 1
game_over = False

while not game_over:


print_board(board)
col = int(input("Player {}, choose column (0-6): ".format(player_turn)))
- 1

if not is_valid_move(board, col):


print("Invalid move. Please try again.")
continue
make_move(board, col, player_turn)

if check_win(board, player_turn):
print_board(board)
print("Player {} wins!".format(player_turn))
game_over = True
else:
player_turn = 3 - player_turn

if __name__ == "__main__":
main()
output:

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