def addUnit_temp(self, unitID, position, mainClass): self.gameUnits[self.unitUniqueID] = copy.copy(self.unitDict[self.main["units"][unitID]]) self.gameUnits[self.unitUniqueID].uID = self.unitUniqueID self.gameUnits[self.unitUniqueID].modelNode = loader.loadModel(self.gameUnits[self.unitUniqueID].model) self.gameUnits[self.unitUniqueID].modelNode.setName("unit " + str(self.unitUniqueID).zfill(3)) self.gameUnits[self.unitUniqueID].modelNode.reparentTo(render) self.gameUnits[self.unitUniqueID].modelNode.setPos(position) self.gameUnits[self.unitUniqueID].modelNode.setCollideMask(BitMask32.bit(1)) self.gameUnits[self.unitUniqueID].select = OnscreenImage(image="data/models/game/selected.png") self.gameUnits[self.unitUniqueID].select.setScale(float(self.gameUnits[self.unitUniqueID].selectScale)) self.gameUnits[self.unitUniqueID].select.reparentTo(self.gameUnits[self.unitUniqueID].modelNode) self.gameUnits[self.unitUniqueID].select.setZ(float(self.gameUnits[self.unitUniqueID].modelHeight) / 2) self.gameUnits[self.unitUniqueID].select.setTransparency(TransparencyAttrib.MAlpha) self.gameUnits[self.unitUniqueID].select.setBillboardPointEye() self.gameUnits[self.unitUniqueID].select.hide() self.gameUnits[self.unitUniqueID].groundRay = CollisionRay() self.gameUnits[self.unitUniqueID].groundRay.setOrigin(0, 0, 100) self.gameUnits[self.unitUniqueID].groundRay.setDirection(0, 0, -1) self.gameUnits[self.unitUniqueID].groundCol = CollisionNode("unit Ray") self.gameUnits[self.unitUniqueID].groundCol.addSolid(self.gameUnits[self.unitUniqueID].groundRay) self.gameUnits[self.unitUniqueID].groundCol.setTag("units", "ray1") self.gameUnits[self.unitUniqueID].groundCol.setFromCollideMask(BitMask32.bit(0)) # self.gameUnits[self.unitUniqueID].groundCol.setIntoCollideMask(BitMask32.allOff()) self.gameUnits[self.unitUniqueID].groundColNp = self.gameUnits[self.unitUniqueID].modelNode.attachNewNode( self.gameUnits[self.unitUniqueID].groundCol ) self.gameUnits[self.unitUniqueID].groundColNp.setPos(0, 0, 0) self.gameUnits[self.unitUniqueID].groundHandler = CollisionHandlerFloor() self.gameUnits[self.unitUniqueID].groundHandler.setMaxVelocity(100) base.cTrav2.addCollider( self.gameUnits[self.unitUniqueID].groundColNp, self.gameUnits[self.unitUniqueID].groundHandler ) self.gameUnits[self.unitUniqueID].groundHandler.addCollider( self.gameUnits[self.unitUniqueID].groundColNp, self.gameUnits[self.unitUniqueID].modelNode ) self.gameUnits[self.unitUniqueID].AI = AICharacter( self.gameUnits[self.unitUniqueID].fullName, self.gameUnits[self.unitUniqueID].modelNode, self.gameUnits[self.unitUniqueID].mass * 2, self.gameUnits[self.unitUniqueID].startForce * 2, self.gameUnits[self.unitUniqueID].maxForce * 2, ) self.AIWorld.addAiChar(self.gameUnits[self.unitUniqueID].AI) self.gameUnits[self.unitUniqueID].AIBehaviors = self.gameUnits[self.unitUniqueID].AI.getAiBehaviors() if self.gameUnits[self.unitUniqueID].moveType == "ground": self.gameUnits[self.unitUniqueID].aStar = astar.aStar(self.meshes.landMesh, mainClass) elif self.gameUnits[self.unitUniqueID].moveType == "water": self.gameUnits[self.unitUniqueID].aStar = astar.aStar(self.meshes.waterMesh, mainClass) elif self.gameUnits[self.unitUniqueID].moveType == "air": self.gameUnits[self.unitUniqueID].aStar = astar.aStar(self.meshes.airMesh, mainClass) self.unitUniqueID += 1
def path_to_tail(self): snake_tails = [info.get_tail() for info in self.board.get_enemies()] snake_tails.append(self.board.get_our_snake().get_tail()) path_to_tail = aStar(self.board.get_our_snake().get_head(), snake_tails, self.board, SnakePartFilter(snake_tails)) return path_to_tail
def addPath(self, mapp, startRoomIndex, endRoomIndex, bigPath): """ add a path between two rooms we can find out if the path needs to go north, south, east, west TODO: should be able to specify startX/Y, endX/Y or less specifically start wall and end wall """ if len(mapp.roomList) == 0: print "ERROR: No rooms! Cannot create path." return #REM: keep in mind self-connecting rooms beginX, beginY, goalX, goalY = self.getStartLocation( mapp, startRoomIndex, endRoomIndex) """ while not ( self.withinBounds(mapp, beginX, beginY) and self.withinBounds(mapp, goalX, goalY)): beginX, beginY, goalX, goalY = self.getStartLocation(mapp, startRoomIndex, endRoomIndex) """ path = aStar(mapp.cells, beginX, beginY, goalX, goalY) for coord in path: mapp.cells[coord.y][coord.x].ascii = Cell.CORRIDOR_SYMBOL if bigPath: self.bigPath(coord.x, coord.y, mapp) #TODO: include door cells? or src and dst room id's? mapp.pathList.append(path)
def get_a_list_of_pose_to_goal(self, start, goal, tf_listener, dist_limit=None, pathpub=None, wppub=None, skip=1): resolution = self.og.info.resolution width = self.og.info.width height = self.og.info.height offsetX = self.og.info.origin.position.x offsetY = self.og.info.origin.position.y tf_listener.waitForTransform('odom', 'map', rospy.Time(0), rospy.Duration(10.0)) tstart = tf_listener.transformPose(self.og.header.frame_id, fuck_the_time(start)) tgoal = tf_listener.transformPose(self.og.header.frame_id, fuck_the_time(goal)) if dist_limit is not None: tgoal = self.limit_max_dist(tstart, tgoal, dist_limit) if wppub is not None: ttgoal = tf_listener.transformPose('map', fuck_the_time(tgoal)) wppub.publish(ttgoal) start_grid_pos = pose2gridpos(tstart.pose, resolution, offsetX, offsetY) goal_grid_pos = pose2gridpos(tgoal.pose, resolution, offsetX, offsetY) try: path = aStar(self.make_navigable_gridpos(), start_grid_pos, goal_grid_pos, self.astarnodescb) wp = self.getWaypoints(path, tgoal, publisher=pathpub) list_of_pose = [] # magic number. skip a few waypoints in the beginning for stuff in wp: retp = PoseStamped() retp.pose = stuff.pose retp.header = self.og.header list_of_pose.append(retp) return list_of_pose except NoPathFoundException as e: raise e
def is_viable(board,path): us = board.get_our_snake() path_check = aStar(path[1],us.get_tail(),board,SnakePartFilter([us.get_tail()])) if not path_check: return False return path_check
def food_path(food_list, board): snake_heads = [info.get_head() for info in board.get_enemies()] snake_heads.append(board.get_our_snake().get_head()) for food in food_list: food_to_head = aStar(food, snake_heads, board, SnakePartFilter(snake_heads)) if not food_to_head: continue if food_to_head[-1] == board.get_our_snake().get_head(): return food_to_head return None
def construct(width, gameboard, finalboard, answers, algo, gamemode): allstatesselected = 0 #Board with random value print("\n\033[95mGAME BOARD\033[0m") posrow = 0 for row in gameboard: print(str(row)) #Goal board print("\n\033[95mFINAL BOARD\033[0m") for row in finalboard: print(str(row)) #If total inversion % 2 == 1, puzzle is unsolvable if gameboard == finalboard: print("\n\033[91mThis game board is Allready solve !\033[90m") return None checkifsolvable = checkIfSolvable(gameboard, finalboard) if (checkifsolvable == False): print("\n\033[91mThis game board is unsolvable !\033[90m") return None #Call A star, time instentiation if gamemode == 'ia': if answers == "Manhattan": print("\033[91mManhattan distance : \033[0m" + str(manhattan(width, gameboard, finalboard, 1000))) elif answers == "Euclidian": print("\033[91mEuclidian distance : \033[0m" + str(euclidian(width, gameboard, finalboard, 1000))) else: print("\033[91mChebyshev distance : \033[0m" + str(chebyshev(width, gameboard, finalboard, 1000))) print("\n\033[95mprocessing : \033[0m") time1 = time.time() if algo == "Astar": print('\033[91mAlgorythm selected : \033[0m' + str(algo)) seqCount, sequence, allstatesselected = aStar( width, gameboard, finalboard, answers, allstatesselected) else: print('\033[91mAlgorythm selected : \033[0m' + str(algo)) seqCount, sequence, allstatesselected = IDA_star( width, gameboard, finalboard, answers, allstatesselected) #Time finished A star time2 = time.time() #Print time, number of move and all move to accomplite board print("\n\033[91mTime : \033[0m" + str(round(time2 - time1, 3)) + "scd") print("\033[91mNumber of move : \033[0m" + str(seqCount)) print('\033[91mAll move : \033[0m\033[92m' + str(sequence)) return sequence return ''
def home(): raw_input = request.args.get('pntdata').split(',') inputSourceLoc = (float(raw_input[0]),float(raw_input[1])) inputDestLoc = (float(raw_input[2]), float(raw_input[3])) mappedSourceLoc = cj.getKNN(inputSourceLoc) mappedDestLoc = cj.getKNN(inputDestLoc) path = algo.aStar(mappedSourceLoc, mappedDestLoc) finalPath, cost = cj.getResponsePathDict(path, mappedSourceLoc, mappedDestLoc) print("Cost of the path(km): "+str(cost)) return json.dumps(finalPath)
def search(filename, initial_i, initial_j, goal_i, goal_j): ''' <filename> is the file that contains the enviornment. the rest of the arguments are the initial and goal coordinates. Returns a list of tuples. Each tuple is a pair of integers. The first tuple represents the (i, j) coordinate of the start state, and the last tuple represents the goal coordinates. The tuple in between are coordinates in order that represents an optimal path from the start state to the goal. ''' # If path was not already computed, compute retList = remember.getPath((initial_i, initial_j), (goal_i, goal_j)) if not retList: # Define the start and goal node startState = world.State(initial_i, initial_j) goalState = world.State(goal_i, goal_j) startNode = astar.Node(startState, config.heuristicWeight) goalNode = astar.Node(goalState, config.heuristicWeight) startNode.heuristicFucntion = goalNode.heuristicFucntion = config.heuristicFunction( goalNode) # Get environment from file environment = readMaze(filename) # Perform A* search foundGoal = astar.aStar(startNode, goalNode, environment, config.heuristicWeight) # Construct the path retList = [] while foundGoal: fromAction = foundGoal.fromAction i = foundGoal.state.i j = foundGoal.state.j retList.append((i, j)) if fromAction: foundGoal = fromAction.fromNode else: foundGoal = None retList.reverse() # Save the path report.report(filename, retList) remember.sendPath(retList) return retList
def attack(board): return None us = board.get_our_snake() snake_heads = [info.get_head() for info in board.get_enemies()] snake_heads.append(board.get_our_snake().get_head()) # Get Possible moves of enemies head # Select move closest to center # A star to that position enemy_moves = find_enemy_moves(board) attack_point = closest_to_center(board, enemy_moves) path = None # If we can attack, return path to attack point if attack_point: path = aStar(attack_point, [us.get_head()], board, SnakePartFilter([us.get_head()])) return path
def OnLaunch(self, event): if self.mode == "aStar": self.RAZ() if self.parser is not None and self.start is not None and self.end is not None: thread.start_new_thread(aStar, (self.parser, self.start, self.end, self.heuristique, self)) self.Refresh() elif self.mode == "TSP": if self.end: meilleurCout = None cout = 0 it = permutations(self.end) for permut in it: self.RAZ() cout += aStar(self.parser, self.start, permut[0], self.heuristique, self) for x in range(0, len(permut)): for noeud in self.parser.setNoeuds: noeud.parent = None if permut[x] == permut[(len(permut) - 1)]: cout += aStar(self.parser, permut[x], self.start, self.heuristique, self) else: cout += aStar(self.parser, permut[x], permut[x + 1], self.heuristique, self) if meilleurCout is None or meilleurCout < cout: meilleurCout = cout elif self.mode == "Commandes": volTotal = 0 points = list() for livraison in self.livr: volTotal += livraison.volume points.append(Point(livraison.x, livraison.y)) nbMinDrone = int(ceil(float(volTotal) / settings.DRONE_CAPACITY)) ok = False nbRate = 0 while(ok is False): self.setDrones = set() if nbRate >= settings.NB_ESSAI: nbMinDrone += 1 nbRate = 0 ok = True clusters = kmeans(points, nbMinDrone, settings.EPSILON) for i, c in enumerate(clusters): listLivr = list() vol = 0 for p in c.points: for commande in self.livr: if commande.x == p.x and commande.y == p.y: listLivr.append(commande) vol += commande.volume if vol > settings.DRONE_CAPACITY: nbRate += 1 print('trop lourd') ok = False self.setDrones.add(Drone(i, listLivr)) for drone in self.setDrones: distance = 0 for x in range(len(drone.listLivr)): if x != len(drone.listLivr) - 1: distance += abs(drone.listLivr[x].x - drone.listLivr[x + 1].x) + abs(drone.listLivr[x].y - drone.listLivr[x + 1].y) else: distance += abs(drone.listLivr[x].x - drone.listLivr[0].x) + abs(drone.listLivr[x].y - drone.listLivr[0].y) if distance > settings.DRONE_AUTONOMY: print('trop long') nbRate += 1 ok = False self.livr = list() self.Refresh()
def path_to_tail(self, board): return aStar(self.get_head(), self.get_tail(), board)
def main(): print("Initialzing the Megaminx...") megaMinx = list() counter = 1 #Put intial values in megaminx, based off greek alphabet for i in "AΒΓΔΕΖΗΘΙΚΛΜ": temp = side(i) megaMinx.append(temp) print("Side", counter) temp.display() counter = counter + 1 #adds all the relations, based off of map.png megaMinx[0].addrelations( [megaMinx[1], megaMinx[2], megaMinx[3], megaMinx[4], megaMinx[5]]) megaMinx[1].addrelations( [megaMinx[0], megaMinx[5], megaMinx[7], megaMinx[11], megaMinx[2]]) megaMinx[2].addrelations( [megaMinx[3], megaMinx[0], megaMinx[1], megaMinx[11], megaMinx[10]]) megaMinx[3].addrelations( [megaMinx[9], megaMinx[4], megaMinx[0], megaMinx[2], megaMinx[10]]) megaMinx[4].addrelations( [megaMinx[9], megaMinx[8], megaMinx[5], megaMinx[0], megaMinx[3]]) megaMinx[5].addrelations( [megaMinx[4], megaMinx[8], megaMinx[7], megaMinx[1], megaMinx[0]]) megaMinx[6].addrelations( [megaMinx[7], megaMinx[8], megaMinx[9], megaMinx[10], megaMinx[11]]) megaMinx[7].addrelations( [megaMinx[6], megaMinx[11], megaMinx[1], megaMinx[5], megaMinx[8]]) megaMinx[8].addrelations( [megaMinx[9], megaMinx[6], megaMinx[7], megaMinx[5], megaMinx[4]]) megaMinx[9].addrelations( [megaMinx[3], megaMinx[10], megaMinx[6], megaMinx[8], megaMinx[4]]) megaMinx[10].addrelations( [megaMinx[3], megaMinx[2], megaMinx[11], megaMinx[6], megaMinx[9]]) megaMinx[11].addrelations( [megaMinx[10], megaMinx[2], megaMinx[1], megaMinx[7], megaMinx[6]]) # While not quit, display options for code quit = False while (not quit): print("Please select an option:") print("S - Rotate a chosen side") # for solving or custom mixing! print( "R - Randomly mix the megaminx (clockwise moves only!)" ) #randomly rotate (can do outside of 3-20 but tells you to enter 3-20) print("D - display a chosen side") #Displays side and neighbors print("A - solve using a* algorithm") #solve using A* (astar.py) print("Q - to quit") selection = input() # Rotate a given side L or R, print error message if not L or R and if not a valid side if (selection == "s" or selection == "S"): print("Which side to rotate clockwise? (1-12 based on map.png)") selection = input() try: print( "Which direction?\nR for Clockwise and L for CounterClockWise:" ) direction = input() if (direction == "R"): megaMinx[int(selection) - 1].rotateClock() megaMinx[int(selection) - 1].displayRelations() elif (direction == "L"): megaMinx[int(selection) - 1].rotateCounter() megaMinx[int(selection) - 1].displayRelations() else: raise ValueError() except ValueError and IndexError: print("Error! Invalid!") # Quits! elif (selection == "q" or selection == "Q"): quit = True #Displays a side, or the entire megaminx elif (selection == "d" or selection == "D"): print("Which side to display? (1-12 based on map.png) A for all") selection = input() if (selection == "A"): printCube(megaMinx) else: # Display side with relations try: megaMinx[int(selection) - 1].displayRelations() except ValueError and IndexError: print("Error not a valid number!") # Randomly rotate the cube k times, based off of system time elif (selection == "R" or selection == "r"): systemtime = datetime.now() rd.seed(systemtime) numRotates = input("How many k rotations?(3-20)") print("Rotating Clockwise! (this information is not stored!") for i in range(0, int(numRotates)): rotated = rd.randint(0, 11) print("rotated:", rotated ) # Again, not stored but printed to compare to results megaMinx[rotated].rotateClock() print("Mixed with", numRotates, "rotations clockwise!") #Redisplays the megaMinx counter = 1 for i in megaMinx: print("Side", counter) i.display() counter = counter + 1 #calls a* to solve the cube, calculates time to solve elif (selection == "A" or selection == "a"): start = time.time() solver = astar.aStar(megaMinx) print("Time: %s seconds" % (time.time() - start)) print("Do you want to solve?") # Solves it for you so you can run again how nice of it response = input() if (response == "y" or response == "Y"): for i in solver: megaMinx[i].rotateCounter()
def __init__(self, *args, **kwargs): root = Tk.__init__(self, *args, **kwargs) self.frame = ScrolledFrame(root) self.frame.pack() ## ----- Cell Information ----- ## Label(self.frame.interior, text="x").grid(row=0, column=0) self.entry_x = Entry(self.frame.interior, width=10).grid(row=0, column=1) Label(self.frame.interior, text="y").grid(row=1, column=0) self.entry_y = Entry(self.frame.interior, width=10).grid(row=1, column=1) ## ----- Cell Information ----- ## rows = 75 columns = 100 for r in range(0, rows): for c in range(0, columns): if (gameMap[r][c]['value'] == '0'): self.label = Label(self.frame.interior, fg='white', bg='black', width=1, height=1).grid(row=r + 5, column=c + 5) #label = Label(root, fg='white', bg='black',text=gameMap[r][c]['value']) gameMap[r][c]['blocked'] = 1 gameMap[r][c]['hardened'] = 0 gameMap[r][c]['highway'] = 0 elif (gameMap[r][c]['value'] == '1'): self.label = Label(self.frame.interior, bg='white', width=1, height=1).grid(row=r + 5, column=c + 5) #label = Label(root, bg='white',text=gameMap[r][c]['value']) gameMap[r][c]['blocked'] = 0 gameMap[r][c]['hardened'] = 0 gameMap[r][c]['highway'] = 0 elif (gameMap[r][c]['value'] == '2'): self.label = Label(self.frame.interior, bg='grey', width=1, height=1).grid(row=r + 5, column=c + 5) #label = Label(root, bg='grey',text=gameMap[r][c]['value']) gameMap[r][c]['blocked'] = 0 gameMap[r][c]['hardened'] = 1 gameMap[r][c]['highway'] = 0 elif (gameMap[r][c]['value'] == 'a'): self.label = Label(self.frame.interior, bg='blue', width=1, height=1).grid(row=r + 5, column=c + 5) #label = Label(root, bg='blue',text=gameMap[r][c]['value']) gameMap[r][c]['blocked'] = 0 gameMap[r][c]['hardened'] = 0 gameMap[r][c]['highway'] = 1 elif (gameMap[r][c]['value'] == 'b'): self.label = Label(self.frame.interior, bg='dark blue', width=1, height=1).grid(row=r + 5, column=c + 5) #label = Label(root, bg='dark blue',text=gameMap[r][c]['value']) gameMap[r][c]['blocked'] = 0 gameMap[r][c]['hardened'] = 1 gameMap[r][c]['highway'] = 1 ## ----- A* ..... Diagonal Distance ----- ## aStar(gameMap, start_x, start_y, goal_x, goal_y, 0, 1) ## ----- A* ..... Manhattan Distance ----- ## #aStar(gameMap, start_x, start_y, goal_x, goal_y, 1, 1) ## ----- A* ..... Chebychev Distance ----- ## #aStar(gameMap, start_x, start_y, goal_x, goal_y, 2, 1) ## ----- A* ..... Euclidean Distance ----- ## #aStar(gameMap, start_x, start_y, goal_x, goal_y, 3, 1) ## ----- A* ..... Minkowski Distance ----- ## #aStar(gameMap, start_x, start_y, goal_x, goal_y, 4, 1) path_x, path_y = printPath(gameMap, start_x, start_y, goal_x, goal_y) bubbleSort2Arrays(path_x, path_y) i = 0 print("Length:", len(path_x)) for r in range(0, rows): for c in range(0, columns): if (i != 0 and i != len(path_x) - 1): if (i < len(path_x)): if (gameMap[r][c]['xcoord'] == path_x[i] and gameMap[r][c]['ycoord'] == path_y[i]): self.label = Label(self.frame.interior, bg='yellow', width=1, height=1).grid(row=r + 5, column=c + 5) i += 1 else: if (gameMap[r][c]['xcoord'] == path_x[i] and gameMap[r][c]['ycoord'] == path_y[i]): self.label = Label(self.frame.interior, bg='red', width=1, height=1).grid(row=r + 5, column=c + 5) i += 1
def addUnit_temp(self, unitID, position, mainClass): self.gameUnits[self.unitUniqueID] = copy.copy( self.unitDict[self.main['units'][unitID]]) self.gameUnits[self.unitUniqueID].uID = self.unitUniqueID self.gameUnits[self.unitUniqueID].modelNode = loader.loadModel( self.gameUnits[self.unitUniqueID].model) self.gameUnits[self.unitUniqueID].modelNode.setName( 'unit ' + str(self.unitUniqueID).zfill(3)) self.gameUnits[self.unitUniqueID].modelNode.reparentTo(render) self.gameUnits[self.unitUniqueID].modelNode.setPos(position) self.gameUnits[self.unitUniqueID].modelNode.setCollideMask( BitMask32.bit(1)) self.gameUnits[self.unitUniqueID].select = OnscreenImage( image='data/models/game/selected.png') self.gameUnits[self.unitUniqueID].select.setScale( float(self.gameUnits[self.unitUniqueID].selectScale)) self.gameUnits[self.unitUniqueID].select.reparentTo( self.gameUnits[self.unitUniqueID].modelNode) self.gameUnits[self.unitUniqueID].select.setZ( float(self.gameUnits[self.unitUniqueID].modelHeight) / 2) self.gameUnits[self.unitUniqueID].select.setTransparency( TransparencyAttrib.MAlpha) self.gameUnits[self.unitUniqueID].select.setBillboardPointEye() self.gameUnits[self.unitUniqueID].select.hide() self.gameUnits[self.unitUniqueID].groundRay = CollisionRay() self.gameUnits[self.unitUniqueID].groundRay.setOrigin(0, 0, 100) self.gameUnits[self.unitUniqueID].groundRay.setDirection(0, 0, -1) self.gameUnits[self.unitUniqueID].groundCol = CollisionNode('unit Ray') self.gameUnits[self.unitUniqueID].groundCol.addSolid( self.gameUnits[self.unitUniqueID].groundRay) self.gameUnits[self.unitUniqueID].groundCol.setTag('units', 'ray1') self.gameUnits[self.unitUniqueID].groundCol.setFromCollideMask( BitMask32.bit(0)) # self.gameUnits[self.unitUniqueID].groundCol.setIntoCollideMask(BitMask32.allOff()) self.gameUnits[self.unitUniqueID].groundColNp = self.gameUnits[ self.unitUniqueID].modelNode.attachNewNode( self.gameUnits[self.unitUniqueID].groundCol) self.gameUnits[self.unitUniqueID].groundColNp.setPos(0, 0, 0) self.gameUnits[ self.unitUniqueID].groundHandler = CollisionHandlerFloor() self.gameUnits[self.unitUniqueID].groundHandler.setMaxVelocity(100) base.cTrav2.addCollider( self.gameUnits[self.unitUniqueID].groundColNp, self.gameUnits[self.unitUniqueID].groundHandler) self.gameUnits[self.unitUniqueID].groundHandler.addCollider( self.gameUnits[self.unitUniqueID].groundColNp, self.gameUnits[self.unitUniqueID].modelNode) self.gameUnits[self.unitUniqueID].AI = AICharacter( self.gameUnits[self.unitUniqueID].fullName, self.gameUnits[self.unitUniqueID].modelNode, self.gameUnits[self.unitUniqueID].mass * 2, self.gameUnits[self.unitUniqueID].startForce * 2, self.gameUnits[self.unitUniqueID].maxForce * 2) self.AIWorld.addAiChar(self.gameUnits[self.unitUniqueID].AI) self.gameUnits[self.unitUniqueID].AIBehaviors = self.gameUnits[ self.unitUniqueID].AI.getAiBehaviors() if (self.gameUnits[self.unitUniqueID].moveType == 'ground'): self.gameUnits[self.unitUniqueID].aStar = astar.aStar( self.meshes.landMesh, mainClass) elif (self.gameUnits[self.unitUniqueID].moveType == 'water'): self.gameUnits[self.unitUniqueID].aStar = astar.aStar( self.meshes.waterMesh, mainClass) elif (self.gameUnits[self.unitUniqueID].moveType == 'air'): self.gameUnits[self.unitUniqueID].aStar = astar.aStar( self.meshes.airMesh, mainClass) self.unitUniqueID += 1
running_time = time.time() - start_time total_time += running_time M, S, G = open_file("map5j.txt") sx, sy, gx, gy = importantCells(S, G) start_time = time.time() M, i = seqheu(M, sx, sy, gx, gy, 4) running_time = time.time() - start_time total_time += running_time print("------------------------------") print("Sequential A* ") print("Average Time = ", total_time / 40.0) print("------------------------------") ## ----- Sequential A* ----- ## ''' ## ----- A* weight = 1 ----- ## H = 4 total_time = 0 total_length = 0 total_path_cost = 0 M, S, G= open_file("map1a.txt") sx, sy, gx, gy = importantCells(S, G) start_time = time.time() aStar(M, sx, sy, gx, gy, H, 1) running_time = time.time() - start_time total_time += running_time path_length, path_cost = printPath(M, sx, sy, gx, gy) total_length += path_length total_path_cost += path_cost
if __name__ == "__main__": maze = Maze(25, random=True) blackPen = Pen() greenPen = Pen() redPen = Pen() blackPen.color("black") greenPen.color("green") redPen.color("red") redPen.ht() wn = turtle.Screen() wn.bgcolor("gray") wn.setup(800, 800) mazeArray = maze.drawMaze() drawMaze(mazeArray, blackPen, greenPen, maze.exit) turtle.ht() # saveScreen("preMaze.png") # distance, dmaze = d.dijkstra(maze,maze.exit[0],maze.exit[1],verbose=True) a.aStar(maze, maze.entrance, maze.exit, verbose=True) # saveScreen("preMaze_d.png") # solveMaze(maze,dmaze,redPen,maze.exit[0],maze.exit[1],distance) # saveScreen("postMaze.png") while True: pass
def stall(self): us = self.board.get_our_snake() return aStar(us.get_head(), us.get_tail(), self.board, SnakePartFilter([us.get_tail]))
def Waypoints(): #waypointpub = rospy.Publisher('Waypoint_Cells', GridCells) #WaypointCells = GridCells() #WaypointCells.cell_width = 1 #WaypointCells.cell_height = 1 #WaypointCells.cells = [Point()] #WaypointCells.header.frame_id = 'map' way = [] i = 0 pointList = aStar((3, 3), (7, 5), mapGrid) navPath = Path() pathPose = PoseStamped() for item in pointList: current_x = item[0] current_y = item[1] next_point = pointList[i+1] next_x = next_point[0] next_y = next_point[1] if(next_x == current_x+1 and next_y == current_y): if(i == 0 or i == 1): i = 1 else: i = 1 way.append((current_x, current_y, 0)) pathPose.pose.position.x = current_x pathPose.pose.position.y = current_y pathPose.pose.position.z = 0 yaw = math.radians(0) roll = 0 pitch = 0 quaternion = tf.transformations.quaternion_from_euler(roll, pitch, yaw) pathPose.pose.orientation.x = quaternion[0] pathPose.pose.orientation.y = quaternion[1] pathPose.pose.orientation.z = quaternion[2] pathPose.pose.orientation.w = quaternion[3] elif(next_x == current_x and next_y == current_y+1): if(i == 0 or i == 2): i = 2 else: i = 2 way.append((current_x, current_y, 90)) pathPose.pose.position.x = current_x pathPose.pose.position.y = current_y pathPose.pose.position.z = 0 yaw = math.radians(0) roll = 0 pitch = 0 quaternion = tf.transformations.quaternion_from_euler(roll, pitch, yaw) pathPose.pose.orientation.x = quaternion[0] pathPose.pose.orientation.y = quaternion[1] pathPose.pose.orientation.z = quaternion[2] pathPose.pose.orientation.w = quaternion[3] if(next_x == current_x-1 and next_y == current_y): if(i == 0 or i == 3): i = 3 else: i = 3 way.append((current_x, current_y, 180)) pathPose.pose.position.x = current_x pathPose.pose.position.y = current_y pathPose.pose.position.z = 0 yaw = math.radians(0) roll = 0 pitch = 0 quaternion = tf.transformations.quaternion_from_euler(roll, pitch, yaw) pathPose.pose.orientation.x = quaternion[0] pathPose.pose.orientation.y = quaternion[1] pathPose.pose.orientation.z = quaternion[2] pathPose.pose.orientation.w = quaternion[3] elif(next_x == current_x and next_y == current_y-1): if(i == 0 or i == 4): i = 4 else: i = 4 way.append((current_x, current_y, 270)) pathPose.pose.position.x = current_x pathPose.pose.position.y = current_y pathPose.pose.position.z = 0 yaw = math.radians(0) roll = 0 pitch = 0 quaternion = tf.transformations.quaternion_from_euler(roll, pitch, yaw) pathPose.pose.orientation.x = quaternion[0] pathPose.pose.orientation.y = quaternion[1] pathPose.pose.orientation.z = quaternion[2] pathPose.pose.orientation.w = quaternion[3] navPath.poses.append(pathPose) print way dispathpub.publish(navPath)
if __name__ == '__main__': M = buildUp(size=64, p=0.35) t1 = biDirectionalAStar(m=M, distFunction=euclideanDist, LIFO=True, plotClosed=True) t3 = biDirectionalAStar(m=M, distFunction=manhattanDist, LIFO=True) t5 = biDirectionalAStar(m=M, distFunction=chebyshevDist, LIFO=True) t7 = solution.BFS(M, BDBFS=True, quickGoal=True, randomWalk=True, checkFringe=True) t9 = astar.aStar(m=M, distFunction=chebyshevDist, LIFO=True) print(str(t1[0]) + ", " + str(t1[2])) print(str(t3[0]) + ", " + str(t3[2])) print(str(t5[0]) + ", " + str(t5[2])) l = len(t7[1]) print(str(t7[0]) + ", " + str(l)) print(str(t9[0]) + ", " + str(t9[2])) M.path = t3[1] imgastar = M.visualize() M.path = t7[1] # imgbfs = M.visualize() # imgastar.save('/home/shengjie/astar.png', 'PNG') # imgbfs.save('/home/shengjie/bfs.png', 'PNG')
finished = True break if event.type == pygame.KEYDOWN: pos = pygame.mouse.get_pos() if event.key == pygame.K_a: if start == None: start = selectStart(pos) start.value = 1 start.display(Color.BLUE) if event.key == pygame.K_s: finish = selectEnd(pos) finish.value = 3 finish.display(Color.PURPLE) if event.key == pygame.K_q: start, end = None, None grid.reset() grid.display() if pygame.mouse.get_pressed()[0]: try: pos = pygame.mouse.get_pos() placeWall(pos, start, finish) except AttributeError: pass elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: try: aStar(gridBase, start, finish) except: pass