Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from string import printable
- start_state = [
- ['1', '2', '3'],
- ['7', '8', '4'],
- ['_', '6', '5']
- ]
- goal_state = [
- ['1', '2', '3'],
- ['4', '5', '6'],
- ['7', '8', '_']
- ]
- """ the total manhatten distance for the starting state is
- 1+1+2+2+2 = 8
- currint blank posistion = (2,0)
- ['1', '2', '3']
- ['_', '8', '4'] = 1+2+2+2 = 7
- ['7', '6', '5']
- ['1', '2', '3']
- ['7', '8', '4'] = 1+1+2+3+2 = 9
- ['6', '_', '5']
- there for the first child state is the best
- """
- def print_board(given_state):
- for i in range(3):
- for j in range(3):
- print(f"|{given_state[i][j]}", end='')
- print('|')
- def calculate_manhattan_distance(node, given_state, goal_state):
- # calculate h score / manhattan distance
- #print(f"{given_state = }")
- distance = 0
- start_position = 0
- final_position = 0
- for i in range(3):
- for j in range(3):
- if node == given_state[i][j]:
- start_position = (i, j)
- #print(start_position)
- if node == goal_state[i][j]:
- final_position = (i,j)
- #print(f"{final_position = }")
- #print(f"{final_position[0] = }")
- distance =+ abs(final_position[0] - start_position[0]) + abs(final_position[1] - start_position[1])
- print(f"{distance = }")
- return distance
- def calculate_h_score(given_state):
- total = 0
- for i in range(3):
- for j in range(3):
- if given_state[i][j] != '_': # dont calculate the empty space
- total += calculate_manhattan_distance(given_state[i][j], given_state, goal_state)
- #print(f"{total = }")
- heuristic = (total, given_state)
- print(f"{heuristic = }")
- return heuristic
- """so far we have calculated the heuristic for a given state
- next we need to expand the node to see the child nodes
- we need to figure out where the blank node is and in which directions it can move, excluding any previous states.
- """
- def find_space(given_state):
- #figure out where the blank is
- for i in range(3):
- for j in range(3):
- if given_state[i][j] == '_':
- blank_position = (i, j)
- #print(blank_position)
- return blank_position
- def possible_moves(blank_position):
- viable_moves = []
- # is up viable?
- if blank_position[0] - 1 >= 0:
- viable_moves.append('up')
- # down?
- if blank_position[0] + 1 <= 2:
- viable_moves.append('down')
- # left?
- if blank_position[1] - 1 >= 0:
- viable_moves.append('left')
- #right?
- if blank_position[1] + 1 <= 2:
- viable_moves.append('right')
- return viable_moves
- # def possible_moves(blank_position, given_state):
- # #trying out dictionary
- # viable_moves = {}
- # # is up viable?
- # if blank_position[0] - 1 >= 0:
- # viable_moves['up'] = calculate_h_score(given_state)
- # # down?
- # if blank_position[0] + 1 <= 2:
- # viable_moves['down'] = calculate_h_score(given_state)
- # # left?
- # if blank_position[1] - 1 >= 0:
- # viable_moves['left'] = calculate_h_score(given_state)
- # #right?
- # if blank_position[1] + 1 <= 2:
- # viable_moves['right'] = calculate_h_score(given_state)
- # return viable_moves
- """now we have the possilbe moves we need to move and move and generate a new grid and give each new grid a h score.
- the h score so far is 0 but on the next level of grids it will increase by our g score.
- our g score increases each level by one, we add this to the h score of the new grids and pick the one with lowest score to explore next
- """
- def generate_next_board(direction, given_state, space):
- target = [9,9]
- temp = []
- #print(f"{direction, given_state, space = }")
- new_state = [sub.copy() for sub in given_state]
- if direction == 'up':
- print("Moved space up")
- #print(space[0] -1)
- target[0] = space[0] -1
- target[1] = space[1]
- #print(space)
- #print(target)
- temp = given_state[target[0]][target[1]]
- #print(f"up temp = {temp}")
- #print(f"{temp = }")
- new_state[target[0]][target[1]] = given_state[space[0]][space[1]]
- new_state[space[0]][space[1]] = temp
- if direction == 'down':
- print("Moved space down")
- target[0] = space[0] +1
- target[1] = space[1]
- #print(space)
- #print(target)
- temp = given_state[target[0]][target[1]]
- #print(f"down temp = {temp}")
- new_state[target[0]][target[1]] = given_state[space[0]][space[1]]
- new_state[space[0]][space[1]] = temp
- if direction == 'left':
- print("Moved space left")
- target[0] = space[0]
- target[1] = space[1] -1
- print(space)
- print(target)
- temp = given_state[target[0]][target[1]]
- #print(f"left temp = {temp}")
- new_state[target[0]][target[1]] = given_state[space[0]][space[1]]
- new_state[space[0]][space[1]] = temp
- if direction == 'right':
- print("Moved space right")
- target[0] = space[0]
- target[1] = space[1] +1
- print(space)
- print(target)
- temp = given_state[target[0]][target[1]]
- #print(f"right temp = {temp}")
- new_state[target[0]][target[1]] = given_state[space[0]][space[1]]
- new_state[space[0]][space[1]] = temp
- print_board(new_state)
- return new_state
- ## test cells ##
- # print_board(start_state)
- # space = find_space(start_state)
- # print(f"{possible_moves(space) = }")
- # moves = possible_moves(space)
- # for key, value in moves.items():
- # moves[key] = calculate_h_score(start_state)
- # print(f"{moves[key] = }")
- # print(moves)
- # child_state = generate_next_board('up', start_state, space)
- # print_board(child_state)
- #h_score = calculate_h_score(start_state)
- #print(f"{h_score = }")
- """function A*(start, goal)
- closedSet := the empty set // The set of nodes already evaluated.
- openSet := set containing the initial node // The set of tentative nodes to be evaluated, initially containing the start node
- cameFrom := the empty map // The map of navigated nodes.
- gScore[start] := 0 // Cost from start along best known path.
- // Estimated total cost from start to goal through y.
- fScore[start] := gScore[start] + heuristic_cost_estimate(start, goal)
- while openSet is not empty
- current := the node in openSet having the lowest fScore[] value
- if current = goal
- return reconstruct_path(cameFrom, goal)
- openSet.Remove(current)
- closedSet.Add(current)
- for each neighbor of current
- if neighbor in closedSet
- continue // Ignore the neighbor which is already evaluated.
- tentative_gScore := gScore[current] + dist_between(current, neighbor) // length of this path.
- if neighbor not in openSet // Discover a new node
- openSet.Add(neighbor)
- else if tentative_gScore >= gScore[neighbor]
- continue // This is not a better path.
- // This path is the best until now. Record it!
- cameFrom[neighbor] := current
- gScore[neighbor] := tentative_gScore
- fScore[neighbor] := gScore[neighbor] + heuristic_cost_estimate(neighbor, goal)
- return failure
- """
- def convert_to_tupple(lis):
- tup = []
- for i in range(3):
- inner_tupple = tuple(lis[i])
- tup = tuple(inner_tupple)
- print(tup)
- return tup
- """Put node_start in the OPEN list with f(node_start) = h(node_start) (initialization)
- while the OPEN list is not empty {
- Take from the open list the node node_current with the lowest
- f(node_current)
- =
- g(node_current) + h(node_current)
- if node_current is node_goal we have found the solution; break
- Generate each state node_successor that come after node_current
- for each node_successor of node_current {
- }
- }
- Set successor_current_cost = g(node_current) + w (node_current, node_successor) if node_successor is in the OPEN list {
- if g(node_successor) successor_current_cost continue (to line 20)
- } else if node_successor is in the CLOSED list {
- if g(node_successor)
- successor_current_cost continue (to line 20)
- Move node_successor from the CLOSED list to the OPEN list } else {
- Add node_successor to the OPEN list
- Set h(node_successor) to be the heuristic distance to node_goal
- Set g(node_successor) = successor_current_cost
- Set the parent of node_successor to node_current
- Add node_current to the CLOSED list
- if(node_current != node_goal) exit with error (the OPEN list is empty)
- """
- open_list = []
- initial_state = (0, start_state) #give the start state a h score of 0
- open_list.append(initial_state)
- #print(f"{open_list = }")
- while open_list:
- #find smallest h_score
- open_list.sort()
- current_state = open_list.pop(0)
- print_board(current_state[1])
- #check if we found thw goal
- if current_state == goal_state:
- print("found it!")
- #find next moves
- space = find_space(current_state[1])
- moves = possible_moves(space)
- print(moves)
- #expand moves
- moves_expanded = []
- #next_state_right = generate_next_board('right', current_state, space)
- #next_state_down = generate_next_board('down', current_state, space)
- #next_state_up = generate_next_board('up', current_state, space)
- for i in range(len(moves)):
- print(f"{moves[i] = }")
- moves_expanded.append(generate_next_board(moves[i], current_state[1], space))
- print(f"{moves_expanded[i] = }")
- print(f"{moves_expanded = }")
- #calculate h_score for each move
- calculated = []
- for i in range(len(moves_expanded)):
- calculated.append(calculate_h_score(moves_expanded[i]))
- print(calculated)
- #print("start_state")
- #print_board(start_state)
Advertisement
Add Comment
Please, Sign In to add comment