def __init__(self, pos,terrain=None, dbh=0, specie=None): Obstacle.__init__(self, pos, isSpherical=True, radius=dbh,terrain=terrain, color='#5C3317') self.z=0 self.dbh=dbh self.specie=specie self.alpha=1 self.rLim=0.01 #smaller than 1cm radius is not relevant. self.zlim=0.2 #roots deeper than this are discarded. if terrain: self.name="stump%d"%len(terrain.stumps) terrain.stumps.append(self) else: self.name="stump" #the new stuff! Exciting self.RPradius=dbh/2.+0.5 #50^2/10000 =>m2, =(50/100)=0.5^2 dvs 0.5m i grundradie self.radius=self.RPradius nRoots=int(round(1.822+(0.019*dbh*1000))) #let's put up the rooots! th=random.uniform(0,2*pi) dth=2*pi/float(nRoots) cart=getCartesian maxdist2=0 self.roots=[] for i in range(nRoots): rootR=abs((-0.18943+2.96*dbh)/nRoots/2.) #radius of root #taper factor: tf=0.04+0.0206*random.normalvariate(0,1)# dm/dm root length.. thus unitless if tf<0.0194: tf=0.04 if self.specie=='pine': rootL=abs(random.normalvariate(0.510, sqrt(0.671))) #length of root elif self.specie=='spruce': rootL=abs(random.normalvariate(0.480, sqrt(0.549))) #length of root elif self.specie=='leaf': rootL=abs(random.normalvariate(0.510, sqrt(0.658))) #length of root else: raise Exception('root did not recognize specie:%s'%self.specie) #finalR=rootR-rootL*tf finalR=rootR*(1-tf) alpha=asin(rootR/self.RPradius)#half angle between p1 and p4 dr=rootR-finalR start=cart([self.RPradius-rootR, th],direction=pi/2., origin=self.pos) p1=cart([self.RPradius-rootR, th-alpha],direction=pi/2., origin=self.pos) comp=rootR/cos(th-pi/2) #to compensate for that the origin of the root is inside the root plate, -rootR above. p2=cart([-dr ,rootL+comp],origin=p1, direction=th, fromLocalCart=True) p3=cart([-dr-2*finalR,rootL+comp],origin=p1, direction=th, fromLocalCart=True) middle=cart([-dr-finalR,rootL],origin=p1, direction=th, fromLocalCart=True) p4=cart([-2*rootR,0],origin=p1, direction=th, fromLocalCart=True) if dr+finalR-rootR>rootR/100.: raise Exception('Root model does not work as planned. %f, %f, %f'%(rootR, finalR, dr)) #self._makeRoot(pos=start, direction=th, nodes=[p1,p2,p3,p4], rin=rootR, rfin=finalR,length=rootL, visible=True) #self._branch(middle, finalR, th=th, zin=0) #makes a branch. May create more sub-branches self._branch(start, rootR, th=th, zin=0, first=True) #makes a branch. May create more sub-branches th+=dth if self.terrain: self.terrain.obstacles.remove(self) self.terrain.obstacles.append(self) # to get after the roots in the list.
from level import Level from obstacle import Obstacle from vector import Point WIDTH: int = 640 HEIGHT: int = 480 POPULATION_SIZE: int = 1000 CHECKPOINT_OPTIMIZATION_ROUNDS: int = 20 LEVEL: Level = [ Level(Point(WIDTH / 2, HEIGHT - 10), Point(WIDTH / 2, 10), [ Obstacle(Point(0, HEIGHT / 2 - 5), Point(WIDTH * 3 / 4, HEIGHT / 2 + 5)) ], []), Level(Point(WIDTH / 8, HEIGHT * 3 / 4), Point(WIDTH / 8, HEIGHT / 4), [ Obstacle(Point(0, HEIGHT / 2 - 5), Point(WIDTH * 7 / 8, HEIGHT / 2 + 5)) ], [Point(WIDTH * 15 / 16, HEIGHT / 2)]), Level(Point(WIDTH / 2, HEIGHT - 10), Point(WIDTH / 2, 10), [ Obstacle(Point(0, HEIGHT / 4 - 5), Point(WIDTH * 3 / 4 + 5, HEIGHT / 4 + 5)), Obstacle(Point(WIDTH * 3 / 4 - 5, HEIGHT / 4 - 5), Point(WIDTH * 3 / 4 + 5, HEIGHT * 5 / 8 - 5)), Obstacle(Point(WIDTH * 3 / 8, HEIGHT * 5 / 8 - 5), Point(WIDTH * 3 / 4 + 5, HEIGHT * 5 / 8 + 5)), Obstacle(Point(WIDTH / 4, HEIGHT * 3 / 8 - 5), Point(WIDTH * 5 / 8, HEIGHT * 3 / 8 + 5)), Obstacle(Point(WIDTH / 4 - 5, HEIGHT * 3 / 8 - 5), Point(WIDTH / 4 + 5, HEIGHT * 3 / 4 + 5)), Obstacle(Point(WIDTH / 4 - 5, HEIGHT * 3 / 4 - 5),
def __init__(self, input_file): # parse input file f = open(input_file, 'r') # parse arm constraints try: self.num_segments = int(next_valid_line(f)) except Exception: print("Invalid value for number of segments") sys.exit(1) self.min_lengths = [float(i) for i in next_valid_line(f).split(' ')] assert len(self.min_lengths) == self.num_segments, \ "Number of minimum lengths does not match number of segments" self.max_lengths = [float(i) for i in next_valid_line(f).split(' ')] assert len(self.max_lengths) == self.num_segments, \ "Number of maximum lengths does not match number of segments" # parse initial configuration initial_grappled = int(next_valid_line(f)) assert initial_grappled == 1 or initial_grappled == 2, "Initial end effector number is not 1 or 2" try: initial_eex, initial_eey = [ float(i) for i in next_valid_line(f).split(' ') ] except Exception: print("Invalid value(s) for initial end effector position") sys.exit(1) initial_angles = [ Angle(degrees=float(i)) for i in next_valid_line(f).split(' ') ] assert len(initial_angles) == self.num_segments, \ "Number of initial angles does not match number of segments" initial_lengths = [float(i) for i in next_valid_line(f).split(' ')] assert len(initial_lengths) == self.num_segments, \ "Number of initial lengths does not match number of segments" if initial_grappled == 1: self.initial = make_robot_config_from_ee1(initial_eex, initial_eey, initial_angles, initial_lengths, ee1_grappled=True) else: self.initial = make_robot_config_from_ee2(initial_eex, initial_eey, initial_angles, initial_lengths, ee2_grappled=True) # parse goal configuration goal_grappled = int(next_valid_line(f)) assert goal_grappled == 1 or goal_grappled == 2, "Goal end effector number is not 1 or 2" try: goal_eex, goal_eey = [ float(i) for i in next_valid_line(f).split(' ') ] except Exception: print("Invalid value(s) for goal end effector 1 position") sys.exit(1) goal_angles = [ Angle(degrees=float(i)) for i in next_valid_line(f).split(' ') ] assert len(goal_angles) == self.num_segments, \ "Number of goal ee1 angles does not match number of segments" goal_lengths = [float(i) for i in next_valid_line(f).split(' ')] assert len(goal_lengths) == self.num_segments, \ "Number of goal lengths does not match number of segments" if goal_grappled == 1: self.goal = make_robot_config_from_ee1(goal_eex, goal_eey, goal_angles, goal_lengths, ee1_grappled=True) else: self.goal = make_robot_config_from_ee2(goal_eex, goal_eey, goal_angles, goal_lengths, ee2_grappled=True) # parse grapple points try: self.num_grapple_points = int(next_valid_line(f)) except Exception: print("Invalid value for number of grapple points") sys.exit(1) grapple_points = [] for i in range(self.num_grapple_points): try: grapple_points.append( tuple([float(i) for i in next_valid_line(f).split(' ')])) except Exception: print("Invalid value(s) for grapple point " + str(i) + " position") sys.exit(1) self.grapple_points = grapple_points # parse obstacles try: self.num_obstacles = int(next_valid_line(f)) except Exception: print("Invalid value for number of obstacles") sys.exit(1) obstacles = [] for i in range(self.num_obstacles): try: x1, y1, x2, y2 = [ float(i) for i in next_valid_line(f).split(' ') ] obstacles.append(Obstacle(x1, y1, x2, y2)) except Exception: print("Invalid value(s) for obstacle " + str(i)) sys.exit(1) self.obstacles = obstacles
from cvxopt import matrix, solvers #区域表,第一个为可行区域,后续为障碍物 #AreaList = [] #地图初始化 map = Section() plt.figure() axes = plt.gca() #起点与终点 origin = Point(0.0, 0.0) remote = Point(0.0, 50.0) result = [origin, remote] #路沿 obstacles = [] road_left_obs = Obstacle() road_left_obs.createObs(-20, 0, 15, 50) road_right_obs = Obstacle() road_right_obs.createObs(5, 0, 15, 50) obstacles.append(road_left_obs) obstacles.append(road_right_obs) road_left_obs_area = Area(road_left_obs.obstacle_x, road_left_obs.obstacle_x, road_left_obs.obstacle_width, road_left_obs.obstacle_height) road_right_obs_area = Area(road_right_obs.obstacle_x, road_right_obs.obstacle_x, road_right_obs.obstacle_width, road_right_obs.obstacle_height) ''' plt.Rectangle((-20,0),15,50) axes.add_patch(road_left_obs)
def game(self, genome, config, mode): #Set Mode (0 = Play, 1 = Train) self.mode = mode FPS = 60 if (self.mode == 1): FPS = 200 WIDTH = 288 HEIGHT = 512 running = True paused = False BACKGROUND = pygame.image.load("bg.png") #NEAT Stuff if (self.mode == 1): fitness = 0 ffnet = neat.nn.FeedForwardNetwork.create(genome, config) pygame.init() CLOCK = pygame.time.Clock() PANEL = pygame.display.set_mode((WIDTH, HEIGHT)) score = 0 time = 0 #Player Character player = Player(PANEL) #Obstacles obsU1 = Obstacle(PANEL, 512, 256, False) obsL1 = Obstacle(PANEL, 512, 256, True) obsU2 = Obstacle(PANEL, 512 + 200, 160, False) obsL2 = Obstacle(PANEL, 512 + 200, 160, True) #Create List of Obstacles for easy handling obsList = [] obsList.append(obsU1) obsList.append(obsL1) obsList.append(obsU2) obsList.append(obsL2) #Create Group of Sprites for Collision Detection obsGroup = pygame.sprite.Group() myNum = 0 for obs in obsList: obsGroup.add(obs) #Let's also use this time to set the initial midY if (myNum == 0 or myNum == 2): myMid = random.randint(160, 512 - 160) obs.setMidY(myMid) myNum += 1 #Game Loop while running: time += 1 if (self.mode == 1 and not paused): #Get Closest Obs minBotX = 1000 minTopX = 1000 botObs = None topObs = None for obs in obsList: if (obs.top and obs.x < minTopX): topObs = obs if (not obs.top and obs.x < minBotX): botObs = obs closestMid = topObs.midY input = (player.y, topObs.x, topObs.y, botObs.y) #distanceToMid = abs(player.y - closestMid) distanceToMid = (( (player.y - closestMid)**2) * 100) / (512 * 512) #fitness = time + score - distanceToMid fitness = score - distanceToMid + (time / 10.0) output = ffnet.activate(input) if (output[0] >= 0.5): player.jump() #Get Inputs for event in pygame.event.get(): if (event.type == KEYDOWN): #Player Jump if (event.key == K_SPACE and mode == 0): player.jump() if (event.key == K_TAB and mode == 0): paused = not paused #Close Game With Escape Key if (event.key == K_ESCAPE): self.close() if (not paused): PANEL.blit(BACKGROUND, (0, 0)) player.step() myMid = random.randint(160, 512 - 160) for obs in obsList: obs.step() #Reset Obs if (obs.x < 0 - obs.w): obs.x = obs.x + WIDTH * 1.5 obs.setMidY(myMid) score += 5 #Check Collision collision = pygame.sprite.spritecollideany(player, obsGroup) #Game Over Conditions if (collision != None or player.y <= 0 or player.y >= HEIGHT): if (self.mode == 0): print("GAME OVER") self.close() if (self.mode == 1): return fitness pygame.display.update() CLOCK.tick(FPS)
all_push_poses.header = self.static_map.header all_push_poses.header.stamp = rospy.Time.now() for obstacle_id, obstacle in self.multilayered_map.obstacles.items(): for push_pose in obstacle.push_poses: all_push_poses.poses = all_push_poses.poses + [push_pose.pose] Utils.publish_once(self.push_poses_pub, all_push_poses) if __name__ == '__main__': rospy.init_node('map_manager') map_manager = MapManager(0.05, 1.0, "/map", "/simulated/global_occupancy_grid", "/simulated/all_push_poses") # This obstacle with these specific coordinates can only be inserted in the 01 map obstacle1 = Obstacle.from_points_make_polygon(Utils.map_coords_to_real_coords( {(7, 1), (8, 1), (7, 6), (8, 6)}, map_manager.multilayered_map.info.resolution), map_manager.multilayered_map.info, map_manager.map_frame, map_manager.robot_metadata, 1, True) map_manager.manually_add_obstacle(obstacle1) # print(obstacle1.robot_inflated_obstacle["matrix"]) # print(obstacle1.obstacle_matrix["matrix"]) # # # TEST # print(map_manager.multilayered_map.info) # print(map_manager.multilayered_map.robot_metadata) # print(map_manager.multilayered_map.frame_id) print(map_manager.multilayered_map.static_occ_grid) print(map_manager.multilayered_map.static_obstacles_positions)
for i in range(len(way_coords)): nums = [float(k) for k in regex.findall(way_coords[i])] #find integer value in string format '[ int, int ]' way_x.append(nums[0]) way_y.append(nums[1]) # print("waypoints : (x,y ) = (", way_x,", ", way_y,")") # print("waypoints :way_x) floatregex =re.compile('[-+]?\d*\.\d+|[-+]?\d+') obstacles = [] # list which will contain all obstacles obstacle_coords = np.asarray(obsdf['obstacle'][0:]) # print("obstacle coords") # print(obstacle_coords) for i in range(len(obstacle_coords)): nums = [float(k) for k in floatregex.findall(obstacle_coords[i])] #find integer value in string format '[ int, int ]' # print(nums) obs = Obstacle(nums[0]-1, nums[1]-1, nums[2], nums[3]) #xmin,ymin, obs.draw() obstacles.append(obs) # attach obstacle to obstacle list # print("num ofobstacles:", len(obstacles)) print("---load completed") #Create wall - Rectangular Search region walls=[] obs = Obstacle(-Region_Boundary, -Region_Boundary, -Region_Boundary, Region_Boundary,True) walls.append(obs) # attach obstacle to obstacle list obs = Obstacle(-Region_Boundary, Region_Boundary, -Region_Boundary, -Region_Boundary,True) walls.append(obs) # attach obstacle to obstacle list obs = Obstacle(-Region_Boundary, Region_Boundary, Region_Boundary, Region_Boundary,True) walls.append(obs) # attach obstacle to obstacle list obs = Obstacle(Region_Boundary, Region_Boundary, -Region_Boundary, Region_Boundary,True) walls.append(obs) # attach obstacle to obstacle list
def read_inputfile(FILE_NAME="input2.txt"): line_ctr = 0 polygons = [] with open(FILE_NAME) as f: num_lines = sum(1 for l in f) with open(FILE_NAME) as f: for l in f: line_ctr += 1 if line_ctr == 1: boundary = list(ast.literal_eval(l)) elif line_ctr in range(2, num_lines): polygons.append(list(ast.literal_eval(l))) else: temp = list(ast.literal_eval(l)) start_state = [temp[0], temp[1], temp[2], temp[3]] init_pos = [temp[0], temp[1]] # goal_state = temp[1] #Create wall objects walls = [] xmin = 100 ymin = 100 xmax = -100 ymax = -100 for point in boundary: if xmin > point[0]: xmin = point[0] if xmax < point[0]: xmax = point[0] if ymin > point[1]: ymin = point[1] if ymax < point[1]: ymax = point[1] print("xmin: ", xmin, ", xmax: ", xmax, ", ymin", ymin, ", ymax: ", ymax) wall = Obstacle(xmin, xmin, ymin, ymax, True) walls.append(wall) wall = Obstacle(xmin, xmax, ymin, ymin, True) walls.append(wall) wall = Obstacle(xmax, xmax, ymin, ymax, True) walls.append(wall) wall = Obstacle(xmin, xmax, ymax, ymax, True) walls.append(wall) #Create obstacle objects obstacles = [] for obs in polygons: xmin = 100 ymin = 100 xmax = -100 ymax = -100 for point in obs: if xmin > point[0]: xmin = point[0] if xmax < point[0]: xmax = point[0] if ymin > point[1]: ymin = point[1] if ymax < point[1]: ymax = point[1] tmp = Obstacle(xmin, xmax, ymin, ymax) obstacles.append(tmp) # attach obstacle to obstacle list # print(obstacles) return start_state, init_pos, obstacles, walls
def spawn_obstacle(self, x, y): self.obstacles.append(Obstacle(self, x, y, random.uniform(60, 130)))
from obstacle import Obstacle class Level: def __init__(self, obstacles, target, time_limit): self.obstacles = obstacles self.target = target # how much food player needs to eat in order to win self.time_limit = time_limit levels = [ Level([], 5, 60), Level([Obstacle(200, 200, 500, 500)], 10, 60), ]
# import necessary classes from world import LightObstacleWorld from robot import Robot from light import Light from obstacle import Obstacle # initialize two robots r = Robot(radius=3) r.setState(x=50, y=80, theta=180) # initialize a light source l = Light(x=50, y=20) # initiallize the obstacle o1 = Obstacle(20, 40, 60, 10) o2 = Obstacle(20, 40, 10, 30) o3 = Obstacle(70, 40, 10, 30) # Modify the move function, such that the robot moves to the goal (the light source) and stops there. # This exercise is identical to exercise03, but the obstacle is now more complex def move(robot, rightMeasurement, leftMeasurement): # ------------- Modify this part -------------------------------------- free = robot.moveForward(0.01) # ---------------------------------------------------------------------- # pass move function to robots r.controller = move
def storeObstacle(self, x, y): point = Obstacle(x, y) self.obstacles.append(point)
def game(self, genome, config, mode): # Set Mode (0 = Play, 1 = Train) self.mode = mode FPS = 800 if (self.mode == 1): FPS = 800 WIDTH = 288 HEIGHT = 512 running = True paused = False BACKGROUND = pygame.image.load("bg.png") # Last Obstacle Jumped Over lastObst = None # closest mid point closestMid = 0 botObs = None topObs = None closestX = 0 lastObst = None lastYDiff = 0 lastDist2Mid = 0 bonus = 0 # NEAT Stuff if (self.mode == 1): fitness = 0 ffnet = neat.nn.FeedForwardNetwork.create(genome, config) pygame.init() CLOCK = pygame.time.Clock() PANEL = pygame.display.set_mode((WIDTH, HEIGHT)) time = 0 # Player Character player = Player(PANEL) # Obstacles obsU1 = Obstacle(PANEL, 300, 256, False) obsL1 = Obstacle(PANEL, 300, 256, True) obsU2 = Obstacle(PANEL, 300 + 200, 160, False) obsL2 = Obstacle(PANEL, 300 + 200, 160, True) # Create List of Obstacles for easy handling obsList = [] obsList.append(obsU1) obsList.append(obsL1) obsList.append(obsU2) obsList.append(obsL2) # Create Group of Sprites for Collision Detection obsGroup = pygame.sprite.Group() myNum = 0 for obs in obsList: obsGroup.add(obs) # Let's also use this time to set the initial midY if (myNum == 0 or myNum == 2): myMid = self.getNewMid() obs.setMidY(myMid) myNum += 1 # Game Loop while running: time += 1 if (self.mode == 1 and not paused): # Get Closest Obs minBotX = 1000 minTopX = 1000 botObs = None topObs = None for obs in obsList: if (obs.top and obs.x < minTopX and obs.x > player.x): topObs = obs minTopX = topObs.x if (not obs.top and obs.x < minBotX and obs.x > player.x): botObs = obs minBotX = botObs.x closestMid = topObs.midY closestX = topObs.x #input = (player.y,topObs.x,closestMid) yDiff = abs(player.y - closestMid) yDiffTop = abs(player.y - (topObs.y + 320)) yDiffBot = abs(player.y - (botObs.y)) #distanceToMid = abs(player.y - closestMid) distanceToMid = ((((player.y - closestMid)**2) + ((player.x - closestX)**2))**(1 / 2)) / 10 #FITNESS FUNCTION if (yDiff < 25 or (yDiff < lastYDiff and player.y < botObs.y and player.y > topObs.y + 320)): myGlobals.SCORE += 1 if (yDiff > lastYDiff and (player.y > botObs.y or player.y < topObs.y + 320)): myGlobals.SCORE -= 1 if (closestX - player.x <= 50 and (distanceToMid <= 5)): myGlobals.SCORE += 1 bonus += 1 #current direction lastYDiff = abs(player.y - closestMid) lastDist2Mid = distanceToMid #NEAT-python inputs input = (yDiff, yDiffTop, yDiffBot, closestX) #pygame.draw.line(PANEL, (57,255,20), (topObs.x,topObs.y+320), (0,topObs.y+320)) #pygame.draw.line(PANEL, (57,255,20), (botObs.x,botObs.y), (0,botObs.y)) # pygame.draw.line(PANEL, (0,0,0), (player.x+34,player.y+18), (player.x+closestX-26,closestMid)) # pygame.draw.line(PANEL, (0,0,0), (player.x+34,player.y+18), (player.x+closestX-26,topObs.y+320)) # pygame.draw.line(PANEL, (0,0,0), (player.x+34,player.y+18), (player.x+closestX-26,botObs.y)) # pygame.display.flip() #fitness = time + SCORE - distanceToMid # ratio to be redetermined! fitness = 5 * myGlobals.SCORE - 3 * distanceToMid # Get Output output = ffnet.activate(input) # Jump if output is above threshold if (output[0] >= 0.5): player.jump() # Get Inputs for event in pygame.event.get(): if (event.type == KEYDOWN): # Player Jump if (event.key == K_SPACE and mode == 0): player.jump() if (event.key == K_TAB and mode == 0): paused = not paused # Close Game With Escape Key if (event.key == K_ESCAPE): self.close() if (not paused): PANEL.blit(BACKGROUND, (0, 0)) myfont = pygame.font.SysFont('Arial', 12) playerYText = myfont.render("playerY: " + str(player.y), False, (0, 0, 0)) distToMidText = myfont.render( "Distance2Mid: " + str(distanceToMid), False, (0, 0, 0)) xMidText = myfont.render("closestX: " + str(closestX), False, (0, 0, 0)) bonusText = myfont.render("numBonuses: " + str(bonus), False, (0, 0, 0)) scoreText = myfont.render("FITNESS: " + str(myGlobals.SCORE), False, (0, 0, 0)) PANEL.blit(playerYText, (20, 20)) PANEL.blit(distToMidText, (20, 40)) PANEL.blit(xMidText, (20, 60)) PANEL.blit(bonusText, (20, 80)) PANEL.blit(scoreText, (20, 100)) player.step() myMid = self.getNewMid() for obs in obsList: obs.step() # Reset Obs if (obs.x < 0 - obs.w): obs.x = obs.x + WIDTH * 1.5 obs.setMidY(myMid) # Up Score if (obs.top and obs.x < player.x and lastObst != obs): myGlobals.SCORE += 10 lastObst = obs print('SCORE: ' + str(myGlobals.SCORE)) # Check Collision collision = pygame.sprite.spritecollideany(player, obsGroup) # Game Over Conditions if (collision != None or player.y <= 0 or player.y >= HEIGHT): if (self.mode == 0): print("GAME OVER") self.close() if (self.mode == 1): return fitness pygame.display.update() CLOCK.tick(FPS)
def game_loop(): gameEnded = False pygame.event.clear() a = 0 t0 = time() while not gameEnded: road.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: gameEnded = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: gameEnded = True elif event.key == pygame.K_UP or event.key == pygame.K_w: a = ACCELARATION elif (event.key == pygame.K_LEFT or event.key == pygame.K_a or event.key == pygame.K_RIGHT or event.key == pygame.K_d): a = 0 elif event.type == pygame.KEYUP: if (event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_w or event.key == pygame.K_s or event.key == pygame.K_LEFT or event.key == pygame.K_a or event.key == pygame.K_RIGHT or event.key == pygame.K_d): a = 0 elif event.type == E_ADDOBSTACLE: obstacle = Obstacle() bush = Bush() allSprites.add(bush) bushes.add(bush) if not car.rect.colliderect(obstacle.rect): allSprites.add(obstacle) obstacles.add(obstacle) t1 = time() dt = (t1 - t0) t0 = t1 pressed_keys = pygame.key.get_pressed() car.update(pressed_keys, ACCELARATION, dt) for obstacle in obstacles: if obstacle.rect.colliderect(car.rect): gameEnded = True crash() break else: obstacle.move(ACCELARATION, dt) for bush in bushes: bush.move(ACCELARATION, dt) road.move(ACCELARATION, dt) allSprites.draw(road.gameDisplay) pygame.display.update() clock.tick(30)
window.drawLineSeg(x1, y1, x2, y2, color, width=3) window.update() if __name__ == "__main__": window = DrawingWindow(800,800,0,800,0,800,"test") grid_size = 50 delta_x = window.windowWidth / grid_size delta_y = window.windowHeight / grid_size pts = [ (0,0), (0,20), (20,20) ] robot = Robot(window, (0,0), pts, (delta_x, delta_y))#, multi=True) pts = [(100,210), (150,350), (250, 300)] o = Obstacle(window, pts) pts = [ (400, 325), (450, 325), (450, 375)] o1 = Obstacle(window, pts) goal = [27, 40] cells = node.all_points(robot.loc, grid_size, grid_size) t0 = time.clock() # robot.plan = node.search(robot.loc, goal, dfs=True) robot.plan = node.dijkstra(robot.loc, goal, cells, grid_size) # heuristic = lambda x: (((x[0] - goal[0]) ** 2 + (x[1] - goal[1]) ** 2)) ** 0.5 # robot.plan = node.ucSearch(robot.loc, goal, heuristic) print "delta", time.clock() - t0
sleep(robot.turn_right_rate) toggle_localization_srv(pause=False) previous_movement = movement rate.sleep() if __name__ == '__main__': # Initalize global variables robot_mode = RobotMode.READY mode_change = False robot = Robot(rate_config_path=os.path.join( rospkg.get_pkg_dir('navigation'), 'config', 'walking_rate.json')) obstacle = Obstacle() SPIN_RATE = 0.5 NUM_MAP_ROWS, NUM_MAP_COLUMNS = 19, 28 look_at_lines = False lines = [] # Wait for other nodes to launch wait_for_node('/op3_manager') wait_for_node('/vision_node') wait_for_node('/slam_node') # Initialze ROS node rospy.init_node('navigation_node') rate = rospy.Rate(SPIN_RATE) # Setup ROS publisher
class GameManager(arcade.Window): def __init__(self): super().__init__(c.SCREEN_WIDTH, c.SCREEN_HEIGHT, "Sprite Example") # 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) # Variables that will hold sprite lists self.player_list = None self.obstacle_list = None self.set_update_rate(1 / 200) self.gameRunning = True self.counter = 0 self.generation = CactusJumperGenerator() # Set up the player info self.player_sprite = None self.score = 1 # Don't show the mouse cursor self.set_mouse_visible(False) arcade.set_background_color(arcade.color.AMAZON) def setup(self): """ Set up the game and initialize the variables. """ obsSpeed = random.uniform(7, 11) obsWidth = random.uniform(30, 50) # Sprite lists self.obstacle = Obstacle(obsSpeed) self.obstacle.width = obsWidth self.generation.obstacle = self.obstacle self.generation.populate() self.player_list = arcade.SpriteList() # Score # Set up the player # Character image from kenney.nl for sprite in self.generation.population: self.player_list.append(sprite) self.fitList = [player.getFittness() for player in self.player_list] # Create the coins def on_draw(self): """ Draw everything """ arcade.start_render() self.obstacle.draw() self.player_list.draw() arcade.draw_line(0, 100, c.SCREEN_WIDTH, 100, arcade.color.BLACK, 2) texture = arcade.load_texture("res/dirt.png") scale = .25 for i in range(50, c.SCREEN_WIDTH, 100): arcade.draw_texture_rectangle(i, 50, scale * texture.width, scale * texture.height, texture, 0) output = f"Generation: {self.score}" arcade.draw_text(output, 600, 450, arcade.color.WHITE, 14) output2 = str(self.fitList) arcade.draw_text(output2, 100, 450, arcade.color.WHITE, 14) for p in self.player_list: o = "G:" + str(p.age) o2 = "F: %.2f" % p.getFittness() o3 = "JP: %.2f" % p.jumpPos o4 = "JH: %.2f" % p.jumpHeight o5 = "%.2f" % (p.gene[0][0]) o6 = "%.2f" % (p.gene[0][1]) o7 = "%.2f" % (p.gene[1][0]) o8 = "%.2f" % (p.gene[1][1]) arcade.draw_text(o, p.center_x, p.center_y + 30, arcade.color.WHITE, 14) arcade.draw_text(o2, p.center_x, p.center_y + 10, arcade.color.WHITE, 14) arcade.draw_text(o3, p.center_x, p.center_y - 10, arcade.color.WHITE, 14) arcade.draw_text(o4, p.center_x, p.center_y - 30, arcade.color.WHITE, 14) arcade.draw_text(o5, p.center_x - 20, p.center_y + 80, arcade.color.WHITE, 8) arcade.draw_text(o6, p.center_x - 20, p.center_y + 70, arcade.color.WHITE, 8) arcade.draw_text(o7, p.center_x - 20, p.center_y + 60, arcade.color.WHITE, 8) arcade.draw_text(o8, p.center_x - 20, p.center_y + 50, arcade.color.WHITE, 8) def update(self, delta_time): # if not self.obstacle_list: # self.obstacle_list.append(Obstacle(OBSTACLE_SPEED)) # elif NEW_OBSTACLE_PER_FRAME > random.randint(0,100) and self.obstacle_list[-1].center_x <= 900: # self.obstacle_list.append(Obstacle(OBSTACLE_SPEED)) self.counter += 1 print(self.counter) self.obstacle.move() for player in self.player_list: if player.readyToJump(): player.jump() hit_list = arcade.check_for_collision_with_list( self.obstacle, self.player_list) for player in hit_list: player.touched = 1000 self.player_list.update() self.obstacle.update() # Loop through each colliding sprite, remove it, and add to the score. if self.generation.jumpingFinished() and self.obstacle.center_x < 10: self.generation.selection() self.score += 1 self.setup() def on_key_press(self, key, modifiers): """ Called whenever the user presses a key. """ if key == arcade.key.SPACE: pass
output_dir = args.output_dir if not os.path.exists(output_dir): os.makedirs(output_dir) img_dir = os.path.join(output_dir, "imgs") plot_dir = os.path.join(output_dir, "plots") if not os.path.exists(img_dir): os.makedirs(img_dir) if not os.path.exists(plot_dir): os.makedirs(plot_dir) app = QApplication(sys.argv) world = Box(0, world_width, 0, world_height) obstacles = [] for obstacle_dim in obstacle_dims: obstacles.append(Obstacle(*obstacle_dim)) places = [] for i, place_dim in enumerate(place_dims): places.append(Place(*place_dim, place_type[i], i)) for place in places: place.pass_others(places) agents = [] for i in range(agent_num): agents.append(Agent(world, obstacles, places, i)) for agent in agents: agent.pass_others(agents) plot = Plot(agents, plot_dir)
from camera import Camera from obstacle import Obstacle pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() player_group = pygame.sprite.Group() enemies_group = pygame.sprite.Group() player_bullets_group = pygame.sprite.Group() enemies_bullets_group = pygame.sprite.Group() obstacles_group = pygame.sprite.Group() for i in range(50): Obstacle(obstacles_group) background = pygame.transform.scale(load_image('background.jpg'), (WIDTH, HEIGHT * 2)) camera = Camera(background.get_rect().h) player = Player(player_group, player_bullets_group, enemies_group, enemies_bullets_group, obstacles_group) running = True font = pygame.font.Font(None, 30) while running: for event in pygame.event.get(): if event.type == pygame.QUIT:
from player import Player from food import Food from obstacle import Obstacle from fire import bulltes import pygame from buttom import buttom worldx = 960 worldy = 720 screen = pygame.display.set_mode((worldx, worldy)) shark = 'image/icon.png' background = pygame.image.load(shark).convert() background = pygame.transform.scale(background, (worldx, worldy), screen) player = Player(background, 0, 0, shark) food = Food(background, 1, 1) obstacle = Obstacle(background, 2, 2) fire = bulltes(background, 0, 0) button = buttom(1, 1, 1, 1, (255, 255, 255), 'Mode1') def test1() -> bool: """ Test whether get_center in player.py works :return: """ x = player.get_center() if x == (65, 35): print("Test 1: Testing player.py get_center() function: Passed") return True else: print("Test 1: Testing player.py get_center() function: Not Passed")
def mainLoop(self): """ 游戏的主循环体 """ # 初始化用户询问界面结束的flag askingFinished = False while True: self.videoClock.tick(80) # 填充背景色 self.mainWindow.fill((255,255,255)) if self.state == 0: # 第一次进入的界面 for event in pygame.event.get(): # 退出事件 if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN or event.type == MOUSEBUTTONUP: self.state = 1 self.mainWindow.blit(self.firstPic,(0,0)) elif self.state == 1: # 初始化询问界面 # 用户询问界面下的事件处理 for event in pygame.event.get(): # 退出事件 if event.type == QUIT: pygame.quit() sys.exit() # 键盘按下事件 if event.type == KEYDOWN: if event.key == 8 and len(self.askingInputStr) != 0: self.askingInputStr = self.askingInputStr[0:len(self.askingInputStr)-1] # 按键 Backspace elif event.key == 48 or event.key == 256: self.askingInputStr += "0" # 按键 0 elif event.key == 49 or event.key == 257: self.askingInputStr += "1" # 按键 1 elif event.key == 50 or event.key == 258: self.askingInputStr += "2" # 按键 2 elif event.key == 51 or event.key == 259: self.askingInputStr += "3" # 按键 3 elif event.key == 52 or event.key == 260: self.askingInputStr += "4" # 按键 4 elif event.key == 53 or event.key == 261: self.askingInputStr += "5" # 按键 5 elif event.key == 54 or event.key == 262: self.askingInputStr += "6" # 按键 6 elif event.key == 55 or event.key == 263: self.askingInputStr += "7" # 按键 7 elif event.key == 56 or event.key == 264: self.askingInputStr += "8" # 按键 8 elif event.key == 57 or event.key == 265: self.askingInputStr += "9" # 按键 9 # 鼠标左键按下事件 elif event.type == MOUSEBUTTONDOWN and (pygame.mouse.get_pressed())[0] == 1: askingFinished = True # 鼠标左键抬起事件 elif event.type == MOUSEBUTTONUP and askingFinished == True: # 获取鼠标的位置 mouse_x = pygame.mouse.get_pos()[0] mouse_y = pygame.mouse.get_pos()[1] askingButtonRect = self.askingButton.get_rect() # 检查鼠标点击的位置是否在按键中 if self.width/4+300 < mouse_x < self.width/4+300+askingButtonRect.width and (self.height)/2 < mouse_y < (self.height)/2+askingButtonRect.height: # 只有当数量在2到8之间的时候才通过 if len(self.askingInputStr) != 0: # 将字符串转化成数字 playersNumber = int(self.askingInputStr) if 2 <= playersNumber <= 4: # 记录玩家的数量 self.playersNumber = playersNumber # 初始分配位置元组 initNO = self.initNO[self.playersNumber] # 创建玩家和胶带 for m1 in range(self.playersNumber): # 创建玩家 self.playersList.append(Player(m1)) # 创建胶带 tempTape = Tape([self.initPositionDict[initNO[m1]][0], self.initPositionDict[initNO[m1]][1]], self.tapeRadius) # 绑定玩家和胶带 self.playersList[m1].bindTape(tempTape) # 创建障碍物 count = 0 for tempPos in self.obstaclePos: count += 1 self.obstacleList.append(Obstacle(count, tempPos[0], tempPos[1], self.obstacleRadius)) self.state = 2 # 初始化回合标记 self.turn = 0 # 初始化玩家回合标记 hasFinished = False # 初始化玩家激励label countingForce = False # 鼠标初始位置 mouse_x = mouse_y = 0 # 创建边框 self.boundary = Barrier(self.boundObstRadius, self.width, self.height) # 画背景图片 self.mainWindow.blit(self.backgroundPic,(0,0)) # 画出标题 self.mainWindow.blit(self.askingTitle, (self.width/2-self.askingTitle.get_rect().width/2,(self.height)/4)) # 画出数字询问文字 self.mainWindow.blit(self.askingNumber, (self.width/4-self.askingNumber.get_rect().width/2,(self.height)/2)) # 画出对话框 textField = self.font1.render(self.askingInputStr, True, (255,255,0)) self.mainWindow.blit(textField, (self.width/4-self.askingNumber.get_rect().width/2+self.askingNumber.get_rect().width,(self.height)/2)) # 画出按钮 self.mainWindow.blit(self.askingButton, (self.width/4+300,(self.height)/2)) elif self.state == 2: if self.isSimulating: # 运动仿真状态 for event in pygame.event.get(): # 退出事件 if event.type == QUIT: pygame.quit() sys.exit() # 所有小球是否都停止的标志 allStop = True # 每个玩家的胶带挨个进行仿真 for player in self.playersList: # 运动仿真 player.myTape.simulation(self.boundary, self.playersList, self.obstacleList) # 检查是否停止 if player.myTape.moving == True: allStop = False if allStop == True: # 结束仿真 self.isSimulating = False # 玩家回合结束回置为False hasFinished = False else: # 玩家输入状态 # 统计玩家的数量 currentPlayer = 0 for player in self.playersList: if player.isPlaying == True: currentPlayer += 1 # 如果玩家数量等于1,那么游戏结束 if currentPlayer <= 1: self.state = 3 # 玩家还未完成弹射操作 if hasFinished == False: for event in pygame.event.get(): # 退出事件 if event.type == QUIT: pygame.quit() sys.exit() # 鼠标移动 elif event.type == MOUSEMOTION: mouse_x = event.pos[0] mouse_y = event.pos[1] # 鼠标按下事件 elif event.type == MOUSEBUTTONDOWN: countingForce = True playerForce = 0.0 # 鼠标松开事件 elif event.type == MOUSEBUTTONUP: # 停止计力 countingForce = False # 计算方向 temp_pos = self.playersList[self.turn].myTape.pos temp_x = temp_pos[0] - mouse_x temp_y = temp_pos[1] - mouse_y temp_l = pow(pow(temp_x,2)+pow(temp_y,2), 0.5) sin_theta = temp_y / temp_l cos_theta = temp_x / temp_l # 将玩家激励作为初速度给胶带 self.playersList[self.turn].myTape.setVelocity([playerForce*cos_theta, playerForce*sin_theta]) # 玩家本回合操作结束 hasFinished = True # 玩家激励计数 if countingForce == True: playerForce += 0.5 # 当超过力上限后,置0重新计数 if playerForce >= self.maxForce: playerForce = 0.0 # 玩家已经完成弹射操作 else: # 跳转至下一玩家, while True: self.turn += 1 # 如果已经达到了玩家上线,则重新回到0 if self.turn == self.playersNumber: self.turn = 0 # 判断是否是正在游戏的玩家 if self.playersList[self.turn].isPlaying == True: # 进入仿真状态 self.isSimulating = True break # 绘制球台背景 self.mainWindow.blit(self.playingBackground,(0,0)) # 绘制边框 if self.boundary.lifeTime == 3: self.mainWindow.blit(self.barrierPic1, (0,0)) elif self.boundary.lifeTime == 2: self.mainWindow.blit(self.barrierPic2, (0,0)) elif self.boundary.lifeTime == 1: self.mainWindow.blit(self.barrierPic3, (0,0)) # 绘制障碍物 for obstacle in self.obstacleList: if obstacle.lifeTime == 3: self.mainWindow.blit(self.obstaclePic1, (obstacle.pos[0]-obstacle.radius,obstacle.pos[1]-obstacle.radius)) elif obstacle.lifeTime == 2: self.mainWindow.blit(self.obstaclePic2, (obstacle.pos[0]-obstacle.radius,obstacle.pos[1]-obstacle.radius)) elif obstacle.lifeTime == 1: self.mainWindow.blit(self.obstaclePic3, (obstacle.pos[0]-obstacle.radius,obstacle.pos[1]-obstacle.radius)) # 如果玩家还未完成该回合,则需要进行划线 if hasFinished == False: pygame.draw.line(self.mainWindow, (0,255,0), self.playersList[self.turn].myTape.pos, (mouse_x, mouse_y), 5) # 如果玩家正在计力,则需要画出计力格 if countingForce == True: boxHeight = int(playerForce/self.maxForce*self.forceBoxMaxHeight) pygame.draw.rect(self.mainWindow, (0,0,0), (self.width-100, self.height-100-self.forceBoxMaxHeight, self.forceBoxWidth, self.forceBoxMaxHeight)) pygame.draw.rect(self.mainWindow, (0,0,255), (self.width-100, self.height-100-boxHeight, self.forceBoxWidth, boxHeight), 0) # 绘制胶带 for player in self.playersList: # 判断玩家是否在游戏 if player.isPlaying: # 绘制胶带图形 self.mainWindow.blit(self.playingTapePic,(int(player.myTape.pos[0])-self.tapeRadius, int(player.myTape.pos[1])-self.tapeRadius)) # 绘制编号 self.mainWindow.blit(self.playingNOFont.render(str(player.playerNO+1), True, (0,0,255)), player.myTape.pos) elif self.state == 3: # 游戏结束状态,统计是谁获得了胜利 # 绘制背景图 self.mainWindow.blit(self.backgroundPic,(0,0)) # 如果剩余玩家数量是0,则没有人获得胜利 if currentPlayer == 0: # 生成表示没有人获得胜利的文字 textField = self.font0.render("No one wins the game!", True, (255,255,0)) else: # 生成获得胜利的玩家的文字 for player in self.playersList: if player.isPlaying == True: winner = player break tempStr = "Player " + str(winner.playerNO+1) + " wins the game!" textField = self.font0.render(tempStr, True, (255,255,0)) # 画出结果统计文字 self.mainWindow.blit(textField, (self.width/2-textField.get_rect().width/2, self.height/4)) # 画出按钮 self.mainWindow.blit(self.finishedAgainButton, (self.width/4,3*self.height/4)) self.mainWindow.blit(self.finishedQuitButton, (3*self.width/4,3*self.height/4)) for event in pygame.event.get(): # 退出事件 if event.type == QUIT: pygame.quit() sys.exit() # 鼠标左键抬起事件 elif event.type == MOUSEBUTTONUP: # 获取鼠标的位置 mouse_x = pygame.mouse.get_pos()[0] mouse_y = pygame.mouse.get_pos()[1] finishedAgainButtonRect = self.finishedAgainButton.get_rect() finishedQuitButtonRect = self.finishedQuitButton.get_rect() # 检查鼠标点击的位置是否在再来一次按键中 if self.width/4 < mouse_x < self.width/4+finishedAgainButtonRect.width and 3*self.height/4 < mouse_y < 3*self.height/4+finishedAgainButtonRect.height: # 回到玩家数量询问界面 self.state = 1 # 清空玩家列表和玩家数量 self.playersList.clear() self.playersNumber = 0 self.obstacleList.clear() # 检查鼠标点击的位置是否在退出按键中 if 3*self.width/4 < mouse_x < 3*self.width/4+finishedQuitButtonRect.width and 3*self.height/4 < mouse_y < 3*self.height/4+finishedQuitButtonRect.height: pygame.quit() sys.exit() # 刷新屏幕 pygame.display.update()
def update(self): # Game Loop - Update self.ground.update() for player in self.players: player.update() for obs in self.obstacles: obs.update() # determine the next obstacle for i, obs in enumerate(self.obstacles): if obs.rect.right > PLAYER_X: nextObstIndex = i break for x, player in enumerate( self.players ): # give each player a fitness of 0.1 for each frame it stays alive self.myGenomes[x].fitness += 0.1 # Var. for Input layer self.nextObs_dis = player.rect.right - self.obstacles[ nextObstIndex].rect.left self.nextObs_hight = self.obstacles[nextObstIndex].rect.height self.nextObs_width = self.obstacles[nextObstIndex].rect.width self.player_y = player.rect.bottom # send player Y-location, next obstacle distance, next obstacle hight, next obstacle widht # determine from network whether to jump or not output = self.nets[x].activate( (self.player_y, self.nextObs_dis, self.nextObs_hight, self.nextObs_width)) if output[ 0] > 0.5: # i use the tanh activation function so result will be between -1 and 1. if over 0.5 jump player.jump() # check if a player hits the ground - only if falling for player in self.players: if player.velocity.y > 0: hits = pygame.sprite.collide_rect(player, self.ground) # if player hits a ground, put him on the ground if hits: player.pos.y = self.ground.rect.y player.velocity.y = 0 # ckeck if a player hits a obstacle for obs in self.obstacles: if obs.rect.left < PLAYER_X + 30: for i, player in enumerate(self.players): hits = pygame.sprite.collide_rect(player, obs) # if a player collide with an obstacle -> fitness -= 1 # he is also deleted from all lists # bad code!! because deleting something from a iterating list if hits: self.myGenomes[i].fitness -= 1 self.nets.pop(i) self.myGenomes.pop(i) self.players.pop(i) # kill old obstacles and count up score for i, obs in enumerate(self.obstacles): if obs.rect.left < -60: self.score += 10 self.obstacles.pop(i) # gives an player reward for passing through a obstical (not required) for genome in self.myGenomes: genome.fitness += 5 # only spawn new obstacles when the last one is far enough away if self.obstacles[-1].rect.x < 800: self.obstacles.append(Obstacle())
] #find integer value in string format '[ int, int ]' way_x.append(nums[0]) way_y.append(nums[1]) # print("waypoints : (x,y ) = (", way_x,", ", way_y,")") # print("waypoints :way_x) floatregex = re.compile('[-+]?\d*\.\d+|[-+]?\d+') obstacles = [] # list which will contain all obstacles obstacle_coords = np.asarray(obsdf['obstacle'][0:]) # print("obstacle coords") # print(obstacle_coords) for i in range(len(obstacle_coords)): nums = [float(k) for k in floatregex.findall(obstacle_coords[i]) ] #find integer value in string format '[ int, int ]' # print(nums) obs = Obstacle(nums[0] - 1, nums[1] - 1, nums[2], nums[3]) #xmin,ymin, # obs.draw() obstacles.append(obs) # attach obstacle to obstacle list # print("num ofobstacles:", len(obstacles)) print("---load completed") if args['opt'] == 'y': area_size = 12 # window size wp = True # switch for use of waypoints. True: waypoints can be used. False: function deactivated vx_init = [0.0] # initial x-component velocity vy_init = [0.0] # initial y-component velocity T = 152 # maximum time of travel dt = 4. # time step size d_obs = 1.0 # minimum distance required from obstacle M = 75 # number of constraints in order to approximate the force and velocity magnitudes
glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # needed so that egi knows where to draw egi.InitWithPyglet(win) # prep the fps display fps_display = clock.ClockDisplay() # register key and mouse event handlers win.push_handlers(on_key_press) win.push_handlers(on_mouse_press) win.push_handlers(on_resize) # create a world for agents world = World(500, 500) # add one agent world.agents.append(Agent(world)) world.obstacles.append(Obstacle(world)) # unpause the world ready for movement print("Controls: A to add an agent, O to add an object to the map, C to reset objects on the map, P to pause, and I to show direction info.") world.paused = False while not win.has_exit: win.dispatch_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # show nice FPS bottom right (default) delta = clock.tick() world.update(delta) world.render() fps_display.draw() # swap the double buffer win.flip()
veh_coords = [[ 5, 5, -0.7, 6 ]] # array containing all vehicles in [x_0,y_0,x_fin,y_fin] format wp_coords = [[[0, -2], [-5, 4]] ] # array containing all waypoint in [x_wp,y_wp] format name = 'waypoints_obs.png' # name of the figure to be saved folder = 'results/waypoints_obs/' # folder name constrain_multiple_vehicles = False # True: add contraints related to multiple vehicle, False: do not add constrain_waypoints = True # True: add contraints related to waypoints, False: do not add constrain_obstacles = True # True: add contraints related to avoiding obstacles, False: do not add steps = int(T / dt) # number of steps obstacles = [] # list which will contain all obstacles for ob in obs_coords: # for every obstacle tmp = Obstacle(ob[0], ob[1], ob[2], ob[3]) # local obstacle variable tmp.draw() # draw local obstacle obstacles.append(tmp) # attach obstacle to obstacle list # Create initial and final positions num_vehicles = len(veh_coords) x0 = [] y0 = [] # initial positions for all vehicles x_fin = [] y_fin = [] # final positions for all vehicles for i in range(num_vehicles): x0.append(veh_coords[i][0]) y0.append(veh_coords[i][1]) x_fin.append(veh_coords[i][2]) y_fin.append(veh_coords[i][3])
from arena import Arena from obstacle import Obstacle global game_arena game_arena = Arena() # ------------------------------------------------------------------------------------ # Add your obstacles here! # Order: name, list of coords, color, and radius/length & width green_circle = Obstacle("circle", [0, 0], "green", 60) game_arena.add_obstacle(green_circle) green_square = Obstacle("square", [-200, 200], "green", 60) game_arena.add_obstacle(green_square) red_rectangle = Obstacle("rectangle", [0, -200], "red", 60, 100) game_arena.add_obstacle(red_rectangle) game_arena.draw_arena()
def main(stdscr, args): curses.curs_set(0) stdscr.nodelay(1) mh, mw = stdscr.getmaxyx() begin_x = 0 begin_y = 0 if args.canvas_height > mh - begin_y or args.canvas_width > mw - begin_x: raise RuntimeError( "The game can't initialize, please adjust your screen size or change canvas size." ) sh = args.canvas_height #leave space for score sw = args.canvas_width - 10 difference = [[50000, 6], [30000, 5], [20000, 4]] #the speed of generating obsttacles, according to different level speed, div = difference[args.diff_level - 1] obstacle = Obstacle(sw, sh, div) ship = Ship(sh, sw, begin_x, begin_y) stdscr.addstr(ship.location[0], ship.location[1], "*") moveList = [curses.KEY_LEFT, curses.KEY_RIGHT] cob = 0 score = 0 while 1: cob += 1 if cob == speed: score += 1 cob = 0 #add new obstacles stdscr.clear() obstacle.createObstacle() for row in range(len(obstacle.obstacles)): for col in obstacle.obstacles[row]: stdscr.addstr(row, col, "-") #move the ship key = stdscr.getch() if key in moveList: stdscr.addstr(ship.location[0], ship.location[1], " ") ship.move(key) elif key == 27: return #check if collision happens #beacuse the ship and obstacle could meet at the bottom, so just check if collision when the obstacle arrived the bottom if len(obstacle.obstacles) == sh: if not ship.safe(obstacle.obstacles[len(obstacle.obstacles) - 1]): #draw the result stdscr.addstr(ship.location[0], ship.location[1], "x") stdscr.addstr(sh - 1, sw + 3, "score: " + str(score - sh)) stdscr.addstr(sh // 2, sw // 2 - 13, "press any key to continue") stdscr.refresh() stdscr.nodelay(0) stdscr.getch() break stdscr.addstr(ship.location[0], ship.location[1], "*") stdscr.refresh()
def __init__(self, song: pygame.mixer.Sound, song_name): self.song = song self.song_name = song_name self.duration = self.song.get_length() self.array = pygame.sndarray.array(self.song) self.blocks = [] # Find tempo of the song BPM = bpm_finder.getBPM(self.array, self.duration) def adjust_frequency_to_aim(frequency, aim): while frequency < aim * 0.66: frequency *= 2 while frequency > aim * 1.33: frequency /= 2 return frequency blocks_per_sec = adjust_frequency_to_aim(BPM/60., config.BLOCKS_PER_SECOND_AIM) print('Blocks per second: ', blocks_per_sec, 'that\'s', blocks_per_sec*60, 'bpm') # Build map from audio sampler = len(self.array) // (self.duration * blocks_per_sec) # audio samples per block for foo in range(int(self.duration * blocks_per_sec) - 1): self.blocks.append(np.mean(np.abs(self.array[int(foo*sampler):int((foo+1)*sampler-1)]))) self.blocks = np.array(self.blocks) # Normalize blocks minimum = np.quantile(self.blocks, config.MAP_LOWER_QUANTILE) self.blocks -= minimum maximum = np.quantile(self.blocks, config.MAP_UPPER_QUANTILE) self.blocks *= config.HEIGHT_LEVELS/maximum self.blocks = self.blocks.clip(min=0, max=config.HEIGHT_LEVELS) # Clear space at the beginning of the song start_Blocks = int(config.DISP_HEI/config.VELOCITY_X*blocks_per_sec) for i in range(start_Blocks-start_Blocks*2//3): self.blocks[i] = 0 # free plain for i in range(start_Blocks-start_Blocks*2//3, start_Blocks): # ramping up to normal map self.blocks[i] *= float(i)/start_Blocks*3/2-0.5 # Quantize blocks self.blocks = np.round(self.blocks) # Show map in seperate window if config.DEBUG_SHOW_LEVEL: plt.bar(range(len(self.blocks))/blocks_per_sec, self.blocks, width=1/blocks_per_sec) plt.legend() plt.show() # Assign graphical elements to blocks self.obstacles = [] self.color = pygame.color.Color(random.choice(list(colors.neon.values()))) self.colors = [] floor_pos = config.DISP_HEI - config.FLOOR_HEIGHT block_hei = floor_pos / config.HEIGHT_LEVELS * config.RELATIVE_BLOCK_HEIGHT block_wid = config.VELOCITY_X/blocks_per_sec for index, block in enumerate(self.blocks): if block: self.obstacles.append(Obstacle(int(config.PLAYER_POS_X + index*block_wid), floor_pos - block_hei*block, int(block_wid), block_hei*block)) rect_color = int(random.uniform(0, 50)) if random.random() < 0.5: self.colors.append(pygame.Color(self.color) + pygame.color.Color(rect_color, rect_color, rect_color)) else: self.colors.append(pygame.Color(self.color) - pygame.color.Color(rect_color, rect_color, rect_color)) for rect_color in self.colors: if rect_color.a < 255: rect_color.a = 255 # Set gravity to the beat seconds_per_jump = config.JUMP_LENGTH/blocks_per_sec self.jump_speed = 4 * config.JUMP_HEIGHT * block_hei / seconds_per_jump self.gravity = 2 * self.jump_speed / seconds_per_jump
def game(self, genome, config, mode): #Set Mode (0 = Play, 1 = Train) self.mode = mode #Run Speed FPS = 60 if (self.mode == 1): FPS = 200 #Panel Dimensions WIDTH = 288 HEIGHT = 512 running = True paused = False BACKGROUND = pygame.image.load("bg.png") #HELPER VARS--- #Last Obstacle Jumped Over lastObst = None #closest mid point closestMid = 0 botObs = None topObs = None closestX = 0 #NEAT Stuff if (self.mode == 1): fitness = 0 ffnet = neat.nn.FeedForwardNetwork.create(genome, config) pygame.init() CLOCK = pygame.time.Clock() PANEL = pygame.display.set_mode((WIDTH, HEIGHT)) time = 0 #Player Character player = Player(PANEL) #Obstacles obsU1 = Obstacle(PANEL, 300, 256, False) obsL1 = Obstacle(PANEL, 300, 256, True) obsU2 = Obstacle(PANEL, 300 + 200, 160, False) obsL2 = Obstacle(PANEL, 300 + 200, 160, True) #Create List of Obstacles for easy handling obsList = [] obsList.append(obsU1) obsList.append(obsL1) obsList.append(obsU2) obsList.append(obsL2) #Create Group of Sprites for Collision Detection obsGroup = pygame.sprite.Group() myNum = 0 for obs in obsList: obsGroup.add(obs) #Let's also use this time to set the initial midY if (myNum == 0 or myNum == 2): myMid = self.getNewMid() obs.setMidY(myMid) myNum += 1 #Game Loop while running: time += 1 if (self.mode == 1 and not paused): #Get Closest Obs minBotX = 1000 minTopX = 1000 botObs = None topObs = None for obs in obsList: if (obs.top and obs.x < minTopX and obs.x > player.x): topObs = obs minTopX = topObs.x if (not obs.top and obs.x < minBotX and obs.x > player.x): botObs = obs minBotX = botObs.x closestMid = topObs.midY closestX = topObs.x #Direction of mid point direction = 1 if (player.y - closestMid < 0): direction = -1 input = (player.y, topObs.x, closestMid, direction) distanceToMid = abs(player.y - closestMid) fitness = time + myGlobals.SCORE * 10 - distanceToMid #Get Output output = ffnet.activate(input) #Jump if output is above threshold if (output[0] >= 0.5): player.jump() #Get Inputs for event in pygame.event.get(): if (event.type == KEYDOWN): #Player Jump if (event.key == K_SPACE and mode == 0): player.jump() if (event.key == K_TAB and mode == 0): paused = not paused #Close Game With Escape Key if (event.key == K_ESCAPE): self.close() if (not paused): PANEL.blit(BACKGROUND, (0, 0)) myfont = pygame.font.SysFont('Arial', 12) closestMidText = myfont.render("closestMid:" + str(closestMid), False, (0, 0, 0)) xMidText = myfont.render("closestX:" + str(closestX), False, (0, 0, 0)) obsU1Text = myfont.render("obsU1.x:" + str(obsU1.x), False, (0, 0, 0)) PANEL.blit(closestMidText, (20, 20)) PANEL.blit(xMidText, (20, 40)) PANEL.blit(obsU1Text, (20, 60)) player.step() myMid = self.getNewMid() for obs in obsList: obs.step() #Reset Obs if (obs.x < 0 - obs.w): obs.x = obs.x + WIDTH * 1.5 obs.setMidY(myMid) #Up Score if (obs.top and obs.x < player.x and lastObst != obs): myGlobals.SCORE += 10 lastObst = obs print('---SCORE: ' + str(myGlobals.SCORE)) #Check Collision collision = pygame.sprite.spritecollideany(player, obsGroup) #Game Over Conditions if (collision != None or player.y <= 0 or player.y >= HEIGHT): if (self.mode == 0): print("GAME OVER") self.close() if (self.mode == 1): return fitness pygame.display.update() CLOCK.tick(FPS)
def add(self): obstacle = Obstacle(self.screen, self.window_size) obstacle.gen_random_parameters_from_bottom() self.collection.append(obstacle)
def generateObstacles(self): if len(self.obstacles) > 20: self.obstacles = self.obstacles[9:] obstacle = Obstacle(self.images) self.obstacles.append(obstacle) return obstacle
def main(): pg.init() pg.display.set_caption("Swarm") # CONFIG width = 1200 height = 700 clock = pg.time.Clock() num_boids = 10 screen = pg.display.set_mode((width, height)) background = pg.Surface(screen.get_size()).convert() background.fill((0, 0, 0)) running = True #pg.event.set_allowed([pg.QUIT, pg.KEYDOWN, pg.KEYUP]) all_sprites = pg.sprite.RenderUpdates() obs_sprites = pg.sprite.RenderUpdates() boids = [Boid(i) for i in range(num_boids)] obs = [] globalvariables.target.append(Targetpoint((width - 50, height - 50))) '''obstacles''' for i in range(0, int(height / 4), 5): obs.append(Obstacle([0, i])) for i in range(int(3 * height / 4), height, 5): obs.append(Obstacle([width, i])) for i in range(0, int(width / 4), 5): obs.append(Obstacle([i, 0])) for i in range(int(3 * width / 4), width, 5): obs.append(Obstacle([i, height])) if len(sys.argv) > 1: for i in [ int(1.5 * height / 4), int(1.70 * height / 4), int(2.30 * height / 4), int(2.5 * height / 4) ]: for j in range(int(1.5 * width / 4), int(2.5 * width / 4), 5): obs.append(Obstacle([j, i])) for i in [ int(1.5 * width / 4), int(1.5 * width / 4 + 2), int(2.5 * width / 4), int(2.5 * width / 4 + 2) ]: for j in range(int(1.5 * height / 4), int(1.70 * height / 4), 5): obs.append(Obstacle([i, j])) for j in range(int(2.30 * height / 4), int(2.5 * height / 4), 5): obs.append(Obstacle([i, j])) for boid in boids: all_sprites.add(boid) for ob in obs: obs_sprites.add(ob) ################################################################################### frame_count = 0 fail_count = 0 averdist = 0 filewriter = open('scenario2_no_ob.csv', 'a') if len(sys.argv) > 1: filewriter.close() filewriter = open('scenario2.csv', 'a') vel_breakdown_filewriter = open('scenario2_breakdown.csv', 'a') b0 = boids[2] while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False if event.type == pg.MOUSEBUTTONDOWN and event.button == 1: pos = pg.mouse.get_pos() globalvariables.point = pg.math.Vector2(pos[0], pos[1]) globalvariables.target.append(Targetpoint(pos)) globalvariables.click = 1 if pg.mouse.get_pressed()[2]: pos = pg.mouse.get_pos() obs.append(Obstacle(pos)) obs_sprites.add(Obstacle(pos)) if event.type == pg.KEYDOWN and event.key == pg.K_UP: boids.append(Boid(0)) all_sprites.add(boids[len(boids) - 1]) if event.type == pg.KEYDOWN and event.key == pg.K_DOWN: boid = boids.pop(len(boids) - 1) all_sprites.remove(boid) ################################################################## for b in boids: if b.checktarget() == True: boids.remove(b) all_sprites.remove(b) elif b.checkcolision_ob(obs) == True: boids.remove(b) all_sprites.remove(b) fail_count += 1 elif frame_count >= 50 and b.checkcolision_neigh(boids) == True: boids.remove(b) all_sprites.remove(b) fail_count += 1 for b1 in boids: if b1.checkcolision_neigh([b]) == True: boids.remove(b1) all_sprites.remove(b1) fail_count += 1 else: stat = b.update(boids, obs) if b0.id == b.id: if len(sys.argv) > 1: vel_breakdown_filewriter.write( '%f,%f,%f,%f,%f\n' % (stat[0], stat[1], stat[2], stat[3], stat[4])) averdist += averagedistance.AverageDistancePerFrame(boids) # if frame_count% 50 ==0: # print(len(boids)) if len(boids) == 0: print("average distance: " + str(averdist / frame_count)) filewriter.write('%f,%d\n' % ((averdist / frame_count), fail_count)) fail_count = 0 frame_count = 0 averdist = 0 # time.sleep(3) boids = [Boid(i) for i in range(num_boids)] for boid in boids: all_sprites.add(boid) b0 = boids[2] # globalvariables.target_sprites = pg.sprite.RenderUpdates(globalvariables.target) # all_sprites.clear(screen, background) # all_sprites.update(boids,obs) # dirty = all_sprites.draw(screen) # pg.display.update(dirty) # dirty1 = obs_sprites.draw(screen) # pg.display.update(dirty1) # globalvariables.target_sprites.clear(screen, background) # dirty2 = globalvariables.target_sprites.draw(screen) # pg.display.update(dirty2) frame_count += 1
def main(): # Function for running the program. pygame.init() # Initialize pygame. screen_size = [P.SCREEN_WIDTH, P.SCREEN_HEIGHT] # Defines screen area. screen = pygame.display.set_mode(screen_size) # Represents the screen. background_image = pygame.image.load("pics/background.png") background_image = pygame.transform.scale( background_image, (P.SCREEN_WIDTH, P.SCREEN_HEIGHT)) pygame.display.set_caption("Boids n' hoiks") font = pygame.font.Font('freesansbold.ttf', 32) icon = pygame.image.load("pics/reddit.png") pygame.display.set_icon(icon) running = True time = pygame.time.Clock() flock = [] # Lists hoikers = [] obstacles = [] while running: for event in pygame.event.get(): # Game loop initialize. if event.type == pygame.QUIT: running = False if event.type == MOUSEBUTTONDOWN and event.button == 1: # When left button is clicked boid = Boid() flock.append(boid) # Adds boid if event.type == MOUSEBUTTONDOWN and event.button == 3: # When right button is clicked hoik = Hoik() hoikers.append(hoik) # Adds hoik if event.type == MOUSEBUTTONDOWN and event.button == 2: # When scrool button is clicked asteroid = Obstacle() obstacles.append(asteroid) # Adds obstacle key = pygame.key.get_pressed() if key[pygame.K_ESCAPE]: running = False if key[pygame. K_LEFT]: # If left button is pressed, all lists are cleared flock.clear() hoikers.clear() obstacles.clear() screen.blit(background_image, (0, 0)) # Draws background. for boid in flock: # Updates boids boid.update(flock, obstacles) for hoik in hoikers: # Updates hoiks hoik.update(flock, obstacles) for asteroid in obstacles: # Updates asteroids asteroid.update() time.tick(60) # Computes how many ms have passed # since prev call, game wont run # higher than 60 fps/ticks. pygame.display.flip() # Updates surface area pygame.quit()