def move(self, command, ID, action): status = -1 ff.customPrint("Moving: " + str(command)) if (command == 'up'): status, boardUpdated = self.moveUp(ID, action) if (command == 'down'): status, boardUpdated = self.moveDown(ID, action) if (command == 'left'): status, boardUpdated = self.moveLeft(ID, action) if (command == 'right'): status, boardUpdated = self.moveRight(ID, action) if (status == 1): if action: ff.customPrint("Move Success", 0) else: ff.customPrint("Plan success", 0) return 1, boardUpdated elif (status == 3): ff.customPrint("Not a valid move due to already at boarder", 0) return 3, "" else: ff.customPrint( "Move failed for some unknown reason. Status: " + str(status), 0) return 99, ""
def calculateHeuristic2(self, board=""): """ h2 = the sum of the distances of the tiles from their goal positions. """ heuristic2 = 0 row_tracker = 1 column_tracker = 0 if board == "": board = self.board for i in board: if column_tracker != 3: column_tracker = column_tracker + 1 else: column_tracker = 1 if row_tracker != 3: row_tracker = row_tracker + 1 else: row_tracker = 1 #ff.customPrint("Current item "+str(i) + " Current row " +str(row_tracker)+" Current column "+str(column_tracker)) if i != 'b': target_row = int(int(i) / 3) + 1 target_column = int(i) % 3 + 1 #sff.customPrint("Current item "+str(i) + " Current row " +str(target_row)+" Current column "+str(target_column)) heuristic2 = heuristic2 + \ abs(target_row-row_tracker) + \ abs(target_column-column_tracker) #ff.customPrint("Current Heuristic "+str(abs(target_row-row_tracker)+abs(target_column-column_tracker))) ff.customPrint("Current Heuristic is " + str(heuristic2)) return heuristic2
def listAvailable(self): potential = ["", "", "", ""] status1, potential[0] = self.move('left', self.findBlank(), False) status2, potential[1] = self.move('right', self.findBlank(), False) status3, potential[2] = self.move('up', self.findBlank(), False) status4, potential[3] = self.move('down', self.findBlank(), False) ff.customPrint("Available Option are: " + str(potential)) return potential
def ingest(fileLocation): operation = [] try: with open(fileLocation, 'r') as schema: for line in schema: operation.append(line) except: ff.customPrint("File command not found! Please check path", 5) exit(99) finally: ff.customPrint("Commands open successfully.") return operation
def calculateHeuristic1(self, board=""): """ h1 = the number of misplaced tiles. """ heuristic1 = 0 if board == "": board = self.board u = zip(board, "b12345678") for i, j in u: if (not i == j) and (not i == 'b'): heuristic1 = heuristic1 + 1 ff.customPrint("Current Heuristic is " + str(heuristic1)) return heuristic1
def customSwap(self, i, j, input_str=""): """ customSwap """ if input_str == "": input_str = self.board input_str_list = list(input_str) input_str_list[i], input_str_list[j] = input_str_list[ j], input_str_list[i] ff.customPrint( "Swapped: |" + input_str_list[i] + "| and |" + input_str_list[j] + "|", 0) return ''.join(input_str_list)
def randomize(self, count): action_step = "" for i in range(count): success = False action = random.choice(["up", "down", "left", "right"]) while not success: status, forecast = self.move(action, self.findBlank(), False) if status == 1: self.move(action, self.findBlank(), True) success = True action_step = action_step + action + ", " else: action = random.choice(["up", "down", "left", "right"]) ff.customPrint( "Randomize complete. Randomized: " + str(count) + " Steps are:" + action_step, 1)
def astar(boardClass, heruisticsOption, maxNodes): moves = 0 openList = [boardClass] closeList = [] while (len(openList) > 0): puzzleNow = openList.pop(0) moves += 1 #! Node Cap if (moves > maxNodes): ff.customPrint("Exceed allowed maxNodes!", 4) return ("Unsolved", 0) #! Completion Check if puzzleNow.getState() == "b12345678": ff.customPrint("====================Solution====================", 6) if len(closeList) > 0: solution = puzzleNow.reverseTraversal([]) solution.reverse() solutionStep = [] # ? Get solution step for index, item in enumerate(solution): if not index % 2 == 0: solutionStep.append(item) # ? Get solution for index, item in enumerate(solution): if index == 0: ff.customPrint("Starting state", 6) item.printState() elif index % 2 == 0: item.printState() else: ff.customPrint("move " + str(item), 6) ff.customPrint("Solution path:" + str(solutionStep), 2) ff.customPrint("Solution length:" + str(puzzleNow.depth), 2) return "Solved", puzzleNow.depth else: ff.customPrint("Given a Solved board!", 4) return "Solved", 0 #! Search by getting babies! Options = puzzleNow.listAvailable() for option in Options: if option != '': state = eight_puzzle(option) if heruisticsOption == "h1": state.herusticValue = state.calculateHeuristic1() else: state.herusticValue = state.calculateHeuristic2() state.depth = puzzleNow.depth + 1 state.functionValue = state.herusticValue + state.depth state.parent = puzzleNow # ? Check existance openID = ff.find_index(openList, state) closeID = ff.find_index(closeList, state) if openID == -1 and closeID == -1: # * Not searched openList.append(state) elif openID > -1: already_seen = openList[openID] if state.functionValue < already_seen.functionValue: already_seen.functionValue = state.functionValue already_seen.herusticValue = state.herusticValue already_seen.parent = state.parent already_seen.depth = state.depth elif closeID > -1: already_seen = closeList[closeID] if state.functionValue < already_seen.functionValue: state.herusticValue = already_seen.herusticValue state.functionValue = already_seen.functionValue state.depth = already_seen.depth state.parent = already_seen.parent closeList.remove(already_seen) openList.append(state) closeList.append(puzzleNow) openList = sorted(openList, key=lambda p: p.functionValue)
def checkInit(initialized): if not initialized: ff.customPrint("Board still not initialized! Using default!", 4)
def beam(boardClass, k, maxNodes): moves = 0 childrenSorted = [] allChildren = [] best = [boardClass] while True: for child in best: #! Node Cap if (moves > maxNodes): ff.customPrint("Exceed allowed maxNodes!", 4) return ("Unsolved", 0) #! Goal! if child.getState() == "b12345678": ff.customPrint( "====================Solution====================", 6) solution = child.reverseTraversal([]) solution.reverse() move_path = [] # ? Get solution step for index, item in enumerate(solution): if not index % 2 == 0: move_path.append(item) # ? Get solution for index, item in enumerate(solution): if index == 0: ff.customPrint("Starting state", 6) item.printState() elif index % 2 == 0: item.printState() else: ff.customPrint("move " + str(item), 6) ff.customPrint("Solution length:" + str(child.depth + 1), 2) ff.customPrint("Solution path:" + str(move_path), 2) return "Solved", (child.depth + 1) else: currentPuzzle = child options = currentPuzzle.listAvailable() for option in options: if option != '': moves += 1 state = eight_puzzle(option) state.herusticValue = state.calculateHeuristic2() state.parent = currentPuzzle state.depth = currentPuzzle.depth + 1 if ff.find_index(allChildren, state) == -1: allChildren.append(state) childrenSorted.append(state) #! Select the best childrenSorted = sorted(childrenSorted, key=lambda p: p.herusticValue) best = [] if len(childrenSorted) >= k: for i in range(0, k): best.append(childrenSorted.pop(0)) elif len(childrenSorted) < k: for i in range(0, len(childrenSorted)): best.append(childrenSorted.pop(0)) childrenSorted = []
commandfile = sys.argv[1] except: commandfile = ".\command.txt" commandList = ingest(commandfile) #! Class initialization current = eight_puzzle() initialized = False maxNodes = 181440 #! Command Operation for command in commandList: operation = command.split() if operation == []: continue if operation[0] == "setState": ff.customPrint("setState Operation called", 2) if (len(operation[1]) == 9): current.setState(operation[1]) initialized = True elif (len(operation[1]) == 3): try: state = "" + operation[1] + operation[2] + operation[3] except: ff.customPrint( "setState command failed. Provided state missing component!", 5) current.setState(state) initialized = True else: ff.customPrint("setState command provided a state not recognized!", 5)
def setState(self, state): new_state = state.replace(" ", "") self.board = new_state ff.customPrint("State Set successfully!")
def printState(self): try: ff.customPrint("Current Board State:", 1) ff.customPrint("+-----------+", 6) ff.customPrint( "| " + self.board[0] + " | " + self.board[1] + " | " + self.board[2] + " | ", 6) ff.customPrint( "| " + self.board[3] + " | " + self.board[4] + " | " + self.board[5] + " | ", 6) ff.customPrint( "| " + self.board[6] + " | " + self.board[7] + " | " + self.board[8] + " | ", 6) ff.customPrint("+-----------+", 6) except: ff.customPrint("Board State ERROR!", 5) exit(99) finally: ff.customPrint("Board State Print completed")