def initObstacles(num_l_to_r, num_r_to_l): global moving_obstacles moving_obstacles = True for i in range(num_l_to_r): obs = obstacle.Obstacle(random.randint(CONST.OBS_LN_LtoR_MIN, CONST.OBS_LN_LtoR_MAX), "l_to_r", art.cars['gray'], car.rect.centerx, car.rect.centery, other_obs=obstacles) all_sprites.addstate(obs) obstacles.add(obs) for i in range(num_r_to_l): obs = obstacle.Obstacle(random.randint(CONST.OBS_LN_RtoL_MIN, CONST.OBS_LN_RtoL_MAX), "r_to_l", art.cars['gray'], car.rect.centerx, car.rect.centery, other_obs=obstacles) all_sprites.add(obs) obstacles.add(obs)
def loader(self, path): """ Takes in a csv file and stores the necessary instances for the simulation object. The file path referenced should point to a file of a particular format - an example of which can be found in utils.py txt_generator(). The exact order of the file is unimportant - the three if statements will extract the needed information. :param path: File path directory to a .csv file holding the simulation information :return: """ # Load and store csv file info = defaultdict(list) print path with open(path) as info_read: for line in info_read: if not self.is_comment(line): data = line.strip().split(',') key, val = data[0], data[1:] info[key].append(val) # print(info) # Extract grid dimensions self.dim_w = int(info['grid'][0][0]) self.dim_h = int(info['grid'][0][1]) # Add items and agents to the environment i = 0 j = 0 l = 0 for k, v in info.items(): # print k # print v if 'item' in k: self.items.append(item.item(v[0][0], v[0][1], v[0][2], i)) i += 1 elif 'agent' in k: #import ipdb; ipdb.set_trace() agnt = agent.Agent(v[0][0], v[0][1], v[0][2], v[0][3], j) agnt.set_parameters(self,v[0][4], v[0][5], v[0][6]) self.agents.append(agnt) j += 1 elif 'main' in k: # x-coord, y-coord, direction, type, index self.main_agent = agent.Agent(v[0][0], v[0][1], v[0][2], 'm', -1) self.main_agent.level = v[0][2] elif 'obstacle' in k: self.obstacles.append(obstacle.Obstacle(v[0][0], v[0][1])) l += 1 # Run Checks assert len(self.items) == i, 'Incorrect Item Loading' assert len(self.agents) == j, 'Incorrect Ancillary Agent Loading' assert len(self.obstacles) == l, 'Incorrect Obstacle Loading' # Print Simulation Description print('Grid Size: {} \n{} Items Loaded\n{} Agents Loaded\n{} Obstacles Loaded'.format(self.dim_w, len(self.items), len(self.agents), len(self.obstacles))) # Update the map self.update_the_map()
def initialize_obstacles(): obstacles = [] for _ in range(NUM_OBSTACLES): obstacles.append(obstacle.Obstacle(random.randint(SCREEN_WIDTH * 0.2, SCREEN_WIDTH * 0.8) // UNIT_SIZE * UNIT_SIZE, random.randint(SCREEN_HEIGHT * 0.2, SCREEN_HEIGHT * 0.8) // UNIT_SIZE * UNIT_SIZE ) ) return obstacles
def initObstacles(num_l_to_r, num_r_to_l): for i in range(num_l_to_r): obs = obstacle.Obstacle(random.randint(0, 2), "l_to_r", art.cars['gray'], car.rect.centerx, car.rect.centery, other_obs=obstacles) all_sprites.add(obs) obstacles.add(obs) for i in range(num_r_to_l): obs = obstacle.Obstacle(random.randint(3, 5), "r_to_l", art.cars['gray'], car.rect.centerx, car.rect.centery, obstacles) all_sprites.add(obs) obstacles.add(obs)
def parse_infile(infile): """ Parses a JSON file into a level :param infile: filename to read from :return: Tuple indicating whether root node and goal node have been set. """ import os root_set = False goal_set = False if not os.path.exists(infile): print("Error: Infile {} does not exist.".format(infile), file=sys.stderr) exit(1) if not os.path.splitext(infile)[-1] == ".json": print("Error: Infile {} does not have correct extension.".format(infile), file=sys.stderr) exit(1) with open(infile) as json_file: json_obj = json.load(json_file) if 'obstacles' in json_obj: obstacles = json_obj["obstacles"] for obs in obstacles: this_obstacle = obstacles[obs] x = this_obstacle["x"] * shared.x_range y = (this_obstacle["y"] * shared.y_range) + shared.y_domain[0] width = this_obstacle["width"] * shared.x_range height = this_obstacle["height"] * shared.y_range shared.obstacles.append(obstacle.Obstacle(x, y, width, height)) if 'nodes' in json_obj: nodes = json_obj["nodes"] for my_node in nodes: this_node = nodes[my_node] if this_node["type"] == "root": x = this_node["x"] * shared.x_range y = (this_node["y"] * shared.y_range) + shared.y_domain[0] for obs in shared.obstacles: if obs.collides_with(x, y): print("Error: Specified root node collides with an obstacle.".format(infile), file=sys.stderr) exit(1) shared.nodes.append(node.Node(x, y, None, "root")) root_set = True if this_node["type"] == "goal": x = this_node["x"] * shared.x_range y = (this_node["y"] * shared.y_range) + shared.y_domain[0] for obs in shared.obstacles: if obs.collides_with(x, y): print("Error: Specified root node collides with an obstacle.".format(infile), file=sys.stderr) exit(1) shared.goal = node.Node(x, y, None, "goal") goal_set = True return root_set, goal_set
def __init_obstacle_on_board(self, unique_id, position, obstacle_type): board = json.loads(self.board) new_obstacle = obstacle.Obstacle(unique_id, obstacle_type, position) # Board is not a standard type, so we must make JSON recognize it d = { '__class__': new_obstacle.__class__.__name__, '__module__': new_obstacle.__module__, } d.update(new_obstacle.__dict__) board["obstacles"].append(d) self.board = json.dumps(board)
def Cluster(self, outblobs, object_thresh=0.5): category_pt_data = outblobs['category_score'][0, 0] #ndim=2 instance_pt_x = outblobs['instance_pt'][0, 0] instance_pt_y = outblobs['instance_pt'][0, 1] rows = self.vldpc.rows cols = self.vldpc.cols lrange = self.vldpc.lrange self.node = nd.Node(rows, cols) self.node.point_num = self.GetPointsNum() self.node.is_object = np.all( [self.node.point_num > 0, category_pt_data >= object_thresh], axis=0) gird_col, grid_row = np.meshgrid(np.arange(cols), np.arange(rows)) scale = 0.5 * rows / lrange center_row = np.round(grid_row + instance_pt_x * scale).astype(np.int) center_col = np.round(gird_col + instance_pt_y * scale).astype(np.int) center_row = np.where(center_row >= 0, center_row, 0) center_row = np.where(center_row < rows, center_row, rows - 1) center_col = np.where(center_col >= 0, center_col, 0) center_col = np.where(center_col < cols, center_col, cols - 1) self.node.center_node[0] = center_row self.node.center_node[1] = center_col for row in range(rows): for col in range(cols): if self.node.is_object[row,col] and \ self.node.traversed[row,col]==0: ut.Traverse(self.node, row, col) for row in range(rows): for col in range(cols): if (not self.node.is_center[row, col]): continue for row2 in [row - 1, row, row + 1]: for col2 in [col - 1, col, col + 1]: if (row2==row or col2==col) and \ (row2>=0 and row2<rows and col2>=0 and col2<cols): if self.node.is_center[row2, col2]: ut.SetUnion(self.node, row, col, row2, col2) for row in range(rows): for col in range(cols): if (not self.node.is_object[row, col]): continue r_row, r_col = ut.SetFind(self.node, row, col) if self.node.obstacle_id[r_row, r_col] < 0: self.node.obstacle_id[r_row, r_col] = self.count_obstacles self.count_obstacles += 1 self.obstacles.append(obs.Obstacle()) grid = row * cols + col self.id_img[grid] = self.node.obstacle_id[r_row, r_col] self.obstacles[self.node.obstacle_id[r_row, r_col]].grids.append(grid)
def update(self, delta_time): self.curr_frame += 1 if self.curr_state == GAME_RUNNING: if (not self.obst_list) or (self.obst_list[-1].center_x <= (self.width - gc.OBSTACLE_GEN_OFF)): obstacle1 = ob.Obstacle(gc.GAME_WIDTH, 0) obstacle2 = ob.Obstacle(gc.GAME_WIDTH, (obstacle1.top+gc.GAP_SIZE)) self.obst_list.append(obstacle1) self.obst_list.append(obstacle2) self.obst_list.update() for p in self.pop_list: collision = arcade.check_for_collision_with_list(p, self.obst_list) if (not p.in_bound()) or any(collision): if p.score > (self.best_score * 0.7): p.net.save_data(self.training_data) if p.score * 0.96 > self.best_score: self.best_score = p.score p.net.save("bestNet.txt") self.save_score() p.net.save("currNet.txt") p.kill() if self.obst_list[0].center_x - p.center_x > 0: p.closest_obst = self.obst_list[0] else: p.closest_obst = self.obst_list[2] p.update() if len(self.pop_list) == 0: self.curr_state = GAME_OVER arcade.finish_render() elif self.curr_state == GAME_OVER: self.setup()
def on_mouse_press(x, y, button, modifiers): """ Mousedown event creates new obstacles, and deletes existing :param x: x position of press :param y: y position :param button: Left or Right LEft creates right deletes :param modifiers: :return: """ if button == mouse.LEFT: shared.obstacles.append(obstacle.Obstacle(x, y, 0, 0)) if button == mouse.RIGHT: for obs in shared.obstacles: if obs.collides_with(x, y): obs.delete()
def add_static_obstacles(self, density, zmin, zmax, objects): """Density: average number of obstacles per 100 m""" n = density * self.zfinish / 100. done = set([]) i = 0 while i < n: x = random.randint(0, self.nx - 1) y = random.randint(0, self.ny - 1) z = random.randint(zmin, zmax) if (x, y, z) not in done: done.add((x, y, z)) obj = random.choice(objects).get_copy() damage = 1 obstacle.Obstacle(damage, x, y, z, obj) i += 1
def setGame(self): """ Resets the game's parameter Args: self (Controller): a Controller object Returns: (None): None """ self.player.lives = 3 self.player.x, self.player.y = self.width / 2, self.height / 2 self.player.setDirection("DOWN") self.player.animObjs[self.player.direction].pause() self.player.running = False self.obstacles.empty() for i in range(10): self.obstacles.add(obstacle.Obstacle(self.windowSurface)) self.state = "START"
def loadProblem(self, filename): """ Loads a problem from a text file @param filename the path of the file to load @throws IOError if the text file doesn't exist or meet specifications """ self.problemLoaded = False self.solutionLoaded = False inputData = open(filename, 'r').read().split('\n') i = 0 try: self.asvCount = inputData[i] i += 1 self.initialState = ASVconfig.ASVConfig(inputData[i]) i += 1 self.goalState = ASVconfig.ASVConfig(inputData[i]) i += 1 numObstacles = inputData[i] i += 1 self.obstacles = [None] * numObstacles for _ in range(numObstacles): self.obstacles[_] = obstacle.Obstacle().construct(inputData[i]) #TODO: Swap the contructors i += 1 self.problemLoaded = True except IndexError: print("Index out of range in input " + i ) raise IOError("Index out of range in input " + i) except IOError: print("Input file not found") raise IOError("Input file not found")
def on_mouse_press(x, y, button, modifiers): """ Mousedown event creates new obstacles, and deletes existing :param x: x position of press :param y: y position :param button: Left or Right LEft creates right deletes :param modifiers: :return: """ if button == mouse.LEFT: shared.obstacles.append(obstacle.Obstacle(x, y, shared.RADIUS)) for this_node in shared.nodes: if shared.obstacles[-1].collides_with(this_node.x, this_node.y): shared.obstacles[-1].delete() if shared.obstacles[-1].collides_with(shared.goal.x, shared.goal.y): shared.obstacles[-1].delete() else: shared.obstacles[-1].add_to_default_batch() if button == mouse.RIGHT: for obs in shared.obstacles: if obs.collides_with(x, y): obs.delete()
import obstacle # Set the working directory (where we expect to find files) to the same # directory this .py file is in. You can leave this out of your own # code, but it is needed to easily run the examples using "python -m" # as mentioned at the top of this program. file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) arcade.open_window(1200, 500, "Drawing Example") arcade.set_background_color(arcade.color.WHITE) # Start the render process. This must be done before any drawing commands. arcade.start_render() texture = arcade.load_texture("res/dirt.png") scale = .25 for i in range(50, 1200, 100): arcade.draw_texture_rectangle(i, 50, scale * texture.width, scale * texture.height, texture, 0) obstacle = obstacle.Obstacle(0) # Finish the render. # Nothing will be drawn without this. # Must happen after all draw commands arcade.finish_render() # Keep the window up until someone closes it. arcade.run()
#cv2.waitKey(0) ##mapper.printMoveGrid() print "STARTIN LOOP" moveId = 0 Xlength = mapper.grid.shape[0] / testdivider Ylength = mapper.grid.shape[1] / testdivider #dstar = dstar3.DStar(Xlength,Ylength,goal) dstar = dlite.Dlite(Xlength, Ylength, goal, robot) print "Entering Loop" testvar = 0 while (robot.y != goal.y or robot.x != goal.x): if testvar % 10 == 0: newObs = obstacle.Obstacle(random.randint(0, height), random.randint(0, width), 10) agvcmap.placeObstacle(newObs, 3) obsList.append(newObs) #Place obstacles on map agvcmap.updateObstacles(obsList) #Morph the obstacles agvcmap.updateMorph() dliteimage = cv2.resize(agvcmap.getImage(), (newWidth, newHeight)) cv2.imwrite('AGVCmap2.bmp', dliteimage) imageMap.loadFile("AGVCmap2.bmp") mapper.initalize(imageMap, robot) moveGrid = imageMap.convertToGrid().copy() testvar = testvar + 1
def defineObstaclesFromWalls(self): obstacles = [] radiusObstacles = 6 spaceBetweenObstaclesCenter = 18 # il ne faut pas que (spaceBetweenObstaclesCenter - 2*radiusObstacles) soit plus grand qu'un robot, sinon ils passent au travers des murs for wall in self.walls: wall_obstacles = [] top_line = [[wall.x_start, wall.y_start], [wall.x_start + wall.width - 1, wall.y_start]] left_line = [[wall.x_start, wall.y_start], [wall.x_start, wall.y_start + wall.height - 1]] right_line = [[wall.x_start + wall.width - 1, wall.y_start], [ wall.x_start + wall.width - 1, wall.y_start + wall.height - 1 ]] bot_line = [[wall.x_start, wall.y_start + wall.height - 1], [ wall.x_start + wall.width - 1, wall.y_start + wall.height - 1 ]] if wall.orientation == 'h': y1 = top_line[0][1] y2 = bot_line[0][1] for x in placeObstaclesOnLine(top_line[0][0], top_line[1][0], radiusObstacles, spaceBetweenObstaclesCenter): wall_obstacles.append( obs.Obstacle(x, y1, radiusObstacles, self, isWall='x', spacing=spaceBetweenObstaclesCenter, positionInWall='top')) wall_obstacles.append( obs.Obstacle(x, y2, radiusObstacles, self, isWall='x', spacing=spaceBetweenObstaclesCenter, positionInWall='bot')) elif wall.orientation == 'v': x1 = left_line[0][0] x2 = right_line[0][0] for y in placeObstaclesOnLine(left_line[0][1], left_line[1][1], radiusObstacles, spaceBetweenObstaclesCenter): wall_obstacles.append( obs.Obstacle(x1, y, radiusObstacles, self, isWall='y', spacing=spaceBetweenObstaclesCenter, positionInWall='left')) wall_obstacles.append( obs.Obstacle(x2, y, radiusObstacles, self, isWall='y', spacing=spaceBetweenObstaclesCenter, positionInWall='right')) obstacles += wall_obstacles wall.obstacles = wall_obstacles return obstacles
def generate_obstacle(self): obstacle = thing.Obstacle(50, 50, random.randrange(0, self.display_width), 0, Game.colors['black']) return obstacle
def runSim(display=True, maxSimTime=None, seed=None): gV.carCount = [] gV.avgVelocityTotal = [] gV.avgVelocityLanes = [] gV.velocityDistribution = [] gV.tempCarCount = {} for x in gV.flowrateChecks: gV.tempCarCount[x] = [0 for _ in range(gV.laneCount)] if seed is not None: gV.seed = seed np.random.seed(gV.seed) print("Seed is", gV.seed) gV.runTimer = 0 gV.vehicleCrossingTimes = [] if maxSimTime is None: maxSimTime = 2 ** 31 # Main loop flag simQuit = False # Create Objects for simulation roadObject = road.Road(pos=[0, (gV.displaySize[1] / 2) - gV.roadWidth / 2], laneCount=gV.laneCount, laneWidth=gV.roadWidth, meanArrivalRate=gV.arrivalRate) # Add obstacle for obstacleObj in gV.obstacles: roadObject.obstructionArray.append(obstacle.Obstacle(road=roadObject, x=obstacleObj['x'], lane=obstacleObj['lane'])) # Main loop while not simQuit and gV.runTimer < maxSimTime: gV.runTimer += gV.deltaTime if display: simQuit = visualiseSimulation(roadObject) # generate traffic coming down road frequency dependent on poisson distribution if round(gV.runTimer, 1) % 1 == 0: roadObject.generateTraffic() if gV.runTimer % 60 < 0.1: # every 60 seconds gV.carCount.append(gV.tempCarCount) gV.tempCarCount = {} for x in gV.flowrateChecks: gV.tempCarCount[x] = [0 for _ in range(gV.laneCount)] # vehicle handling loop for vehicleObject in roadObject.vehicleArray: vehicleObject.checkHazards(roadObject, roadObject.vehicleArray, roadObject.obstructionArray) vehicleFinishTime = vehicleObject.move() if vehicleFinishTime is not None and vehicleFinishTime > 0: gV.vehicleCrossingTimes.append(vehicleFinishTime) # Recalculates the average velocity of all vehicles in each lane for laneNum in range(roadObject.laneCount): roadObject.calcLaneFlowRate(laneNum) velocities = averageVelocity(roadObject) gV.avgVelocityTotal.append(velocities[0]) gV.avgVelocityLanes.append(velocities[1]) velocities = [x.velocity for x in roadObject.vehicleArray] if len(velocities) > 0: gV.velocityDistribution.append(stats.norm.fit(velocities)) else: gV.velocityDistribution.append((0, 0)) return processData(gV.vehicleCrossingTimes, roadObject)
## Robot Parameters ## r = 115 / 2.0 ##### Workspace ##### # Obstacles will be rectangles of length 15 and width 50 obstacle_length = 260 obstacle_width = 25 # Workspace Obstacle locations # obstacle_locations = [(690, 50), (690, 440)] # Create Obstacles and their Rectangular Plot Representation # obstacles = [] for x, y in obstacle_locations: obs = obstacle.Obstacle(x, y, obstacle_length, obstacle_width) obstacles.append(obs) obs = obstacle.Obstacle(300, 400, 100, 100) obstacles.append(obs) obs = obstacle.Obstacle(200, 150, 30, 500) obstacles.append(obs) obstacles_work = copy.deepcopy(obstacles) ##### Configuration Space ##### config_origin = (r, r) config_length = length - 2 * r config_width = width - 2 * r
## Robot Parameters ## r = 115 / 2.0 ##### Workspace ##### # Obstacles will be rectangles of length 15 and width 50 obstacle_length = 580 obstacle_width = 10 # Workspace Obstacle locations # obstacle_locations = [(250, 50), (500, 120)] # Create Obstacles and their Rectangular Plot Representation # obstacles = [] for x, y in obstacle_locations: obs = obstacle.Obstacle(x, y, obstacle_length, obstacle_width) obstacles.append(obs) obstacles_work = copy.deepcopy(obstacles) ##### Configuration Space ##### config_origin = (r, r) config_length = length - 2 * r config_width = width - 2 * r # Translate Obstacles to Configuration Space and get their Rectangular Plot Representation # obs_rects_after = [] for obs in obstacles: obs.translate(r) obstacles_config = copy.deepcopy(obstacles)
def make_objects(objects, bd, mario, objects_y): br = obstacle.Bricks(bd._height - 12, 18, 2, 8) objects.append(br) br = obstacle.Bricks(bd._height - 18, 30, 2, 6) objects.append(br) br = obstacle.Bricks(bd._height - 12, 40, 2, 8) objects.append(br) p = obstacle.Pipe(bd._height - 11, 70, 7, 6) objects.append(p) p = obstacle.Pipe(bd._height - 14, 82, 10, 10) objects.append(p) p = obstacle.Pipe(bd._height - 22, 98, 18, 8) objects.append(p) h = obstacle.Obstacle(bd._height - 4, 140, 3, 5) objects.append(h) br = obstacle.Bricks(bd._height - 12, 160, 2, 6) objects.append(br) br = obstacle.Bricks(bd._height - 17, 172, 2, 4) objects.append(br) br = obstacle.Bricks(bd._height - 6, 200, 2, 10) objects.append(br) br = obstacle.Bricks(bd._height - 8, 202, 2, 8) objects.append(br) br = obstacle.Bricks(bd._height - 10, 204, 2, 6) objects.append(br) br = obstacle.Bricks(bd._height - 12, 206, 2, 4) objects.append(br) br = obstacle.Bricks(bd._height - 14, 208, 2, 2) objects.append(br) h = obstacle.Obstacle(bd._height - 4, 210, 3, 5) objects.append(h) br = obstacle.Bricks(bd._height - 14, 215, 2, 2) objects.append(br) br = obstacle.Bricks(bd._height - 12, 215, 2, 4) objects.append(br) br = obstacle.Bricks(bd._height - 10, 215, 2, 6) objects.append(br) br = obstacle.Bricks(bd._height - 8, 215, 2, 8) objects.append(br) br = obstacle.Bricks(bd._height - 6, 215, 2, 10) objects.append(br) br = obstacle.Bricks(bd._height - 14, 240, 2, 6) objects.append(br) br = obstacle.Bricks(bd._height - 14, 258, 2, 6) objects.append(br) br = obstacle.Bricks(bd._height - 14, 276, 2, 8) objects.append(br) p = obstacle.Pipe(bd._height - 11, 290, 7, 8) objects.append(p) p = obstacle.Pipe(bd._height - 11, 303, 7, 8) objects.append(p) p = obstacle.Pipe(bd._height - 11, 316, 7, 8) objects.append(p) br = obstacle.Bricks(bd._height - 6, 330, 2, 20) objects.append(br) br = obstacle.Bricks(bd._height - 8, 332, 2, 18) objects.append(br) br = obstacle.Bricks(bd._height - 10, 334, 2, 16) objects.append(br) br = obstacle.Bricks(bd._height - 12, 336, 2, 14) objects.append(br) br = obstacle.Bricks(bd._height - 14, 338, 2, 12) objects.append(br) br = obstacle.Bricks(bd._height - 16, 340, 2, 10) objects.append(br) br = obstacle.Bricks(bd._height - 18, 342, 2, 8) objects.append(br) br = obstacle.Bricks(bd._height - 20, 344, 2, 6) objects.append(br) br = obstacle.Bricks(bd._height - 22, 346, 2, 4) objects.append(br) br = obstacle.Bricks(bd._height - 24, 348, 2, 2) objects.append(br) f = obstacle.Pipe(bd._height - 28, 357, 24, 1) objects.append(f)
def main(): ''' Testing all methods of spaceship, obstacle, and resup args: None return: None ''' # Initializing pygame: pygame.init() pygame.key.set_repeat(1,50) clock = pygame.time.Clock() width = 500 height = 700 print("########## Testing spaceship model ##########") # Initialize our spaceship: ship = spaceship.SpaceShip(width,height) startPos = getPos(ship) print("Start position: ",startPos) print("========== Testing Spaceship Update ==========") print("~~~~~~~~~~ Press q to continue ~~~~~~~~~~") stop = False while(stop != True): clock.tick(60) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if(event.key==pygame.K_q): stop = True ship.update() pos = getPos(ship) print(pos) print("========== Testing Spaceship Lucid & Update ==========") print("~~~~~~~~~~ Press q to continue ~~~~~~~~~~") ship.change_lucid(False) stop = False while(stop != True): clock.tick(60) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if(event.key==pygame.K_q): stop = True ship.update() pos = getPos(ship) print(pos) print("========== Testing spaceship speed ==========") print("~~~~~~~~~~ Press q to continue ~~~~~~~~~~") sp = int(input("Input speed: ")) lu = input("Input lucid (True/False): ") ship = spaceship.SpaceShip(width,height,lu,sp) startPos = getPos(ship) print("Start position: ",startPos) stop = False while(stop != True): clock.tick(60) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if(event.key==pygame.K_q): stop = True ship.update() pos = getPos(ship) print(pos) print("########## Testing obstacle model ##########") print("~~~~~~~~~~ Press q to continue ~~~~~~~~~~") xdirection = input("Input x direction (left,right): ") ydirection = input("Input y direction (up,down): ") speed = int(input("Input speed: ")) obst = obstacle.Obstacle(width/2,height/2,width,height,xdirection,ydirection,speed) startPos = getPos(obst) print("Start position: ",startPos) testMinMax(obst) print("========== Testing obstacle setx and sety ==========") obst = obstacle.Obstacle(width/2,height/2,width,height) print("Position: ", getPos(obst)) newx = int(input("Input new x: ")) newy = int(input("Input new y: ")) obst.setX(newx) obst.setY(newy) print("New Position: ", getPos(obst)) print("########## Testing resup model ##########") print("========== Testing stationary resup ==========") print("~~~~~~~~~~ Press q to continue ~~~~~~~~~~") station = resup.Resup(width/2,height/2,width,height) testMinMax(station) print("========== Testing moving resup ==========") print("~~~~~~~~~~ Press q to continue ~~~~~~~~~~") direction = input("Input direction (left/right): ") speed = int(input("Input speed: ")) station = resup.Resup(width/2,height/2,width,height,'moon',True,direction,speed) testMinMax(station)
def init(): new_obstacle = obstacle.Obstacle(window, x=100, y=100, batch=main_batch) obstacles.add(new_obstacle) collision_solver.add_obstacles(obstacles)
def init_obstacles(self, obs_json): obstacles = list() for ob in obs_json: obstacles.append(obstacle.Obstacle(**ob)) return obstacles
def get_obstacles(self): obstacles = [] for o in self.tiles.getObjects(): obstacles.append(obstacle.Obstacle(o.x, o.y, o.name, o.type)) return obstacles
def initializeObjects(self): ''' Create the spaceship,obstacles and resupply station arg: None return: None ''' # Create the spaceship self.spaceship = spaceship.SpaceShip(self.width, self.height, 5) self.spaceship.change_lucid(self.notReverse) # Create the resupply station, and set it to a different image depending on the game level # Set the moving direction of the resupply station direction = random.choice(['right', 'left']) img = '' if self.level == 1: img = 'moon' self.resup = resup.Resup(self.width / 2, self.height / 7, self.width, self.height, img) elif self.level == 2: img = 'mars' self.resup = resup.Resup(self.width / 2, self.height / 7, self.width, self.height, img, True, direction) elif self.level == 3: img = 'POD_small' self.resup = resup.Resup(self.width / 2, self.height / 7, self.width, self.height, img, True, direction, 2) else: img = 'satellite' self.resup = resup.Resup(self.width / 2, self.height / 7, self.width, self.height, img, True, direction, 3) # Set the number of obstacles equal to the game level numobs = self.level # Make a list for all obstacles self.obstacle = [] for i in range(numobs): posx = 0 posy = 0 # Set the moving direction of each obstacle mydirx = random.choice(['left', 'right']) mydiry = random.choice(['up', None]) self.obstacle.append( obstacle.Obstacle(posx, posy, self.width, self.height, mydirx, mydiry)) # Set the start position of each obstacle posx = random.randrange(0, self.width - self.obstacle[i].rect.width) posy = random.randrange( self.resup.rect.bottom, self.spaceship.rect.top - self.obstacle[i].rect.height) # Create each obstacle self.obstacle[i].setX(posx) self.obstacle[i].setY(posy) # Group the spaceship, obstacles and resupply station as a tuple self.sprites = pygame.sprite.RenderPlain((self.spaceship, ) + tuple(self.obstacle) + (self.resup, ))
def run(self): # 初始化窗口系统 curses.initscr() curses.noecho() curses.curs_set(0) self.window.init() # 创建玩家 center_x = (self.window.min_x() + self.window.max_x()) // 2 self.player = player.Player(self.window.max_y(), center_x, '*', self.window) # 初始化分数 obstacle.Obstacle.score = 0 # 根据难度等级生成障碍物列表 obstacle_num = int(self.window.width * self.window.height * Game.level_cfg[self.level - 1][0]) self.obstacles = [ obstacle.Obstacle('-', self.window) for _ in range(0, obstacle_num) ] # 初始化循环计数器 loop_cnt = Game.level_cfg[self.level - 1][1] loop_index = 0 hit = False # 游戏主循环 while True: self.window.clear() # 绘制障碍物 for obs in self.obstacles: obs.draw() # 绘制玩家 self.player.draw() # 显示分数 self.window.show('Score: ' + str(obstacle.Obstacle.score)) # 如果之前玩家已被击中,则跳出游戏主循环 if hit: self.window.refresh() break # 获取键盘输入 key = self.window.key() # 如果是ESC键,则退出游戏 if 27 == key: break # 更新玩家位置 self.player.move(key) # 判断障碍物是否与玩家发生碰撞 for obs in self.obstacles: if obs.get_y() == self.player.get_y() and obs.get_x( ) == self.player.get_x(): hit = True self.player.set_sym('X') break # 若无碰撞发生,更新障碍物位置 if not hit: loop_index += 1 if loop_index >= loop_cnt: loop_index = 0 for obs in self.obstacles: obs.move() # 跳出主循环后,3秒后关闭窗口 time.sleep(3.0) curses.endwin()
def loader(self, path, log_file): """ Takes in a csv file and stores the necessary instances for the simulation object. The file path referenced should point to a file of a particular format - an example of which can be found in utils.py txt_generator(). The exact order of the file is unimportant - the three if statements will extract the needed information. :param path: File path directory to a .csv file holding the simulation information :return: """ # Load and store csv file i, j, l = 0, 0, 0 info = defaultdict(list) print path with open(path) as info_read: for line in info_read: print line log_file.write(line) if not self.is_comment(line): data = line.strip().split(',') key, val = data[0], data[1:] if key == 'grid': self.dim_w = int(val[0]) self.dim_h = int(val[1]) if 'item' in key: self.items.append(item.item(val[0], val[1], val[2], i)) i += 1 elif 'agent' in key: #import ipdb; ipdb.set_trace() agnt = agent.Agent(val[1], val[2], val[3], val[4], int(val[0])) agnt.set_parameters(self, val[5], val[6], val[7]) agnt.choose_target_state = copy(self) self.agents.append(agnt) j += 1 elif 'main' in key: # x-coord, y-coord, direction, type, index self.main_agent = intelligent_agent.Agent( val[0], val[1], val[2]) self.main_agent.level = val[4] elif 'enemy' in key: self.enemy_agent = intelligent_agent.Agent( val[0], val[1], val[2], True) self.enemy_agent.level = val[4] elif 'obstacle' in key: self.obstacles.append(obstacle.Obstacle( val[0], val[1])) l += 1 # Run Checks assert len(self.items) == i, 'Incorrect Item Loading' assert len(self.agents) == j, 'Incorrect Ancillary Agent Loading' assert len(self.obstacles) == l, 'Incorrect Obstacle Loading' # Print Simulation Description print( 'Grid Size: {} \n{} Items Loaded\n{} Agents Loaded\n{} Obstacles Loaded' .format(self.dim_w, len(self.items), len(self.agents), len(self.obstacles))) # Update the map self.update_the_map()
def calculatePath(self): height = self.map.height width = self.map.width newHeight = int(height * 0.1) newWidth = int(width * 0.1) dliteimage = cv2.resize(self.map.getImage(), (newWidth, newHeight)) cv2.imwrite('AGVCmap2.bmp', dliteimage) robot = Robot(self.vehicle.x, self.vehicle.y, self.vehicle.radius * 2) imageMap = ImageReader() imageMap.loadFile("AGVCmap2.bmp") mapper.initalize(imageMap, robot) moveGrid = imageMap.convertToGrid().copy() ##goal = point(3,17) testdivider = 1 self.goal = point(int(newHeight / testdivider * 0.8), int(newWidth / testdivider * 0.8)) #cv2.waitKey(0) ##mapper.printMoveGrid() print "STARTIN LOOP" moveId = 0 Xlength = mapper.grid.shape[0] / testdivider Ylength = mapper.grid.shape[1] / testdivider #dstar = dstar3.DStar(Xlength,Ylength,goal) dstar = dlite.Dlite(Xlength, Ylength, self.goal, robot) print "Entering Loop" testvar = 0 #for i in range(10): while (robot.y != self.goal.y or robot.x != self.goal.x): if testvar % 2 == 0: newObs = obstacle.Obstacle(random.randint(0, height), random.randint(0, width), 40) self.map.placeObstacle(newObs, 3) self.obsList.append(newObs) #Place obstacles on map self.map.updateObstacles(self.obsList) #Morph the obstacles self.map.updateMorph() dliteimage = cv2.resize(self.map.getImage(), (newWidth, newHeight)) cv2.imwrite('AGVCmap2.bmp', dliteimage) imageMap.loadFile("AGVCmap2.bmp") mapper.initalize(imageMap, robot) moveGrid = imageMap.convertToGrid().copy() testvar = testvar + 1 moveId = moveId + 1 print moveId if path.pathIsBroken(mapper.grid): path.restart() print "The path is broken" # dstar2.dstar(mapper, robot, goal, path) dstar.dstar(mapper, robot, self.goal, path) #dlite.dstar(robot,goal,path) # # DstarLite.dstar(mapper, robot, goal, path) # astar.astar(mapper, robot, goal, path) pathNode = path.getNextMove() robot.x = pathNode.x robot.y = pathNode.y mapper.moveGrid[pathNode.x][pathNode.y] = "1" #mapper.printMoveGrid() self.vehicle.x = pathNode.x self.vehicle.y = pathNode.y self.vehicle.addPosition(pathNode.x, pathNode.y) mapper.updateMap(robot) #raw_input("TEST") cv2.imshow('AGVC Map', self.map.getMap()) cv2.imshow('AGVC Map Morphed', self.map.getImage()) for i in range(len(self.vehicle.positions)): self.map.placeRobot( self.vehicle.positions[i][1] * height / newHeight, self.vehicle.positions[i][0] * width / newWidth, self.vehicle.radius) nPoints = len(self.vehicle.positions) points = np.array(self.vehicle.positions) * height / newHeight #points = np.random.rand(nPoints,2)*200 xpoints = [p[0] for p in points] ypoints = [p[1] for p in points] xvals, yvals = self.bezier_curve(points, nTimes=1000) for i in range(len(xvals)): self.map.placeRobot(int(yvals[i]), int(xvals[i]), self.vehicle.radius * 2) self.map.updateActObstacles(self.obsList) cv2.waitKey(0)