def onDrawFunnelsButton(self, change=True): if change == True: self.funnel_number_x = self.funnel_number_x + 1 if self.funnel_number_x == 5: self.funnel_number_x = 0 self.funnel_number_y = self.funnel_number_y + 1 if self.funnel_number_y == 5: self.funnel_number_y = 0 print "I pressed the draw funnels button" variance_x = 1.5 + abs(self.XVelocity_drawing*0.1) variance_y = 1.5 + abs(self.YVelocity_drawing*0.1) variance_z = 0.2 self.ActionSet.computeAllPositions(self.XVelocity_drawing,self.YVelocity_drawing) print np.shape(self.ActionSet.p_x_trajectories), "is my shape" for i in xrange(np.size(self.ActionSet.p_x_trajectories,1)): print i x_center = self.ActionSet.p_x_trajectories[self.funnel_number_x,i] y_center = self.ActionSet.p_y_trajectories[self.funnel_number_y,i] print x_center, y_center World.buildEllipse(i, [x_center,y_center,0], variance_x*i/10.0*0.5, variance_y*i/10.0*0.5, variance_z, alpha=0.3)
def test(): the_map = Map() tic = time.clock() the_map.discretize_map() print time.clock() - tic #obstacle = Polygon([(40,15), (45,15), (45,20), (40,20)], safety_region_length=4.0) #the_map.add_obstacles([obstacle]) tend = 10 dT = 1 h = 0.05 N = int(tend/h) + 1 N2 = int(tend/dT) + 1 x0 = np.array([10, 10, 0.0, 3.0, 0, 0]) xg = np.array([50, 50, 0]) myDynWnd = DynamicWindow(dT, N2) v = Vessel(x0, xg, h, dT, N, [myDynWnd], is_main_vessel=True, vesseltype='viknes') v.current_goal = np.array([50, 50]) world = World([v], the_map) myDynWnd.the_world = world world.update_world(0,0) fig = plt.figure() ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-10, 160), ylim=(-10, 160)) world.visualize(ax, 0, 0) plt.show()
def setup_world(): w = World() w.sim = PhysicsSimulator( timestep = None ) block = QuadBlock(32) bs = BlockStructure(block) thing = Thing( w, bs.create_collision_shape(), 1.0, 1.0 ) return block, thing
def greedy(world): initial_world = World(world) global solver cmds = '' while not world.terminated: if len(cmds) > 10000: break #print cmds t = utils.path_to_nearest_lambda_or_lift(world) if t is None: break _, c = t #print c world = world.apply_commands(c) cmds += c if world.score > solver.best_score: solver.best_score = world.score solver.best_solution = cmds print 'greedy', solver.best_score, len(solver.best_solution) if initial_world.apply_commands(cmds).score < 0: solver.best_score = 0 solver.best_solution = '' print 'shit!'
def __init__(self, world_map, multiplayer): World.__init__(self, world_map, multiplayer) self._create_sprites() self.brick_energy() self.set_bounds_energy() self.set_dynamics_energy() self._set_walls()
class Game(object): def __init__(self): pygame.init() self.caption = "Zelda Love Candy" self.resolution = (640, 480) self.screen = pygame.display.set_mode(self.resolution) pygame.display.set_caption(self.caption) self.clock = pygame.time.Clock() self.isGameOver = False self.world = World() def update(self): """overide this to add neccessary update """ self.world.update() self.world.render(self.screen) def start(self): """ start the game """ while not self.isGameOver: self.clock.tick(30) for events in pygame.event.get(): if events.type == pygame.QUIT: self.isGameOver = True self.update() pygame.display.flip() pygame.quit()
def redrawFunnelsButton(self, change=True): if self.funnels_toggle: variance_x = 1.5 + abs(self.XVelocity_drawing*0.1) variance_y = 1.5 + abs(self.YVelocity_drawing*0.1) variance_z = 1.5 + abs(self.ZVelocity_drawing*0.1) #self.ActionSet.computeAllPositions(self.XVelocity_drawing,self.YVelocity_drawing,self.ZVelocity_drawing) #find almost equally spaced indexes indices_to_draw = np.zeros(10) indices_to_draw[0] = 0 next_time = 0 + self.ActionSet.t_f/10.0 number = 0 for index, value in enumerate(self.ActionSet.overall_t_vector): if value > next_time: indices_to_draw[number] = index number = number + 1 next_time = next_time + self.ActionSet.t_f/10.0 for index, value in enumerate(indices_to_draw): time = self.ActionSet.overall_t_vector[value] x_center = self.ActionSet.pos_trajectories[self.funnel_number,0,value] y_center = self.ActionSet.pos_trajectories[self.funnel_number,1,value] z_center = self.ActionSet.pos_trajectories[self.funnel_number,2,value] World.buildEllipse(index, [x_center,y_center,z_center], variance_x*time, variance_y*time, variance_z*time, alpha=0.3)
class MainGameState(object): def __init__(self): self.background = backgrounds.Cave() self.world = World() self.player = Player(self.world, (-100, 52.4)) self.camera = Camera((0, 100.0), tracking=self.player) def update(self, delta): for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) elif event.type == KEYDOWN: if event.key == K_ESCAPE: raise states.StateChange(states.PauseMenuState(self)) self.world.center = self.player.pos self.background.update(delta) self.world.update(delta) self.player.update(delta) self.camera.update(delta) def render(self, screen): self.background.render(screen, self.camera) self.world.render(screen, self.camera) self.player.render(screen, self.camera)
def onBuildWorldFromRandomObstacles(self): distances = self.Sensor.raycastAll(self.frame) firstRaycastLocations = self.Sensor.invertRaycastsToLocations(self.frame, distances) self.LineSegmentWorld = World.buildLineSegmentWorld(firstRaycastLocations) self.LineSegmentLocator = World.buildCellLocator(self.LineSegmentWorld.visObj.polyData) self.Sensor.setLocator(self.LineSegmentLocator) self.updateDrawIntersection(self.frame)
def onAddAccelSphereButton(self): self.AccelSphere_toggle = not self.AccelSphere_toggle if not self.AccelSphere_toggle: self.AccelSphere = World.buildAccelSphere([self.XVelocity_drawing*self.ActionSet.t_f,self.YVelocity_drawing*self.ActionSet.t_f,self.ZVelocity_drawing*self.ActionSet.t_f], a_max=0.0) self.AccelArrow = World.buildAccelArrow([0,0,0], 0.0+9.8, 0.0, 0.0) else: self.redrawAccelSphere()
def compile(self, candidate): world = World(self.world) compiled = [] for gene in candidate.genes: gene_type, gene_value = gene if gene_type == 'wait': world = world.apply_command('W') compiled.append('W') if world.terminated: break elif gene_type == 'move': destination = gene_value commands = pathfinder.commands_to_reach(world, destination) for c in commands: direction = [-world.width, world.width, -1, 1, 0]['UDLRA'.index(c)] if world.data[world.robot + direction] == 'W' and world.razors > 0: world = world.apply_command('S') compiled.append('S') if world.terminated: break world = world.apply_command(c) compiled.append(c) if world.terminated: break else: assert False, "Unrecognized gene: %s" % gene_type if world.terminated: break if not world.terminated: compiled.append('A') return ''.join(compiled)
def cleanup(): world = World(None) conn = sqlite3.connect(DB_PATH) query = 'select x, y, z from block order by rowid desc limit 1;' last = list(conn.execute(query))[0] query = 'select distinct p, q from block;' chunks = list(conn.execute(query)) count = 0 total = 0 delete_query = 'delete from block where x = %d and y = %d and z = %d;' print 'begin;' for p, q in chunks: chunk = world.create_chunk(p, q) query = 'select x, y, z, w from block where p = :p and q = :q;' rows = conn.execute(query, {'p': p, 'q': q}) for x, y, z, w in rows: if chunked(x) != p or chunked(z) != q: continue total += 1 if (x, y, z) == last: continue original = chunk.get((x, y, z), 0) if w == original or original in INDESTRUCTIBLE_ITEMS: count += 1 print delete_query % (x, y, z) conn.close() print 'commit;' print >> sys.stderr, '%d of %d blocks will be cleaned up' % (count, total)
def main(): # Construct the objects that will run the game. courier = Courier() world = World(courier) gui = Gui(courier, world) systems = [courier, world, gui] # Connect to the server and wait until the game is ready to begin. courier.setup() courier.login(world.setup) # Open up a window and get ready to start playing. clock = pygame.time.Clock() frequency = 40 gui.setup() # Play the game! while world.still_playing(): time = clock.tick(frequency) / 1000 for system in systems: system.update(time) # Exit gracefully. for system in systems: system.teardown()
class ExploreScreen(GameScreen): def __init__(self, app): GameScreen.__init__(self, app) utilities.setApp(self.app) self.world = World(10) self.app.taskMgr.add(self.update, "update") self.app.accept("a", self.world.player.moveLeft, [True]) self.app.accept("a-up", self.world.player.moveLeft, [False]) self.app.accept("d", self.world.player.moveRight, [True]) self.app.accept("d-up", self.world.player.moveRight, [False]) self.app.accept("space", self.world.player.jump, [True]) self.app.accept("space-up", self.world.player.jump, [False]) self.app.accept("c", self.world.player.crouch, [True]) self.app.accept("c-up", self.world.player.crouch, [False]) self.app.accept("mouse1", self.world.player.activate, []) self.app.accept("escape", sys.exit, []) #self.app.accept("h", self.showDBG, [True]) #self.app.accept("h-up", self.showDBG, [False]) self.prevTime = 0 self.app.mousePos = Point2() self.app.disableMouse() self.app.rl = base.camLens.makeCopy() #bullet testing #debugNode = BulletDebugNode('Debug') #debugNode.showWireframe(True) #debugNode.showConstraints(True) #debugNode.showBoundingBoxes(False) #debugNode.showNormals(False) #self.debugNP = render.attachNewNode(debugNode) #self.debugNP.show() #self.world.bw.setDebugNode(self.debugNP.node()) def update(self, task): delta = task.time - self.prevTime self.prevTime = task.time if(self.app.mouseWatcherNode.hasMouse()): self.app.mousePos.x = self.app.mouseWatcherNode.getMouseX() self.app.mousePos.y = self.app.mouseWatcherNode.getMouseY() self.world.update(delta) return Task.cont
def main(): parser = argparse.ArgumentParser( description="Compute the optimal path using A*" ) group = parser.add_mutually_exclusive_group() group.add_argument( "-w", "--world", help="The filename of the world to load", ) group.add_argument( "-s", "--size", type=int, help="Size of the random board to be generated" ) parser.add_argument( "-f", "--file", help="The file to output the world to" ) parser.add_argument( "heuristic", type=int, help="The heuristic number to run (in range(1, 7))" ) args = parser.parse_args() if args.world: newWorld = World(filepath=args.world) elif args.size: newWorld = World(height=args.size, width=args.size) else: newWorld = World(height=10, width=10) if args.file: newWorld.write_world(args.file) astar = AStar(newWorld, args.heuristic) astar.start()
class Simulation(): """The simulation class executes the simulation. Upon initialization it creates the system - the world, sun, oceans etc. The step function proceeds forwards in time. """ def __init__(self): """Create the simulation.""" log("> Creating world") self.create_world() log("> Creating sun") self.create_sun() def create_world(self): """Create the world.""" self.world = World() def create_sun(self): """Create the sun.""" self.sun = Sun() def step(self): """Advance 1 time step.""" self.world.slosh_oceans() self.world.transfer_energy_vertically() self.world.transfer_energy_horizontally() self.world.absorb_energy_from_core() self.world.absorb_energy_from_sun(self.sun)
def main(world_size, slowness): world = World(world_size) game = world.go() print('New world was born') for m in world.monsters: print(event_message(('spawn', m, m.coord, None))) try: for step in game: was_event = False for event in step: if event: was_event = True print(event_message(event)) time.sleep(slowness) if world.move_number == 0 or was_event: print(coord_line(world)) print('{}) {}'.format(world.move_number, world)) time.sleep(slowness) except KeyboardInterrupt: print(world.stat.get_stat()) sys.exit(1) if world.monsters: winner = world.monsters.pop() print('Finished! Last hero is {}'.format(winner.name)) print(text_winner(winner)) else: print('Finished. No one survived') print('Enter or any command to see game statistics.') input() print(world.stat.get_stat())
class InfiniteQuestWindow(QMainWindow): # ---------------------------------------------------------------------- def __init__(self): """""" super(InfiniteQuestWindow, self).__init__() self.setWindowTitle("Infinite Quest") self.mapview = MapView() # self.mapview = QGraphicsView() # self.sc = MapScene() # self.mapview.setScene(self.sc) self.mapview.installEventFilter(self) self.setCentralWidget(self.mapview) self.minimap = MiniMapView(self.mapview) minimap_dw = QDockWidget() minimap_dw.setWidget(self.minimap) self.addDockWidget(Qt.LeftDockWidgetArea, minimap_dw) self.statushero = StatusHeroWidget() statushero_dw = QDockWidget() statushero_dw.setWidget(self.statushero) self.addDockWidget(Qt.LeftDockWidgetArea, statushero_dw) # self.mapview.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding)) self.world = World() self.hero = Hero(self.world.map(), *self.world.map().find_passable_landscape_coords()) self.connection = Connection(self.hero, self.world) self.game_state_update() # ---------------------------------------------------------------------- def game_state_update(self): """""" st = self.connection.get_world_state() self.mapview.scene.mapstate_update(st["map_state"]) # ---------------------------------------------------------------------- def eventFilter(self, obj, ev): """""" if ev.type() == QEvent.KeyPress: try: self.connection.action( { Qt.Key_Up: "move_up", Qt.Key_Down: "move_down", Qt.Key_Right: "move_right", Qt.Key_Left: "move_left", }[ev.key()] ) self.game_state_update() return True except KeyError: pass else: pass return super(InfiniteQuestWindow, self).eventFilter(obj, ev)
def init_placement(self, creature_type): for x in range(World.get_max_x(self.inst_of_world)): for y in range(World.get_max_y(self.inst_of_world)): if World.get_xy(self.inst_of_world, x, y) is None: World.set_xy(self.inst_of_world, x, y, creature_type) self.current_position_x = x self.current_position_y = y return
def simulate(living,nticks=None, max_bush_count=None, max_red_bush_count=None): """Used to run a simulation, placed outside of class to enable multiprocessing""" creatures = living[0] predators = living[1] w = World(gene_pool_creatures=creatures, gene_pool_predators=predators, nticks=nticks,max_bush_count=max_bush_count,max_red_bush_count=max_red_bush_count) w.run_ticks() return (w.get_creatures(), w.get_predators())
class ServerPregame (Engine): """ Sets up the world and creates client identities then sends both to each client. Eventually allow for users to modify the initial world settings plus personalizations like name or color. """ # Constructor {{{1 def __init__ (self, loop, server): print 'S: Begin pregame.' Engine.__init__(self,loop) self.server = server self.world = World() self.conversations = [] # Setup {{{1 def setup (self): pipes = self.server.get_pipes() # Create identities for the World. human_identities = range(len(pipes)) #ai_identities = self.create_ai_identities() #player_identities = human_identities + ai_identities target_identities = range(game_settings.target_count) print 'Human identites: ', human_identities # Create the world. self.world.setup(human_identities, target_identities) #self.world.setup(player_identities, target_identities) # Prepare to send info to the clients. for identity in human_identities: pipe = pipes[identity] setup_world = SetupWorld(self.world, identity) self.conversations.append(SimpleSend(pipe, setup_world)) # Start the conversations. for conversation in self.conversations: conversation.start() # Update, Callbacks, and Methods {{{1 def update(self, time): active_conversations = [] for conversation in self.conversations: if not conversation.finished(): active_conversations.append(conversation) conversation.update() if active_conversations: self.conversations = active_conversations else: self.exit_engine() def successor (self): pipes = self.server.get_pipes() forum = Forum(*pipes, safe=False) return ServerGame(self.loop, forum, self.world) def teardown(self): pass
def world(self): world = World( self.name, self.width, self.height, self.seed, self.n_plates, self.ocean_level, Step.get_by_name("plates") ) hm = platec.get_heightmap(self.p) pm = platec.get_platesmap(self.p) world.set_elevation(array_to_matrix(hm, self.width, self.height), None) world.set_plates(array_to_matrix(pm, self.width, self.height)) return world
def __init__ (self, scheduler, evthandler, sfc, player = None): self.player = player World.__init__(self, scheduler, evthandler) evthandler.add_event_handlers({pg.JOYBUTTONDOWN: self._joycb}) evthandler.add_key_handlers([ (conf.KEYS_BACK, lambda *args: conf.GAME.quit_world(), eh.MODE_ONDOWN), (conf.KEYS_QUIT, lambda *args: conf.GAME.quit_world(2), eh.MODE_ONDOWN) ]) self.graphics.add(gm.Graphic(sfc), gm.Colour((0, 0, 0, 180), ((0, 0), conf.RES), -1))
def init(self): # create 9 worlds and collect them for i in xrange(0,9): newWorld = World() newWorld.init(i) self.worlds.append(newWorld) # grab first 3 worlds self.visibleWorlds = self.worlds[:3]
def onDrawFunnelsButton(self): self.funnels_toggle = not self.funnels_toggle if self.funnels_toggle: self.onDrawActionSetButton() if not self.funnels_toggle: for i in xrange(0,10): x_center = self.ActionSet.pos_trajectories[self.funnel_number,0,i] y_center = self.ActionSet.pos_trajectories[self.funnel_number,1,i] z_center = self.ActionSet.pos_trajectories[self.funnel_number,2,i] World.buildEllipse(i, [x_center,y_center,z_center], 0.0, 0.0, 0.0, alpha=0.3)
def test_reshape_early(): w = World() w.sim = physics.PhysicsSimulator( timestep = None ) a = QuadBlock(32) b = QuadBlock(35) thing = physics.Thing( w, BlockStructure(a).create_collision_shape(), 1.0, 1.0 ) assert thing.abstract_shape.area() == a.area() thing.reshape( BlockStructure(b).create_collision_shape() ) assert thing.abstract_shape.area() == b.area() w.sim.perform_removals_and_additions()
def run(): WIDTH = 640 HEIGHT = 480 running = True clock = pygame.time.Clock() screen = pygame.display.set_mode( (WIDTH,HEIGHT) ) w = World() c = Camera(screen, (0,0), 3.0, HEIGHT) c.set_world(w) b = BallEntity((100,100), {'radius': 10, 'density': 10, 'restitution': 0.1, 'static': True, 'line-width': 5}) w.add_entity(b) b2 = BallEntity((100,60), {'radius': 20, 'density': 100, 'restitution': 1.0}) w.add_entity(b2) b2.body.SetLinearVelocity((0,40)) base = BoxEntity((20,20), {'width': 100, 'height': 10})#, 'static': True}) w.add_entity(base) while running: screen.fill((255,255,255)) c.draw() pygame.display.flip() w.step(dt) clock.tick(hz)
def __init__(self): self.worlds = [] for i in xrange(3): world = World('world%d' %i, self) world.run('../server/maps/world_server.json') self.worlds.append(world) application = Application([ ('/', Connection, {'gameserver': self}), ]) http_server = HTTPServer(application) http_server.listen(8000)
def onRandomObstaclesButton(self): print "random obstacles button pressed" self.setInitialStateAtZero() self.world = World.buildLineSegmentTestWorld(percentObsDensity=8.0, circleRadius=self.options['World']['circleRadius'], nonRandom=False, scale=self.options['World']['scale'], randomSeed=self.options['World']['randomSeed'], obstaclesInnerFraction=self.options['World']['obstaclesInnerFraction']) self.locator = World.buildCellLocator(self.world.visObj.polyData)
def _plates_simulation(name, width, height, seed, num_plates=10, ocean_level=1.0, step=Step.full(), verbose=get_verbose()): e_as_array, p_as_array = generate_plates_simulation(seed, width, height, num_plates=num_plates, verbose=verbose) world = World(name, width, height, seed, num_plates, ocean_level, step) world.set_elevation(array_to_matrix(e_as_array, width, height), None) world.set_plates(array_to_matrix(p_as_array, width, height)) return world
def display(self): c = True while c != 27: # self.config.GUI() if self.world_latest is None: w = World() else: self.world_previous = self.world_latest w = World(self.world_latest) preprocessed = self.getPreprocessed() frame = preprocessed['frame'] height, width, dim = frame.shape frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) q = Queue() # note hte potential to detect in threads and then join back! #print("track ball") self.tracker_ball.find(frame_hsv, q) #print("track blue") self.tracker_blue.find(frame_hsv, q) #print("track yellow") self.tracker_yellow.find(frame_hsv, q) while not q.empty(): item = q.get_nowait() #print(item) if item is None: continue x, y = item['x'], item['y'] if item['name'] == "ball": if self.world_previous is not None and self.world_previous.ball is not None: angle = math.atan2(y - self.world_previous.ball.y, x - self.world_previous.ball.x) distance = sp_dist.euclidean( (x, y), (self.world_previous.ball.x, self.world_previous.ball.y)) t = w.time - self.world_previous.time # print time.time(), w.time, self.world_previous.time velocity = distance / t / 10 else: angle = 0 velocity = 0 while angle > 2 * math.pi: angle -= math.pi while angle < 0: angle += math.pi w.ball = Vector(x, y, angle, velocity) elif "robot" in item['name']: if item['orientation'] is None: rad = 0 dis = 0 else: rad = math.radians(item["orientation"] % 360) dis = 1 if item['colour'] == 'blue': if item['identification'] == 'green': w.robot_blue_green = Vector(x, y, rad, dis) if w.ball != None and (abs(w.ball.x - x) <= 10 and abs(w.ball.y - y) <= 10): w.ball = self.world_previous.ball elif item['identification'] == 'pink': w.robot_blue_pink = Vector(x, y, rad, dis) if w.ball != None and (abs(w.ball.x - x) <= 10 and abs(w.ball.y - y) <= 10): w.ball = self.world_previous.ball if item['colour'] == 'yellow': if item['identification'] == 'green': w.robot_yellow_green = Vector(x, y, rad, dis) if w.ball != None and (abs(w.ball.x - x) <= 10 and abs(w.ball.y - y) <= 10): w.ball = self.world_previous.ball elif item['identification'] == 'pink': w.robot_yellow_pink = Vector(x, y, rad, dis) if w.ball != None and (abs(w.ball.x - x) <= 10 and abs(w.ball.y - y) <= 10): w.ball = self.world_previous.ball # quit() self.world_latest = w # found items will be stored in the queue, and accessed if/when drawing the overlay for name in self.config.filter_stack: filter = self.config.filters[name] if filter["option"].selected: frame = filter["function"](frame) cv2.imshow(name, frame) #else: #print("Filter stack does not agree with activated filters") cv2.imshow(self.config.OUTPUT_TITLE, frame) cv2.setMouseCallback( self.config.OUTPUT_TITLE, lambda event, x, y, flags, param: self.p( event, x, y, flags, param, frame_hsv)) c = cv2.waitKey(50) & 0xFF planner_w = copy.deepcopy(w) if planner_w.ball != None: planner_w.ball.y = height - planner_w.ball.y if planner_w.robot_yellow_green != None: planner_w.robot_yellow_green.y = height - planner_w.robot_yellow_green.y planner_w.robot_yellow_green.angle = ( pi / 2 - planner_w.robot_yellow_green.angle) % (2 * pi) if planner_w.robot_yellow_pink != None: planner_w.robot_yellow_pink.y = height - planner_w.robot_yellow_pink.y planner_w.robot_yellow_pink.angle = ( pi / 2 - planner_w.robot_yellow_pink.angle) % (2 * pi) if planner_w.robot_blue_green != None: planner_w.robot_blue_green.y = height - planner_w.robot_blue_green.y planner_w.robot_blue_green.angle = ( pi / 2 - planner_w.robot_blue_green.angle) % (2 * pi) if planner_w.robot_blue_pink != None: planner_w.robot_blue_pink.y = height - planner_w.robot_blue_pink.y planner_w.robot_blue_pink.angle = ( pi / 2 - planner_w.robot_blue_pink.angle) % (2 * pi) # print(planner_w.__dict__) self.planner_callback(planner_w) else: cv2.destroyAllWindows()
def main(): w = World(5, 5, [(0, 0, 5), (2, 2, 5), (4, 4, 5)], [(0, 4, 5), (2, 4, 5), (0, 2, 5)], -1, 15, 15) a = Agent(1, 1) manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(4000, p_greedy)], filename="Experiment1_1.txt") manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(4000, p_greedy)], filename="Experiment1_2.txt") manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment2_1.txt") manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment2_2.txt") manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment3_1.txt") manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment3_2.txt") manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 1.0, p_random, 8000, [(200, p_exploit)], filename="Experiment4_1.txt") manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 1.0, p_random, 8000, [(200, p_exploit)], filename="Experiment4_2.txt") manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], swap_after_iter=2, filename="Experiment5_1.txt") manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], swap_after_iter=2, filename="Experiment5_2.txt") manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(4000, p_greedy)], filename="Experiment1_SmallStatespace_1.txt", state_space='small') manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(4000, p_greedy)], filename="Experiment1_SmallStatespace_2.txt", state_space='small') manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment2_SmallStatespace_1.txt", state_space='small') manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment2_SmallStatespace_2.txt", state_space='small') manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment3_SmallStatespace_1.txt", state_space='small') manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], filename="Experiment3_SmallStatespace_2.txt", state_space='small') manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 1.0, p_random, 8000, [(200, p_exploit)], filename="Experiment4_SmallStatespace_1.txt", state_space='small') manager(deepcopy(w), deepcopy(a), SARSA, 0.3, 1.0, p_random, 8000, [(200, p_exploit)], filename="Experiment4_SmallStatespace_2.txt", state_space='small') manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], swap_after_iter=2, filename="Experiment5_SmallStatespace_1.txt", state_space='small') manager(deepcopy(w), deepcopy(a), q_learning, 0.3, 0.5, p_random, 8000, [(200, p_exploit)], swap_after_iter=2, filename="Experiment5_SmallStatespace_2.txt", state_space='small')
def __init__(self, video_port=0, pitch=None, planner_callback=None): self.config = Config(self) while pitch is None: req_room = raw_input("Enter Pitch Room [{opts}]: ".format( opts="/".join(self.config.pitch_room.options))) pitch_no = self.config.pitch_room.getCode( req_room, unifier=lambda str: re.sub(r'\W+', '', str.upper())) if pitch_no is not None: pitch = pitch_no self.config.pitch_room.selected = pitch if pitch == 0: self.config.colours = colour_profiles['pitch_3d03'] elif pitch == 1: self.config.colours = colour_profiles['pitch_3d04'] self.cam = Camera(port=video_port, pitch=pitch, config=self.config) #print("Camera initialised") def print_function(x): info(x) if planner_callback is None: self.planner_callback = (lambda x: print_function(x)) else: self.planner_callback = planner_callback c = Calibrate(self.cam, self.config) self.world_latest = World() self.world_previous = None # c.run(True) print("Basic camera calibration complete") colours = c.calibrateColor(self.cam) all_colors = np.empty([10, 3], dtype=np.uint8) color_id = 0 if colours is not None: for colour, data in colours.iteritems(): if data is not None: for field in data: self.config.colours[colour][field] = np.uint8( data[field]) all_colors[color_id] = np.uint8(data[field]) color_id += 1 print("Colors recorded") np.save("color_calibrations", all_colors) else: print("Colors calibration skipped") all_colors = np.load("color_calibrations.npy") all_color_names = ['red', 'yellow', 'blue', 'green', 'pink'] for i in range(0, 5): self.config.colours[all_color_names[i]]['max'] = all_colors[i * 2] self.config.colours[all_color_names[i]]['min'] = all_colors[i * 2 + 1] # print all_color_names[i], all_colors[i*2+1], all_colors[i*2] self.config.addFilter("overlay", filters.filter_overlay, default=1) self.config.addFilter("grayscale", filters.filter_grayscale) self.config.addFilter("normalised", filters.filter_normalize) self.config.addFilter("red", partial(filters.filter_colour, "red")) self.config.addFilter("yellow", partial(filters.filter_colour, "yellow")) self.config.addFilter("blue", partial(filters.filter_colour, "blue")) self.config.addFilter("green", partial(filters.filter_colour, "green")) self.config.addFilter("pink", partial(filters.filter_colour, "pink")) self.config.addFilter("manual colour", partial(filters.filter_colour, None)) #print("Filters set up") #print("Initialising trackers") self.tracker_ball = DotTracker(0, 0, 'red', self.config, "ball") self.tracker_blue = DotTracker(0, 0, 'yellow', self.config, "robot") self.tracker_yellow = DotTracker(0, 0, 'blue', self.config, "robot") self.config.GUI() self.display()
def __init__(self, aPlayer): self.thePlayer = aPlayer self.theWorld = World()
class Run( ): def __init__( self ): if debug: self.size = ( 900, 700 ) self.scr = p.display.set_mode( self.size ) else: self.size = ( 1920, 1080 ) self.scr = p.display.set_mode( self.size, FULLSCREEN ) strings = ( " .... ", " .xxxx. ", " .xxxx. ", " .xx xx. ", " .xx xx. ", " .xx xx. ", " .xx xx. ", " .xx xx. ", " .xx xx. ", " .xx xx. ", " .xx xx. ", ".xx xx.", ".xx xx.", ".xxxxxxxxxxxxxx.", " .xxxxxxxxxxxx. ", " .............. ", ) data, mask = p.cursors.compile( strings, 'x', '.', 'o' ) p.mouse.set_cursor( ( 16, 16 ), ( 0, 0 ), data, mask ) #p.mouse.set_cursor( *p.cursors.ball ) self.world = World( self ) self.active = True self.holdingSpace = False self.WFPS = 60 self.FPSlist = [ self.WFPS ] self.events = [ ] def eventListener( self ): if p.mouse.get_pressed( ) == ( 1, 0, 0 ) and self.world.player.shoot_timer < 0: self.world.player.shoot( { "dad" : self.world.player, "color" : ( 250, 250, 0 ), "colorindex" : ( 20, 100, 0 ), "angle" : self.world.player.rotation, "radius" : self.world.s1.sliderpos, "speed" : 7, "damage" : 3, "lifetime" : 90, "pos" : self.world.player.pos, } ) self.world.player.shoot_timer = 2 if p.mouse.get_pressed( ) == ( 0, 0, 1 ) and self.world.player.rocketshoot_timer <= 0: self.world.player.rocketshoot( ) for e in self.events: if e.type == p.QUIT: self.active = False p.quit() quit() if e.type == p.KEYDOWN: if e.unicode == "d": self.world.player.vx = self.world.player.speed if e.unicode == "a": self.world.player.vx = -self.world.player.speed if e.unicode == "w": self.world.player.vy = -self.world.player.speed if e.unicode == "s": self.world.player.vy = self.world.player.speed if e.unicode == " ": self.holdingSpace = True if e.key == p.K_ESCAPE: self.active = False if e.type == p.KEYUP: if e.key == p.K_d and self.world.player.vx > 0: self.world.player.vx = 0 if e.key == p.K_SPACE: self.holdingSpace = False if e.key == p.K_a and self.world.player.vx < 0: self.world.player.vx = 0 if e.key == p.K_s and self.world.player.vy > 0: self.world.player.vy = 0 if e.key == p.K_w and self.world.player.vy < 0: self.world.player.vy = 0 def update( self ): self.world.update( ) def draw( self ): self.world.draw( ) def loop( self ): clk = p.time.Clock( ) while self.active: lasttime = time.time( ) self.events = p.event.get( ) self.eventListener( ) self.update( ) self.draw( ) FPS = 0 for x in self.FPSlist: FPS += x Messages.message( self.scr, round( FPS / len( self.FPSlist ), 1 ), ( 10, 10 ), p.Color( 'magenta' ) ) p.display.update( ) now = time.time( ) self.FPSlist.append( round( 1.0 / ( now - lasttime ), 0 ) ) if len( self.FPSlist ) > 100: del self.FPSlist[ 0 ] clk.tick( self.WFPS )
# print (sys.executable) filepath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, filepath) #sys.path.append('/home/georgiy/.local/lib/python3.7/site-packages/') from world import World from spatial2 import Spatial datapath = sys.argv[-1] fname = datapath.split(os.sep)[-1] old_stdout = sys.stdout # backup current stdout sys.stdout = open(os.devnull, "w") world = World(bpy.context.scene, simulation_mode=True) spatial = Spatial(world) sys.stdout = old_stdout objlist = [name.name for name in world.entities] #print(objlist) def test(): with open(datapath, "r") as f: flag = 0 lines = f.readlines() annotations = [line.split(":") for line in lines if line.strip() != ""] for i, ele in enumerate(annotations): if len(ele) != 3: if len(ele) != 4 or ele[1] !='between':
debug_mode = True # Use this to toggle verbose mode on the text parser. game_name = "Hive Ambush" help_text = "To interact with this game world, you will use a basic text-based interface. \ Try single-word commands like 'inventory' or 'west' (or their counterpart abbreviations, 'i' or 'w', respectively \ to get started. For more complex interactions, use commands of the format [VERB][NOUN] (e.g. 'open door', \ or in some cases, [VERB][NOUN][OBJECT] (e.g. 'attack thief with nasty knife').\ The game will ignore the articles 'a', 'an', and 'the' (e.g. 'open the door' is the same as 'open door.').\n\n\ To toggle output from the game parser, type 'debug'. To exit the game at any time, type 'exit' or 'quit'." player = Player() world = World() def play(): print_welcome_text() print_wrap(world.tile_at(player.x,player.y).intro_text()) while True: print() # Print a blank line for spacing purposes. [raw_input, parsed_input] = parse.get_command() print() # Print a blank line for spacing purposes. if(debug_mode): print("--------------------------------------------------------") print("RAW USER COMANDS: " + raw_input)
from room import Room from player import Player from world import World import queue import random # Load world world = World() # You may uncomment the smaller graphs for development and testing purposes. # roomGraph={0: [(3, 5), {'n': 1}], 1: [(3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5, 'w': 11}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}], 9: [(1, 4), {'n': 8, 's': 10}], 10: [(1, 3), {'n': 9, 'e': 11}], 11: [(2, 3), {'w': 10, 'e': 6}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2, 'e': 12, 'w': 15}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5, 'w': 11}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}], 9: [(1, 4), {'n': 8, 's': 10}], 10: [(1, 3), {'n': 9, 'e': 11}], 11: [(2, 3), {'w': 10, 'e': 6}], 12: [(4, 6), {'w': 1, 'e': 13}], 13: [(5, 6), {'w': 12, 'n': 14}], 14: [(5, 7), {'s': 13}], 15: [(2, 6), {'e': 1, 'w': 16}], 16: [(1, 6), {'n': 17, 'e': 15}], 17: [(1, 7), {'s': 16}]} roomGraph = { 494: [(1, 8), { 'e': 457 }], 492: [(1, 20), { 'e': 400 }], 493: [(2, 5), { 'e': 478 }], 457: [(2, 8), { 'e': 355, 'w': 494 }], 484: [(2, 9), {
env = "main" vis = visdom.Visdom(env=env, log_to_filename="log/" + env + ".log") if vis.check_connection(): log_string('Visdom server ' + vis.server + ':' + str(vis.port)) else: log_string( 'Cannot connect to the visdom server. Does it run? (\'python -m visdom.server\')' ) exit(1) assert torch.cuda.is_available(), 'We need a GPU to run this.' ###################################################################### world = World(5) # FOR NORMAL CONVAUTOENCODER layer_specs_enc = [ { 'in_channels': 3, 'out_channels': 32, 'kernel_size': 8, 'stride': 4 }, { 'in_channels': 32, 'out_channels': 64, 'kernel_size': 4, 'stride': 2 },
# create a pyglet window and set glOptions win = window.Window(width=500, height=500, vsync=True, resizable=True) 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 for i in range(0, 50): world.agents.append(Agent(world)) world.hunter = world.agents[0] # unpause the world ready for movement 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()
import os import time from world import World from hero import Hero def update_game_state(world): """ """ world.update_world() time.sleep(0.1) if __name__ == '__main__': os.system('clear') world = World() hero = Hero() world.add_hero(hero) while True: update_game_state(world)
parser.add_argument('--log_dir', type=str, default="log/dqn_4x4", help='directory in which logs should be saved') args = parser.parse_args() if not os.path.exists(args.log_dir): os.makedirs(args.log_dir) logger = logging.getLogger('main') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(os.path.join(args.log_dir, datetime.now().strftime('%Y%m%d-%H%M%S') + ".log")) fh.setLevel(logging.DEBUG) sh = logging.StreamHandler() sh.setLevel(logging.INFO) logger.addHandler(fh) logger.addHandler(sh) # create world world = World(args.config_file, thread_num=args.thread) # create agents agents = [] for i in world.intersections: action_space = gym.spaces.Discrete(len(i.phases)) agents.append(DQNAgent( action_space, LaneVehicleGenerator(world, i, ["lane_count"], in_only=True, average=None), LaneVehicleGenerator(world, i, ["lane_waiting_count"], in_only=True, average="all", negative=True), i.id )) if args.load_model: agents[-1].load_model(args.save_dir) # if len(agents) == 5: # break
class Game(Widget): temp_text = StringProperty("") temp_textlist = ListProperty(["", "", "", ""]) def gamesetup(self): # Setting up the Event Handler. self.events = EventHandler() self.events.calls["keydown"] = self.key_down self.events.calls["keyup"] = self.key_up self.events.calls["mouseover"] = self.mouse_over self.events.eventsetup() # Setting up the Menu controller. self.menus = Menus(size=self.size) self.menus.menusetup() # Setting up the NPCs. self.npcs = NPCController() self.npcs.controllersetup() # Setting up the Player. self.player = Player() self.player.playersetup(Window.size) self.player.place(Window.center[0], Window.center[1]) # Setting up the Dialogue controller. self.dialogue = Dialogue() self.dialogue.dialoguesetup() # Setting up the world. self.world = World() self.world.worldcenter = self.center self.world.setupworld((768 * 3, 608 * 3)) # Adding everything to the Widget stack self.add_widget(self.events) self.world.add_npcs(self.npcs.npcgroup) self.world.add_widget(self.player) self.add_widget(self.world) self.add_widget(self.menus) self.add_widget(self.dialogue) # Centering Screen on the player self.center_screen(0.2) def center_screen(self, delay=0.1): Clock.schedule_once(self.world.center_screen, delay) def update(self, dt): self.menus.update(dt) self.npcs.update(dt) self.player.update(dt) def mouse_over(self, pos): pass def key_down(self, key, mod): if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"): self.player.keydown(key[1]) elif key[1] == "spacebar": print(self.player.pos, self.player.center) def key_up(self, key): if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"): self.player.keyup(key[1]) def begin_conv(self, npc): self.dialogue.npc = npc self.dialogue.start_conv() self.menus.menu_on = not self.menus.menu_on def change_top_text(self, txt): """ Top text area contains only one piece of text at a time. """ self.temp_text = txt self.menus.fade_out_top = True def change_bottom_text(self, txtlist): """ Bottom Text contains 4 question areas. """ for num, _ in enumerate(self.menus.bottomtext): try: self.menus.bottomtext[num] = txtlist[num] except IndexError: self.menus.bottomtext[num] = "" self.menus.fade_out_bottom = True
class Window(pyglet.window.Window): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sensor = Sensor() self.setup() self.world = World() self.sync_frame = 0 self.mouse_pos = (0, 0) self.frame_rate = 1 / 60 self.fps_display = FPSDisplay(self) self.grid = Grid() self.camera = Camera() self.cursor_block = self.world.create_cursor() self.label = pyglet.text.Label('Move = W,A,S,D\tUp\\Down = R\\F', font_name='Calibri', font_size=12, x=2, y=self.height - 15, multiline=True, width=120) # stress_test() # self.world.random_build() pyglet.clock.schedule(self.update) def label_update(self): """ Refreshes screen text after resizing window """ self.label = pyglet.text.Label('Move = W,A,S,D\tUp\\Down = R\\F', font_name='Calibri', font_size=12, x=2, y=self.height - 15, multiline=True, width=120) def adjust_stage_height(self, direction): self.grid.scroll(direction) self.sensor.move_y(direction) def on_mouse_scroll(self, x, y, mouse, direction): self.adjust_stage_height(direction) def on_mouse_press(self, x, y, button, modifiers): if button == window.mouse.LEFT: xyz = self.grid.select(x, y, self.camera, self) self.world.add_block(xyz) elif button == window.mouse.RIGHT: xyz = self.grid.select(x, y, self.camera, self) self.world.del_block(xyz) def on_mouse_drag(self, x, y, dx, dy, button, modifiers): self.mouse_pos = (x, y) if button == window.mouse.MIDDLE: self.camera.mouse_motion(dx, dy) elif button == window.mouse.LEFT: xyz = self.grid.select(x, y, self.camera, self) self.world.add_block(xyz) elif button == window.mouse.RIGHT: xyz = self.grid.select(x, y, self.camera, self) self.world.del_block(xyz) def on_mouse_motion(self, x, y, dx, dy): self.mouse_pos = (x, y) def on_key_press(self, button, modifiers): if button == window.key.ESCAPE: self.close() speed = 1 if button == window.key.W: self.camera.strafe[0] = -speed elif button == window.key.S: self.camera.strafe[0] = speed elif button == window.key.A: self.camera.strafe[2] = -speed elif button == window.key.D: self.camera.strafe[2] = speed elif button == window.key.R: self.camera.strafe[1] = speed elif button == window.key.F: self.camera.strafe[1] = -speed elif button == window.key.RETURN: self.sensor.input_enter() elif button == window.key.NUM_ADD: self.world.tex_index += 1 self.world.tex_index %= len(self.world.tex_lst) self.cursor_block.update_texture(self.world) elif button == window.key.NUM_SUBTRACT: self.world.tex_index -= 1 self.world.tex_index %= len(self.world.tex_lst) self.cursor_block.update_texture(self.world) elif button == window.key.F11: self.world.save() elif button == window.key.F12: self.world.load() elif button == window.key.NUM_1: pass elif button == window.key.NUM_2: self.sensor.move_z(1) elif button == window.key.NUM_3: pass elif button == window.key.NUM_4: self.sensor.move_x(-1) elif button == window.key.NUM_5: self.sensor.commit_blocks(self.world) elif button == window.key.NUM_6: self.sensor.move_x(1) elif button == window.key.NUM_7: pass elif button == window.key.NUM_8: self.sensor.move_z(-1) elif button == window.key.NUM_9: self.world.random_build() #pass elif button == window.key.PAGEUP: self.adjust_stage_height(1) elif button == window.key.PAGEDOWN: self.adjust_stage_height(-1) def on_key_release(self, button, modifiers): if button == window.key.W: self.camera.strafe[0] = 0 elif button == window.key.S: self.camera.strafe[0] = 0 elif button == window.key.A: self.camera.strafe[2] = 0 elif button == window.key.D: self.camera.strafe[2] = 0 elif button == window.key.R: self.camera.strafe[1] = 0 elif button == window.key.F: self.camera.strafe[1] = 0 def update(self, dt): self.sensor.update(self.world) self.sync_frame += dt self.sync_frame %= 4 # modulus by max animation frames mouse_over = self.grid.select(*self.mouse_pos, self.camera, self) self.cursor_block.update_position(mouse_over) self.cursor_block.update(dt) self.camera.update(dt) self.world.update(dt, self.sync_frame) def set_2d(self): width, height = self.get_size() glDisable(GL_CULL_FACE) glDisable(GL_DEPTH_TEST) viewport = self.get_viewport_size() glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, max(1, width), 0, max(1, height), -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def set_3d(self): width, height = self.get_size() glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45.0, width / float(height), 0.1, 60.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() yaw, pitch = self.camera.rotation glRotatef(yaw, 0, 1, 0) glRotatef(-pitch, math.cos(math.radians(yaw)), 0, math.sin(math.radians(yaw))) x, y, z = self.camera.position glTranslatef(-x, -y, -z) def on_resize(self, width, height): width, height = self.get_size() self.label_update() glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45.0, width / float(height), 0.1, 60.0) glMatrixMode(GL_MODELVIEW) return pyglet.event.EVENT_HANDLED def on_draw(self): self.clear() self.set_3d() self.grid.draw() self.world.draw() if not tuple(self.cursor_block.position) in self.world.boxel_hash: self.cursor_block.batch.draw() self.sensor.draw() self.set_2d() self.fps_display.draw() self.label.draw() def setup_fog(self): glEnable(GL_FOG) glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogi(GL_FOG_MODE, GL_LINEAR) glFogf(GL_FOG_START, 20.0) glFogf(GL_FOG_END, 60.0) def setup(self): glClearColor(0.3, 0.8, 0.96, 1) # Background color (r,g,b,a) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_CULL_FACE) self.setup_fog()
class _Game(object): default_triggers = () # empty tuple; a tuple is immutable game_type_name = None record_replay = True allow_cheatmode = True must_apply_equivalent_type = False def create_replay(self): self._replay_file = open( os.path.join(REPLAYS_PATH, "%s.txt" % int(time.time())), "w") self.replay_write(self.game_type_name) players = " ".join([p.login for p in self.players]) self.replay_write(self.map.get_name() + " " + players) self.replay_write(VERSION) self.replay_write(res.mods) self.replay_write(compatibility_version()) if self.game_type_name == "mission": self.replay_write(self.map.campaign.path) self.replay_write(str(self.map.id)) else: self.replay_write(self.map.pack()) self.replay_write(players) alliances = [p.alliance for p in self.players] self.replay_write(" ".join(map(str, alliances))) factions = [p.faction for p in self.players] self.replay_write(" ".join(factions)) self.replay_write(str(self.seed)) def replay_write(self, s): self._replay_file.write(s + "\n") def _game_type(self): return "%s/%s/%s" % (VERSION, self.game_type_name + "-" + self.map.get_name(), self.nb_human_players) def _record_stats(self, world): stats.add(self._game_type(), int(world.time / 1000)) def run(self, speed=config.speed): if self.record_replay: self.create_replay() self.world = World( self.default_triggers, self.seed, must_apply_equivalent_type=self.must_apply_equivalent_type) if self.world.load_and_build_map(self.map): self.map.load_style(res) try: self.map.load_resources() update_orders_list() # when style has changed self.pre_run() if self.world.objective: voice.confirmation(mp.OBJECTIVE + self.world.objective) self.interface = clientgame.GameInterface(self.me, speed=speed) b = res.get_text_file("ui/bindings", append=True, localize=True) b += "\n" + self.map.get_campaign("ui/bindings.txt") b += "\n" + self.map.get_additional("ui/bindings.txt") try: b += "\n" + open(CUSTOM_BINDINGS_PATH, "U").read() except IOError: pass self.interface.load_bindings(b) self.world.populate_map(self.players) self.nb_human_players = self.world.current_nb_human_players() t = threading.Thread(target=self.world.loop) t.daemon = True t.start() if PROFILE: import cProfile cProfile.runctx("self.interface.loop()", globals(), locals(), "interface_profile.tmp") import pstats for n in ("interface_profile.tmp", ): p = pstats.Stats(n) p.strip_dirs() p.sort_stats('time', 'cumulative').print_stats(30) p.print_callers(30) p.print_callees(20) p.sort_stats('cumulative').print_stats(50) else: self.interface.loop() self._record_stats(self.world) self.post_run() finally: self.map.unload_resources() self.world.stop() else: voice.alert(mp.BEEP + [self.world.map_error]) if self.record_replay: self._replay_file.close() def pre_run(self): pass def post_run(self): self.say_score() def say_score(self): for msg in self.me.player.score_msgs: voice.info(msg) voice.flush()
def setUp(self, agent_opts=None): spec = { "players": [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))], "mobs": [], "ground_generator": flat_ground_generator, "agent": { "pos": (0, 63, 0) }, "coord_shift": (-16, 54, -16), } world_opts = Opt() world_opts.sl = 32 self.world = World(world_opts, spec) self.agent = FakeAgent(self.world, opts=agent_opts) # More helpful error message to encourage test writers to use self.set_looking_at() self.agent.get_player_line_of_sight = Mock( side_effect=NotImplementedError( "Cannot call into C++ function in this unit test. " + "Call self.set_looking_at() to set the return value")) self.speaker = self.agent.get_other_players()[0].name self.agent.perceive() # Combinable actions to be used in test cases self.possible_actions = { "destroy_speaker_look": { "action_type": "DESTROY", "reference_object": { "location": { "location_type": "SPEAKER_LOOK" } }, }, "copy_speaker_look_to_agent_pos": { "action_type": "BUILD", "reference_object": { "location": { "location_type": "SPEAKER_LOOK" } }, "location": { "location_type": "AGENT_POS" }, }, "build_small_sphere": { "action_type": "BUILD", "schematic": { "has_name": "sphere", "has_size": "small" }, }, "build_1x1x1_cube": { "action_type": "BUILD", "schematic": { "has_name": "cube", "has_size": "1 x 1 x 1" }, }, "move_speaker_pos": { "action_type": "MOVE", "location": { "location_type": "SPEAKER_POS" }, }, "build_diamond": { "action_type": "BUILD", "schematic": { "has_name": "diamond" } }, "build_gold_cube": { "action_type": "BUILD", "schematic": { "has_block_type": "gold", "has_name": "cube" }, }, "fill_all_holes_speaker_look": { "action_type": "FILL", "location": { "location_type": "SPEAKER_LOOK" }, "repeat": { "repeat_key": "ALL" }, }, "go_to_tree": { "action_type": "MOVE", "location": { "location_type": "REFERENCE_OBJECT", "reference_object": { "has_name": "tree" }, }, }, "build_square_height_1": { "action_type": "BUILD", "schematic": { "has_name": "square", "has_height": "1" }, }, "stop": { "action_type": "STOP" }, "fill_speaker_look": { "action_type": "FILL", "location": { "location_type": "SPEAKER_LOOK" }, }, "fill_speaker_look_gold": { "action_type": "FILL", "has_block_type": "gold", "location": { "location_type": "SPEAKER_LOOK" }, }, }
class Life(object): speeds = [10, 7, 5, 3, 2, 1.5, 1, 0.75, 0.5, 0.25, 0.15, 0] def __init__(self): self.__world = World(34, 66) self.__fillrate = 25 self.__speed = 5 self.__delay = Life.speeds[self.__speed] self.__menu = 'main' self.random() def main(self): """ Main event loop for store. :return: choice """ command = 'help' parameter = None while command != 'quit': if command == 'help': self.help('help3.txt', 'Press <return> to continue. ') elif command == 'more menu': self.__menu = 'more' elif command == 'back to main menu': self.__menu = 'main' elif command == 'run simulation': self.run_simulation(parameter) elif command == 'skip generations': self.skip_generations(parameter) elif command == 'random world': self.random() elif command == 'save world': self.save(parameter, './worlds/') elif command == 'open world': self.open(parameter, './worlds/') elif command == 'change fillrate': self.change_fillrate(parameter) elif command == 'change speed': self.change_speed(parameter) elif command == 'change size': self.change_size(parameter) elif command == 'change graphics': self.change_graphics(parameter) elif command == 'geometry': self.set_geometry() elif command == 'library': self.from_library(parameter, './library/') self.display() command, parameter = self.get_command() print('See ya, thanks for playing!') def menu(self): """ returns a string containing the menu. :return: string containing the menu """ return '[R]un s[K]ip [N]ew [S]ave [O]pen [M]ore [H]elp [L]ibrary [Q]uit' def menu_more(self): """ returns a string containing the menu. :return: string containing the menu """ return 's[P]eed [D]elay s[I]ze [G]raphics g[E]ometry [H]elp [B]ack' def get_command(self): """ Get a valid command from the user. :return: command """ commands = { 'r': 'run simulation', 'k': 'skip generations', 'n': 'random world', 's': 'save world', 'o': 'open world', 'f': 'change fillrate', 'p': 'change speed', 'i': 'change size', 'g': 'change graphics', 'e': 'geometry', 'l': 'library', 'm': 'more menu', 'b': 'back to main menu', 'h': 'help', '?': 'help', 'q': 'quit' } validCommands = commands.keys() userInput = '&' parameter = None while userInput[0].lower() not in validCommands: userInput = input('Command: ') if userInput == '': userInput = 'n' parameter = 1 command = commands[userInput[0].lower()] if len(userInput) > 1: parameter = userInput[1:].strip() return command, parameter def status(self): """ Returns a string representing the status of the world. :return: string showing the status """ rows = self.__world.get_rows() columns = self.__world.get_columns() percentAlive = (self.__world.get_living_cell_count() / (rows * columns)) * 100 string = 'Status: ' string += f'gen:{self.__world.get_generation()} ' string += f'speed: {self.__speed} ' string += f'size:[{rows}x{columns}] ' string += f'alive: {percentAlive:0.0f}% ' return string def help(self, filename, prompt=None): """ Displays instructions. :param filename: help3.txt :param prompt: :return: None """ with open(filename, 'r') as file: help = file.read() print(help, end='') if prompt: input('\n' + prompt) def next_generation(self, parameter): """ Displays the next generation of the world :param parameter: parameter :return: """ self.__world.next_generation() self.display() def run_simulation(self, generations): """ Displays the next generation of the world :param generations: :return: next generation """ if toolbox.is_integer(generations) and int(generations) > 0: generations = int(generations) else: prompt = 'How many generations do you want to do?' generations = toolbox.get_integer_between(1, 10000, prompt) for generation in range(generations): self.__world.next_generation() if self.__world.is_stable() == True: break string = self.__world.__str__() string += self.status() string += f'left: {generations - generation}' print(string) time.sleep(self.__delay) print(self.menu()) def skip_generations(self, generations): """ Displays the next generation of the world :param generations: :return: next generation """ if toolbox.is_integer(generations) and int(generations) > 0: generations = int(generations) else: prompt = 'How many generations do you wanna skip?' generations = toolbox.get_integer_between(1, 10000, prompt) print(f'Skipping {generations} generations.', end='') for generation in range(generations): self.__world.next_generation() if self.__world.is_stable() == True: print('It is stable now.') break else: pass if generation % 100 == 0: print('.', end='') print(' done!') time.sleep(2) self.display() def change_fillrate(self, fillrate): """ Change the fillrate for the simulation. :param fillrate: :return: fillrate """ if toolbox.is_number(fillrate) and 0 <= float(fillrate) <= 100: fillrate = float(fillrate) else: prompt = 'What percent of cells do you want to be alive?' fillrate = toolbox.get_integer_between(0, 100, prompt) self.__fillrate = fillrate self.random() def change_speed(self, speed): """ Change the delay betwen generations of the simulation. :param speed: :return: speed """ if toolbox.is_number(speed): speed = int(speed) else: prompt = 'How fast should the generations update?' speed = toolbox.get_integer_between(0, 11, prompt) self.__delay = Life.speeds[speed] def change_graphics(self, whichCharacters): """ Change the live and dead characters for the cells. :param whichCharacters: :return: whichCharacters """ if toolbox.is_integer(whichCharacters) and \ 1 <= int(whichCharacters) <= len(Cell.displaySets.keys()): whichCharacters = int(whichCharacters) else: print('**************************************') for number, set in enumerate(Cell.displaySets): liveChar = Cell.displaySets[set]['liveChar'] deadChar = Cell.displaySets[set]['deadChar'] print( f'{number+1}: living cells: {liveChar} dead cells: {deadChar}' ) print(f'{number + 2}: pick your own characters') print('**************************************') prompt = 'What character do you want to use?' whichCharacters = toolbox.get_integer_between( 1, number + 2, prompt) if whichCharacters == number + 2: alive = toolbox.get_string( 'Which character should represent alive cells?') dead = toolbox.get_string( 'Which character should represent dead cells?') Cell.set_display_user_values(alive, dead) setString = list(Cell.displaySets.keys())[whichCharacters - 1] Cell.set_display(setString) self.display() def set_geometry(self): userGeo = toolbox.get_integer_between( 1, 2, """ Choose 1 or 2: 1. bowl 2. torus""") self.__world.set_geometry(userGeo) print(self.__world, end='') print(self.status() + '\n' + self.menu(), end='') def random(self): """ Create a random world :return: world """ self.__world.randomize(self.__fillrate) self.display() def save(self, filename, myPath='./'): """ Save the current generation of the current world as a text file. :param filename: name of the file, may be None at this point. :param myPath: Where the file should be saved. :return: None """ if filename == None: filename = toolbox.get_string('What do you wanna call the file? ') # # Make sure the file has the correct file extension. # if filename[-5:] != '.life': filename = filename + '.life' # # if the path doesn't already exist, create it. # if not os.path.isdir(myPath): os.mkdir(myPath) # # Add on the correct path for saving files if the user didn't # include it in the filename. # if filename[0:len(myPath)] != myPath: filename = myPath + filename self.__world.save(filename) def open(self, filename, myPath='./'): """ open a text file and use it to populate a new world. :param filename: name of the file, may be None at this point. :param myPath: Where the file is located. :return: None """ if filename == None: filename = toolbox.get_string('Which file do you wanna open?') # # Check for and add the correct file extension. # if filename[-5:] != '.life': filename = filename + '.life' allFiles = os.listdir(myPath) if filename not in allFiles: print( '404: File not found...thanks for breaking the program, idiot.' ) else: # # Add on the correct path for saving files if the user didn't # include it in the filename. # if filename[0:len(myPath)] != myPath: filename = myPath + filename self.__world = World.from_file(filename) def change_size(self, parameter): if parameter and ('x' in parameter): rows, columns = parameter.split('x', 2) if toolbox.is_integer(rows) and toolbox.is_integer(columns): rows = int(rows) columns = int(columns) else: prompt = 'How many rows of cells?' rows = toolbox.get_integer_between(1, 40, prompt) prompt = 'How many cells in each row?' columns = toolbox.get_integer_between(1, 120, prompt) self.__world = World(rows, columns) self.random() def display(self): """ Prints the world, status bar and menu :return: None """ if self.__menu == 'main': print(self.__world, self.status() + '\n' + self.menu()) elif self.__menu == 'more': print(self.__world, self.status() + '\n' + self.menu_more()) def long_l_world(self): """Create a blank world and put this pattern in the middle: .... .x.. .x.. .x.. .xx. .... """ rows = self.__world.get_rows() columns = self.__world.get_columns() self.__world = World(rows, columns) middleRow = int(rows / 2) middleColumn = int(columns / 2) self.__world.set_cell(middleRow - 2, middleColumn, True) self.__world.set_cell(middleRow - 1, middleColumn, True) self.__world.set_cell(middleRow - 0, middleColumn, True) self.__world.set_cell(middleRow + 1, middleColumn, True) self.__world.set_cell(middleRow + 1, middleColumn + 1, True) self.display() def acorn_world(self): """Create a blank world and put this pattern in the middle: ......... ..x...... ....x.... .xx..xxx. ......... """ rows = self.__world.get_rows() columns = self.__world.get_columns() self.__world = World(rows, columns) middleRow = int(rows / 2) middleColumn = int(columns / 2) self.__world.set_cell(middleRow - 1, middleColumn - 2, True) self.__world.set_cell(middleRow - 0, middleColumn - 0, True) self.__world.set_cell(middleRow + 1, middleColumn - 3, True) self.__world.set_cell(middleRow + 1, middleColumn - 2, True) self.__world.set_cell(middleRow + 1, middleColumn + 1, True) self.__world.set_cell(middleRow + 1, middleColumn + 2, True) self.__world.set_cell(middleRow + 1, middleColumn + 3, True) self.display() def from_library(self, filename, myPath='./'): allFiles = os.listdir(myPath) if filename not in allFiles: for file in allFiles: print(file) if filename == None: filename = toolbox.get_string('Which world do you wanna use?') if filename[-5:] != '.life': filename = filename + '.life' else: if filename[0:len(myPath)] != myPath: filename = myPath + filename self.__world = World.from_file(filename)
class InfectSim: def __init__(self, mapfile, params, sim_name): """ Initialize the simulation. Keyword arguments: mapfile -- path to an image file containing a map params -- dictionary containing simulation parameters sim_name -- title for the current simulation """ self.num_inhabitants = params["num_inhabitants"] self.day_length = params["day_length"] self.max_frames = int(params["sim_days"] * self.day_length) self.worker_ratio = params["worker_ratio"] self.work_length_factor = params["work_length_factor"] self.workend_common_chance = params["workend_common_chance"] self.home_common_chance = params["home_common_chance"] self.infection_chance = params["infection_chance"] self.initial_infected = params["initial_infected"] self.infection_length = params["infection_length"] self.object_infection_modifiers = params["object_infection_modifiers"] self.lockdown_ratio = params["lockdown_ratio"] self.lockdown_chance = params["lockdown_chance"] self.infected_stay_home_chance = params["infected_stay_home_chance"] self.disease_health_impact = params["disease_health_impact"] self.allow_natural_deaths = params["allow_natural_deaths"] self.life_expectancy = params["life_expectancy"] self.rebirth_chance = params["rebirth_chance"] self.allow_rebirths = params["allow_rebirths"] self.expected_death_rate = death_rate( 5 - self.disease_health_impact) * self.infection_length print( f"You have provided a disease health impact of {self.disease_health_impact} and ", end="") print( f"an infection length of {self.infection_length}. With a normal health of 5 this gives ", end="") print( f"the disease an expected death rate of {self.expected_death_rate:.4f}." ) self.im = Image.open(f"{os.getcwd()}/{mapfile}") self.mapfile = mapfile self.map_array = np.array(self.im) self.sim_name = sim_name self.world = World( self.map_array, num_inhabitants=self.num_inhabitants, worker_ratio=self.worker_ratio, day_length=self.day_length, work_length_factor=self.work_length_factor, workend_common_chance=self.workend_common_chance, home_common_chance=self.home_common_chance, infection_chance=self.infection_chance, initial_infected=self.initial_infected, infection_length=self.infection_length, object_infection_modifiers=self.object_infection_modifiers, infected_stay_home_chance=self.infected_stay_home_chance, disease_health_impact=self.disease_health_impact, allow_natural_deaths=self.allow_natural_deaths, life_expectancy=self.life_expectancy, rebirth_chance=self.rebirth_chance, allow_rebirths=self.allow_rebirths) max_frames = self.max_frames day_length = self.day_length num_inhabitants = self.num_inhabitants self.day_array = np.arange(max_frames + 1) / day_length self.position_history = np.zeros((max_frames + 1, num_inhabitants, 2)) self.position_history[0] = self.world.get_actor_plotpositions() self.state_history = np.zeros((max_frames + 1, 5)) self.color_history = np.empty((max_frames + 1, num_inhabitants), dtype=str) self.state_history[0], self.color_history[ 0] = self.world.get_states_and_colors() self.R_history = np.full(max_frames + 1, np.nan) self.mult_history = np.full(max_frames + 1, np.nan) self.frame_time = np.zeros(max_frames) self._has_simulated = False self.infection_heatmap = None self.recovered_stats = None def initiate_lockdown(self): self.world.set_behaviors("stay_home", self.lockdown_chance) def deactivate_lockdown(self): self.world.set_behaviors("normal") def run_sim(self, max_frames=None): if max_frames is None: max_frames = self.max_frames eta = 0 R0 = np.nan s = "" R_eval_time = int(self.infection_length * self.day_length * 1) R0_max_time = int(self.infection_length * self.day_length * 1.1) gfactor_interval = int(self.day_length) current_infected = self.initial_infected lockdown_initiated = False time_begin = time.time() print("Running sim...") """ MAIN SIMULATION LOOP """ for i in range(max_frames): frame_time_init = time.time() self.state_history[i + 1], self.color_history[ i + 1] = self.world.frame_forward() self.position_history[i + 1] = self.world.get_actor_plotpositions() self.recovered_stats = self.world.get_recovered_stats() current_infected = self.state_history[i + 1][1] if (current_infected / self.num_inhabitants > self.lockdown_ratio and not lockdown_initiated): self.initiate_lockdown() lockdown_initiated = True if self.world.global_time > R_eval_time: recovered_recently = self.recovered_stats[:, 0][( self.world.global_time - self.recovered_stats[:, 1]) < R_eval_time] if len(recovered_recently) > 0: self.R_history[i + 1] = np.average(recovered_recently) if self.world.global_time < R0_max_time: R0 = np.average( self.R_history[R_eval_time + 1:min(i + 2, R0_max_time)]) if self.world.global_time > gfactor_interval: if self.state_history[int(i - gfactor_interval + 1)][1] != 0: self.mult_history[ i + 1] = current_infected / self.state_history[ i - gfactor_interval + 1][1] if i % 10 == 0: minutes = int(eta) seconds = eta % 1 * 60 s = f"{i/max_frames*100:3.1f}% | ETA = {minutes:02d}:{int(seconds):02d} | Current infected = {current_infected} | R0 (this run) = {R0:3.3f} " print(s, end="\r") time_now = time.time() self.frame_time[i] = time_now - frame_time_init total_elapsed_time = time_now - time_begin eta = (((total_elapsed_time) / (i + 1)) * (max_frames - i) // 6) / 10 """ CLEANING UP AND SAVING DATA """ print(" " * len(s), end="\r") minutes = total_elapsed_time / 60 seconds = minutes % 1 * 60 print( f"Simulation completed... Time taken: {int(minutes):02d}:{int(seconds):02d}" ) print(f"Final states:") print(f" S: {self.state_history[-1][0]}") print(f" I: {self.state_history[-1][1]}") print(f" R: {self.state_history[-1][2]}") print(f"DI: {self.state_history[-1][3]}") print(f"DN: {self.state_history[-1][4]}") self.map = self.world.get_map() if not os.path.exists(f"{os.getcwd()}/output"): os.mkdir(f"{os.getcwd()}/output") if not os.path.exists(f"{os.getcwd()}/output/{self.sim_name}"): os.mkdir(f"{os.getcwd()}/output/{self.sim_name}") self.output_dir = f"{os.getcwd()}/output/{self.sim_name}" output_data = [ self.map, self.im, self.position_history, self.state_history, self.color_history, self.day_length, self.R_history ] print("Saving data...") np.save(f"{self.output_dir}/data.npy", output_data) def calculate_R0(self, iterations=5): """ Runs the beginning of the simulation _iterations_ number of times and returns the average R0 value. """ R0 = np.nan s = "" R_eval_time = int(self.infection_length * self.day_length * 1) R0_max_time = int(self.infection_length * self.day_length * 1.1) R0_list = [] print(f"Calculating R0 with {iterations} iterations...") s = "" """ MAIN LOOP """ for itr in range(iterations): R_history = np.full(R0_max_time + 1, np.nan) print(f"Iteration {itr}...", end="\r") for i in range(R0_max_time): self.world.frame_forward() recovered_stats = self.world.get_recovered_stats() if self.world.global_time > R_eval_time: recovered_recently = recovered_stats[:, 0][( self.world.global_time - recovered_stats[:, 1]) < R_eval_time] if len(recovered_recently) > 0: R_history[i + 1] = np.average(recovered_recently) if self.world.global_time < R0_max_time: R0 = np.average( R_history[R_eval_time + 1:min(i + 2, R0_max_time)]) if i % 10 == 0: s = f"Iteration {itr}... {i/R0_max_time*100:2.2f}% R0: {R0:2.3f}" print(s, end="\r") print(" " * len(s), end="\r") print(f"Iteration {itr}: {R0:2.3f}") R0_list.append(R0) R0 = np.nan self.world.reset() print(f"Average R0: {np.mean(R0_list):2.3f}") return np.mean(R0_list) def make_infection_heatmap(self): map_ = self.map infection_heatmap = np.zeros(map_.shape) for i, row in enumerate(map_): for j, item in enumerate(row): infection_heatmap[i, j] = item.infection_occurences self.infection_heatmap = infection_heatmap def plot_infection_heatmap(self, save_plot=True): plt.figure(figsize=(8, 8)) hmap = sns.heatmap(self.infection_heatmap[::-1], cmap=cm.OrRd, alpha=0.8, zorder=2) plt.axis("equal") hmap.imshow(self.map_array, aspect=hmap.get_aspect(), extent=hmap.get_xlim() + hmap.get_ylim(), zorder=1) plt.title("Infection hotspots") if save_plot: plt.savefig(f"{self.output_dir}/infection_heatmap.pdf", dpi=400) def plot_SIR_graph(self, save_plot=True): fig, ax = plt.subplots(figsize=(8, 8)) state_history = self.state_history day_array = self.day_array infected = state_history[:, 1] dead_inf = infected + state_history[:, 3] recovered = dead_inf + state_history[:, 2] susceptible = recovered + state_history[:, 0] dead_natural = susceptible + state_history[:, 4] l1 = [ ax.fill_between(day_array, infected, label="infected", color="red", alpha=0.3) ] l2 = [ ax.fill_between(day_array, infected, dead_inf, label="dead (from infection)", color="black", alpha=0.3) ] l3 = [ ax.fill_between(day_array, dead_inf, recovered, label="recovered", color="green", alpha=0.3) ] l4 = [ ax.fill_between(day_array, recovered, susceptible, label="susceptible", color="blue", alpha=0.3) ] if np.sum(state_history[:, 4]) >= 1: l5 = [ ax.fill_between(day_array, susceptible, dead_natural, label="dead (natural)", color="purple", alpha=0.3) ] ax.set_ylabel("Inhabitants") ax2 = ax.twinx() # shift R history R_history = self.R_history[int(self.day_length * self.infection_length):] R_plot = np.zeros(len(day_array)) R_plot[:len(R_history)] = R_history R0_est = np.nanmean( R_plot / state_history[:, 0] * state_history[1, 0] * (day_array[-1] - day_array)) / np.mean(day_array) l6 = ax2.plot(day_array, R_plot, "--", color="orange", label="R value") l7 = ax2.plot(day_array, self.mult_history, "--", color="grey", label="growth factor", linewidth=0.5) ax2.set_ylabel("R value / growth factor", color="orange") ax2.axhline(1, day_array[0], day_array[-1], color="orange", linestyle="--") ax2.tick_params(axis='y', colors="orange") ax2.set_ylim(0, 5) plt.xlabel("Day") lns = l1 + l2 + l3 + l4 if np.sum(state_history[:, 4]) >= 1: lns = lns + l5 lns = lns + l6 + l7 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc=2) plt.title("SIR plot") print(f"R0 estimate: {R0_est}") if save_plot: plt.savefig(f"{self.output_dir}/infection_development.pdf", dpi=400) def plot_death_rate(self, save_plot=True): plt.figure(figsize=(8, 8)) dr_recovered = np.full(self.state_history[:, 3].shape, np.inf) dr_recovered[self.state_history[:, 2] != 0] = ( self.state_history[:, 3])[self.state_history[:, 2] != 0] / ( (self.state_history[:, 2])[self.state_history[:, 2] != 0]) dr_cumulative = self.state_history[:, 3] / (self.state_history[:, 2] + self.state_history[:, 1] + self.state_history[:, 4]) plt.plot(self.day_array, dr_recovered, color="red", label="Death rate (vs. recovered)") plt.plot(self.day_array, dr_cumulative, color="green", label="Death rate (vs. cumulative num. of infections)") plt.hlines(self.expected_death_rate, self.day_array[0], self.day_array[-1], color="black", linestyle="--", label="Expected rate") plt.xlabel("Day") plt.ylabel("Death rate") plt.ylim(0, 1) plt.legend() plt.title("Death rate (only deaths while infected)") if save_plot: plt.savefig(f"{self.output_dir}/death_rate.pdf", dpi=400) def plot_computation_time(self, save_plot=True): plt.figure(figsize=(8, 8)) day_comptimes = [] start = 0 end = self.day_length while start < self.max_frames: day_comptimes.append(np.sum(self.frame_time[start:end])) start += self.day_length end += self.day_length plt.plot(day_comptimes) plt.xlabel("Day") plt.ylabel("Computation time") plt.title("Computation time") if save_plot: plt.savefig(f"{self.output_dir}/comp_time.pdf", dpi=400) def animation(self, skipframes=1, fps=30, plot_width=13, max_frames=None, save_anim=False): map_ = self.map if max_frames is None: max_frames = self.max_frames anim_size = np.array(map_.T.shape + np.array([1, 0])) / len( map_[1]) * plot_width fig, ax = plt.subplots(figsize=anim_size.astype(int)) self.world.plot_world(ax=ax) ax.set_xlim(left=-2) initial_positions = self.position_history[0] d = ax.scatter(initial_positions[:, 0], initial_positions[:, 1], c=self.color_history[0], s=5, zorder=4) day_length = self.day_length print("Animating...") def animate(i): index = i * skipframes + 1 positions = self.position_history[index] d.set_offsets(positions) d.set_color(self.color_history[index]) day = index // day_length plt.title( f"Frame {index}, day {day}, day progress {((index)/day_length)%1:1.2f}, infected = {self.state_history[index][1]}" ) return d, Writer = animation.writers['ffmpeg'] writer = Writer(fps=fps, metadata=dict(artist='Me'), bitrate=3000) anim = animation.FuncAnimation(fig, animate, frames=max_frames // skipframes, interval=20) if save_anim: print("Saving animation...") anim.save(f"{self.output_dir}/movie.mp4", writer=writer) return anim
class Game: def __init__(self): self.menu = """ Меню: 1) Показать общую статистику о деревне 2) Следующий день 3) Изменить погоду 4) Закончить игру """ self.day = 1 self.village = Village() self.player = Player() self.nature = Nature() self.world = World() self.world.add_nature(self.nature) self.world.add_player(self.player) self.village.add_player(self.player) for i in range(5): house = House() self.village.add_house(house) index = 1 start_specialization = specialization list_spec = [] for house in self.village.houses: for i in range(2): human = Human() spec = random.choice(start_specialization) list_spec.append(spec) if list_spec.count(spec) >= 4: start_specialization.remove(spec) human.specialization = spec index += 1 house.add_people(human) self.world.add_worker(self.village.get_people()) def get_satiety_peaple(self): list_sat = [] list_health = [] list_name = [] for hum in self.village.get_people(): list_sat.append(hum.satiety) list_health.append(hum.health) list_name.append(hum.name) # print(list_sat) # print(list_health) # print(list_name) def check_new_peaple(self): part_food = self.village.get_surplus_food2() # print("part_food", part_food) if part_food >= 6: human = Human() self.village.add_human(human) faith = 10 self.player.add_faith(faith) print( colored( "Житель {} прибыл в деневню. Вера увеличилась на {}". format(human.name, faith), "cyan")) def print_stat(self): dict_stat = self.village.short_paeple_statistic() short_stat_text = """Среднее здоровье людей: {}\nСредняя сытость людей: {}\nСреднее счастье людей: {}\nКоличество больных людей: {}\nВера: {}\nКоличество охотников: {}\nКоличество рыбаков {} \nКоличество собирателей {}""".format( dict_stat['health_peaple'], dict_stat['satiety_peaple'], dict_stat['fun_peaple'], dict_stat['illnesses_peaple'], dict_stat['faith'], dict_stat['hunters'], dict_stat['fisherman'], dict_stat['collectors'], ) print(short_stat_text) def run(self): while True: print("\nДень: {}".format(self.day)) print(self.village.news()) print("Погода сейчас: {}".format(self.nature.weather_now_ru)) self.get_satiety_peaple() print("Вера: {}".format(self.player.faith)) print(self.menu) r = input("Твоя команда?: ") if r == '1': self.print_stat() # while True: # r_stat = input("1) Назад\nТвоя команда?: ") # if r_stat == '1': # break elif r == '2': self.check_new_peaple() self.world.add_worker(self.village.get_people()) self.nature.next_day() food = self.world.next_day() self.village.food += food self.village.next_day() col_peaple = self.village.check_peaple() if col_peaple == 0: print(colored("Все жители умерли. Конец игры!", "red")) break self.day += 1 elif r == '3': print(self.nature.get_weather_info()) while True: print("&!" * 10) rate = input( "На пунктов изменить погоду?\nОт -50 до 50. 1 пункт равен 3 манны.\nОтвет: " ) if -50 <= int(rate) <= 50: self.nature.add_weather_rate(int(rate)) self.player.faith -= abs(int(rate) * 3) print("Уровень веры: ", self.player.faith) print(self.nature.get_weather_info()) break # elif r == '5': # print(self.nature.get_weather_info()) # self.nature.add_weather_rate(random.randint(-10, -50)) elif r == '4': break else: print(colored("Я не знаю такой команды", "red"))
class DroneSimulator: def __init__(self): self.x_max = 50 self.y_max = 50 self.world = World(self.x_max, self.y_max) #self.world.random() #self.world.generate_with_roads(resource_points=True, drop_points = True, recharge_points=True) self.world.generate_city(resource_points=True, drop_points=True, recharge_points=True) # drones may have different charaterisics, battery size, max lift, max weight carrying capacity, turning abilities? some might make only right turns? self.drones = [] self.drone_world_plots = [] self.message_dispatcher = MessageDispatcher() self.drone_alpha = Drone('URBAN0X1', self.world, self.message_dispatcher, cooperate=True) self.drones.append(self.drone_alpha) self.drone_beta = Drone('URBAN0X2', self.world, self.message_dispatcher, cooperate=True) self.drones.append(self.drone_beta) #self.drone_gamma = Drone('URBAN0X3', self.world,self.message_dispatcher, cooperate=False) #self.drones.append(self.drone_gamma) #self.fig = plt.figure(figsize=(1, 2))#, dpi=80, facecolor='w', edgecolor='k') self.drop_point_marker = 'o' #self.world.drop_point_locations = [random.sample(range(self.world.x_max), 10), random.sample(range(self.world.y_max), 10)] self.drop_point_plot = None #reacharge point self.recharge_point_marker = 's' #square self.recharge_point_plot = None #resources #self.fig = plt.figure(figsize=(1, 2))#, dpi=80, facecolor='w', edgecolor='k') #self.world.resource_locations = [[5,10,20,40,45],[5,10,20,40,45]] self.resource_plot = None self.resource_marker = 'v' self.markers = ['|', '+', 'x', '*'] self.colors = ['r', 'k', 'g', 'c', 'm', 'b'] self.init_figures() # def init_plot(self, location, title): plot = self.fig.add_subplot(location) plot.set_title(title, y=1.08) plot.xaxis.tick_top() #presence_plot_x, presence_plot_y = np.meshgrid(np.arange(self.width), np.arange(self.height)) plt.gca().invert_yaxis() #presence_plot.scatter(presence_plot_x, presence_plot_y, c=self.presence, cmap='gray_r', marker='+') #presence_plot.grid(color='g', linestyle='-', linewidth=1) #presence_draw_array = np.where(self.presence<1, 1, 0) plot.set_xticks(np.arange(self.x_max) + 0.5) plot.set_yticks(np.arange(self.y_max) + 0.5) plot.set_yticklabels([]) plot.set_xticklabels([]) return plot def init_figures(self): self.fig_rows = 1 self.fig_images = len(self.drones) + 1 self.fig = plt.figure(figsize=( self.fig_rows, self.fig_images)) #, dpi=80, facecolor='w', edgecolor='k') #Let there be light, the world begins #self.fig.set_size_inches(200,200) plot_location = int(str(self.fig_rows) + str(self.fig_images) + str(1)) self.world_plot = self.init_plot(location=plot_location, title='World') self.world_image = self.world_plot.imshow( self.world.map, cmap='Blues', interpolation='nearest', vmin=self.world.MIN_OBJECT_HEIGHT, vmax=self.world.MAX_OBJECT_HEIGHT, animated=False) #self.drop_point_plot = (self.world_plot.plot(self.world.drop_points[1], self.world.drop_points[0], color=self.colors.pop(), linestyle='', marker=self.drop_point_marker, markerfacecolor='white', markersize=3))[0] #Let there be resources resources_x, resources_y = self.world.get_resource_points() self.resource_plot = (self.world_plot.plot(resources_x, resources_y, color='red', linestyle='', marker=self.resource_marker, markerfacecolor='white', markersize=3))[0] #plt.gca().invert_yaxis() #Let there be drop points drop_points_x, drop_points_y = self.world.get_drop_points() self.drop_point_plot = (self.world_plot.plot( drop_points_x, drop_points_y, color='black', linestyle='', marker=self.drop_point_marker, markerfacecolor='white', markersize=3))[0] #Let there be recharge points #Let there be drop points recharge_points_x, recharge_points_y = self.world.get_recharge_points() self.recharge_point_plot = (self.world_plot.plot( recharge_points_x, recharge_points_y, color='magenta', linestyle='', marker=self.recharge_point_marker, markerfacecolor='white', markersize=3))[0] # Let there be drones #self.fig_drone_0 = plt.figure(figsize=(1, 2))#, dpi=80, facecolor='w', edgecolor='k') #self.fig.set_size_inches(200,200) for i, drone in enumerate(self.drones): drone.marker = self.markers.pop() plot_location = int( str(self.fig_rows) + str(self.fig_images) + str(i + 2)) #print(plot_location) drone.world_plot = self.init_plot(location=plot_location, title='Drone ' + drone.uid + ' View:' + drone.marker) drone.world_image = drone.world_plot.imshow( self.drones[0].world.map, cmap='Blues', interpolation='nearest', vmin=self.drones[0].world.MIN_OBJECT_HEIGHT, vmax=self.drones[0].world.MAX_OBJECT_HEIGHT, animated=True) #drone.location_plot = (drone.world_plot.plot([drone.location[1]], [drone.location[0]], color=self.colors.pop(), linestyle='', marker=self.markers.pop(), markerfacecolor='red', markersize=3))[0] drone.location_plot = (self.world_plot.plot( [drone.location[1]], [drone.location[0]], color=self.colors.pop(), linestyle='', marker=drone.marker, markerfacecolor='red', markersize=3))[0] #print(drone.location_plot) #self.drone_world_plots.append(drone_world_plot) def update(self, args): #print('update--') #drone_locations_y = [] #drone_locations_x = [] self.world.step() for i, drone in enumerate(self.drones): drone.move() #print(drone.location_plot) drone.world_image.set_data(drone.world.map) drone.location_plot.set_data([drone.location[1]], [drone.location[0]]) #drone_locations_y.append(drone.location[0]) #drone_locations_x.append(drone.location[1]) #self.drone_world_plots[i].set_data(drone.world.map) #self.drone_world_plots.gca().plot #self.world_plot.plot(drone.location[0], drone.location[1], marker='o', markersize=3, color="red") #for drone_world_plot in self.drone_world_plots # self.drone_world_plot_0.set_data(self.drones[0].world.map) self.world_image.set_data(self.world.map) x, y = self.world.get_resource_points() self.resource_plot.set_data([x], [y]) drop_point_x, drop_point_y = self.world.get_drop_points() self.drop_point_plot.set_data([drop_point_x], [drop_point_y]) recharge_point_x, recharge_point_y = self.world.get_recharge_points() self.recharge_point_plot.set_data([recharge_point_x], [recharge_point_y]) #self.world_drone_plot.set_data([drone_locations_x,drone_locations_y]) #self.im.set_array(self.luminosity) #self.im.set_facecolors(self.luminosity) #self.luminosity_im.set_data(self.luminosity_extrapolate(self.luminosity)) #im.set_cmap("gray") #im.update() #self.steps += 1 #if self.steps > self.MAX_STEPS: # self.ani.event_source.stop() # plt.grid() # plt.grid() return self.world_image, def run(self): self.ani = animation.FuncAnimation(self.fig, self.update, interval=50, blit=False) #self.update([]) plt.show()
class BaseCraftassistTestCase(unittest.TestCase): def setUp(self, agent_opts=None): spec = { "players": [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))], "mobs": [], "ground_generator": flat_ground_generator, "agent": { "pos": (0, 63, 0) }, "coord_shift": (-16, 54, -16), } world_opts = Opt() world_opts.sl = 32 self.world = World(world_opts, spec) self.agent = FakeAgent(self.world, opts=agent_opts) # More helpful error message to encourage test writers to use self.set_looking_at() self.agent.get_player_line_of_sight = Mock( side_effect=NotImplementedError( "Cannot call into C++ function in this unit test. " + "Call self.set_looking_at() to set the return value")) self.speaker = self.agent.get_other_players()[0].name self.agent.perceive() # Combinable actions to be used in test cases self.possible_actions = { "destroy_speaker_look": { "action_type": "DESTROY", "reference_object": { "location": { "location_type": "SPEAKER_LOOK" } }, }, "copy_speaker_look_to_agent_pos": { "action_type": "BUILD", "reference_object": { "location": { "location_type": "SPEAKER_LOOK" } }, "location": { "location_type": "AGENT_POS" }, }, "build_small_sphere": { "action_type": "BUILD", "schematic": { "has_name": "sphere", "has_size": "small" }, }, "build_1x1x1_cube": { "action_type": "BUILD", "schematic": { "has_name": "cube", "has_size": "1 x 1 x 1" }, }, "move_speaker_pos": { "action_type": "MOVE", "location": { "location_type": "SPEAKER_POS" }, }, "build_diamond": { "action_type": "BUILD", "schematic": { "has_name": "diamond" } }, "build_gold_cube": { "action_type": "BUILD", "schematic": { "has_block_type": "gold", "has_name": "cube" }, }, "fill_all_holes_speaker_look": { "action_type": "FILL", "location": { "location_type": "SPEAKER_LOOK" }, "repeat": { "repeat_key": "ALL" }, }, "go_to_tree": { "action_type": "MOVE", "location": { "location_type": "REFERENCE_OBJECT", "reference_object": { "has_name": "tree" }, }, }, "build_square_height_1": { "action_type": "BUILD", "schematic": { "has_name": "square", "has_height": "1" }, }, "stop": { "action_type": "STOP" }, "fill_speaker_look": { "action_type": "FILL", "location": { "location_type": "SPEAKER_LOOK" }, }, "fill_speaker_look_gold": { "action_type": "FILL", "has_block_type": "gold", "location": { "location_type": "SPEAKER_LOOK" }, }, } def handle_logical_form(self, d, chatstr: str = "", answer: str = None, stop_on_chat=False, max_steps=10000) -> Dict[XYZ, IDM]: """Handle a logical form and call self.flush() If "answer" is specified and a question is asked by the agent, respond with this string. If "stop_on_chat" is specified, stop iterating if the agent says anything """ dummy_chat = "TEST {}".format(d) self.add_incoming_chat(dummy_chat, self.speaker) self.agent.set_logical_form(d, dummy_chat, self.speaker) changes = self.flush(max_steps, stop_on_chat=stop_on_chat) if len(self.agent.dialogue_manager.dialogue_stack ) != 0 and answer is not None: self.add_incoming_chat(answer, self.speaker) changes.update(self.flush(max_steps, stop_on_chat=stop_on_chat)) return changes def flush(self, max_steps=10000, stop_on_chat=False) -> Dict[XYZ, IDM]: """Run the agant's step until task and dialogue stacks are empty If "stop_on_chat" is specified, stop iterating if the agent says anything Return the set of blocks that were changed. """ if stop_on_chat: self.agent.clear_outgoing_chats() world_before = self.agent.world.blocks_to_dict() for _ in range(max_steps): self.agent.step() if self.agent_should_stop(stop_on_chat): break # get changes world_after = self.world.blocks_to_dict() changes = dict(set(world_after.items()) - set(world_before.items())) changes.update({ k: (0, 0) for k in set(world_before.keys()) - set(world_after.keys()) }) return changes def agent_should_stop(self, stop_on_chat=False): stop = False if (len(self.agent.dialogue_manager.dialogue_stack) == 0 and not self.agent.memory.task_stack_peek()): stop = True # stuck waiting for answer? if (isinstance(self.agent.dialogue_manager.dialogue_stack.peek(), AwaitResponse) and not self.agent.dialogue_manager.dialogue_stack.peek().finished ): stop = True if stop_on_chat and self.agent.get_last_outgoing_chat(): stop = True return stop def set_looking_at(self, xyz: XYZ): """Set the return value for C++ call to get_player_line_of_sight""" self.agent.get_player_line_of_sight = Mock(return_value=Pos(*xyz)) def set_blocks(self, xyzbms: List[Block], origin: XYZ = (0, 0, 0)): self.agent.set_blocks(xyzbms, origin) def add_object(self, xyzbms: List[Block], origin: XYZ = (0, 0, 0)) -> ObjectNode: return self.agent.add_object(xyzbms, origin) def add_incoming_chat(self, chat: str, speaker_name: str): """Add a chat to memory as if it was just spoken by SPEAKER""" self.world.chat_log.append("<" + speaker_name + ">" + " " + chat) # self.agent.memory.add_chat(self.agent.memory.get_player_by_name(self.speaker).memid, chat) def assert_schematics_equal(self, a, b): """Check equality between two list[(xyz, idm)] schematics N.B. this compares the shapes and idms, but ignores absolute position offsets. """ a, _ = to_relative_pos(a) b, _ = to_relative_pos(b) self.assertEqual(set(a), set(b)) def get_idm_at_locs(self, xyzs: Sequence[XYZ]) -> Dict[XYZ, IDM]: return self.world.get_idm_at_locs(xyzs) def last_outgoing_chat(self) -> str: return self.agent.get_last_outgoing_chat() def get_speaker_pos(self) -> XYZ: return self.agent.memory.get_player_by_name(self.speaker).pos
class Game(): def __init__(self, aPlayer): self.thePlayer = aPlayer self.theWorld = World() def runGame(self): while True: print(self.thePlayer) print(self.theWorld.currentRoom) ind = input('Hvad vil du gøre?\n').lower() action = self.getAction(ind) target = self.getTarget(ind) if action == 'gå' and target in self.theWorld.currentRoom.directions: self.enterDoor(target) elif action == 'se' and target in self.theWorld.currentRoom.contents.keys( ): print(self.theWorld.currentRoom.contents[target]) else: print('Det kan ikke lade sig gøre!') def enterDoor(self, direction): if self.theWorld.currentRoom.contents[direction].locked: print('Døren er låst.\n') else: print('\nDu går gennem døren mod {}.'.format(direction)) if self.theWorld.currentRoom.contents[direction].trapped: self.springTrap() otherroom = self.theWorld.currentRoom.contents[direction].otherRoom if otherroom != None: self.theWorld.currentRoom.contents[direction].use() self.theWorld.currentRoom = otherroom else: self.theWorld.newRoom(direction) self.theWorld.currentRoom.contents[ self.theWorld.currentRoom.oppositeDirection( direction)].use() def springTrap(self): damage = random.randint(1, 10) print('Du gik i en fælde og tog {} skade. AV!'.format(damage)) self.thePlayer.takeDamage(damage) def getAction(self, ind): # Gå igennem en ulåst dør if 'gå' in ind or 'løb' in ind: return 'gå' # Angrib en dør, en kiste eller et væsen i rummet elif 'angrib' in ind or 'nak' in ind: pass # Dirk en låst dør op... hvis du kan elif 'dirk' in ind: pass # Undersøg en dør, en kiste eller et væsen i rummet elif 'undersøg' in ind or 'se' in ind: return 'se' # Uskadeliggør en fælde på en dør eller en kiste elif 'afmonter': pass def getTarget(self, ind): for target in self.theWorld.currentRoom.contents: if target in ind: return target
) def sendImages(self, images): self.viz.images(images, win="images") self.callbackhit = False def callback(self, event): self.callbackhit = True vislogger = Plot(vis) vislogger.register('Loss') ###################################################################### world = World(nbots=5, skip=True) train_images, train_actions = world.generate_batch(1) image_shape = train_images.shape[1:] print('Image shape', train_images.shape) model = ConvAutoEncoderDense_v2(image_shape, 300, 100, 200) log_string(str(model)) log_string("Number of parameters %d" % count_parameters(model)) embed_shape = model.get_embed_shape() log_string('Embedding dimensions are ' + str(embed_shape)) criterion = torch.nn.MSELoss() lr = 1e-3 clip = 1e-2
import random from ast import literal_eval from room import Room from player import Player from world import World from util import Stack # Load world world = World() # You may uncomment the smaller graphs for development and testing purposes. # map_file = "maps/test_line.txt" # map_file = "maps/test_cross.txt" # map_file = "maps/test_loop.txt" # map_file = "maps/test_loop_fork.txt" map_file = "maps/main_maze.txt" # Loads the map into a dictionary room_graph = literal_eval(open(map_file, "r").read()) world.load_graph(room_graph) # Print an ASCII map world.print_rooms() player = Player(world.starting_room) # Fill this out with directions to walk # traversal_path = ['n', 'n'] traversal_path = []
age_curve.plot() plt.show() world = World() world.init_nation('UK', uk) world.initiate_infection('UK') world.new_day(10) world.plot_infections() plt.show() """ from world import World, Pathogen import pandas as pd world = World(base_resistance=0.5, max_age=100) world.init_nation('Not Sociable', pop_size=1000, avg_compliance=.5, avg_age=20, sociability=2) world.init_nation('Somewhat Sociable', pop_size=1000, avg_compliance=.5, avg_age=20, sociability=5, borders=['Not Sociable', 'Very Sociable']) world.init_nation('Very Sociable',
from room import Room from player import Player from world import World import random from ast import literal_eval from collections import deque # Load world world = World() # You may uncomment the smaller graphs for development and testing purposes. # map_file = "maps/test_line.txt" # map_file = "maps/test_cross.txt" # map_file = "maps/test_loop.txt" # map_file = "maps/test_loop_fork.txt" map_file = "maps/main_maze.txt" # Loads the map into a dictionary room_graph = literal_eval(open(map_file, "r").read()) world.load_graph(room_graph) # Print an ASCII map # world.print_rooms() player = Player(world.starting_room) # Fill this out with directions to walk # traversal_path = ['n', 'n'] # traversal_path = []
from world import World if __name__ == "__main__": world = World() world.run()
for event in pygame.event.get(): if event.type == pygame.locals.KEYDOWN: if not game_started: if event.key == pygame.locals.K_RETURN: game_started = True while True: food_row = randint(1, World.TOTAL_ROWS - 2) food_col = randint(1, World.TOTAL_COLS - 2) if food_row == Player.STARTING_ROW and \ food_col == Player.STARTING_COL: continue if food_row == Enemy.STARTING_ROW and \ food_col == Enemy.STARTING_COL: continue break world = World(food_row, food_col) if not DEBUG_AI: player = Player(world) enemy = Enemy(world) Keys.reset() if not DEBUG_AI: player.dead = False elif event.key == pygame.locals.K_ESCAPE: exit(0) else: if event.key == pygame.locals.K_RIGHT: Keys.set_right() elif event.key == pygame.locals.K_LEFT: Keys.set_left() elif event.key == pygame.locals.K_UP: Keys.set_up()
from room import Room from player import Player from world import World import random # Load world world = World() # You may uncomment the smaller graphs for development and testing purposes. # roomGraph = {0: [(3, 5), {'n': 1}], 1: [ # (3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5, 'w': 11}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}], 9: [(1, 4), {'n': 8, 's': 10}], 10: [(1, 3), {'n': 9, 'e': 11}], 11: [(2, 3), {'w': 10, 'e': 6}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2, 'e': 12, 'w': 15}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5, 'w': 11}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}], 9: [(1, 4), {'n': 8, 's': 10}], 10: [(1, 3), {'n': 9, 'e': 11}], 11: [(2, 3), {'w': 10, 'e': 6}], 12: [(4, 6), {'w': 1, 'e': 13}], 13: [(5, 6), {'w': 12, 'n': 14}], 14: [(5, 7), {'s': 13}], 15: [(2, 6), {'e': 1, 'w': 16}], 16: [(1, 6), {'n': 17, 'e': 15}], 17: [(1, 7), {'s': 16}]} roomGraph = { 494: [(1, 8), { 'e': 457 }], 492: [(1, 20), { 'e': 400 }], 493: [(2, 5), { 'e': 478 }], 457: [(2, 8), { 'e': 355, 'w': 494 }], 484: [(2, 9), {
def __init__(self, mapfile, params, sim_name): """ Initialize the simulation. Keyword arguments: mapfile -- path to an image file containing a map params -- dictionary containing simulation parameters sim_name -- title for the current simulation """ self.num_inhabitants = params["num_inhabitants"] self.day_length = params["day_length"] self.max_frames = int(params["sim_days"] * self.day_length) self.worker_ratio = params["worker_ratio"] self.work_length_factor = params["work_length_factor"] self.workend_common_chance = params["workend_common_chance"] self.home_common_chance = params["home_common_chance"] self.infection_chance = params["infection_chance"] self.initial_infected = params["initial_infected"] self.infection_length = params["infection_length"] self.object_infection_modifiers = params["object_infection_modifiers"] self.lockdown_ratio = params["lockdown_ratio"] self.lockdown_chance = params["lockdown_chance"] self.infected_stay_home_chance = params["infected_stay_home_chance"] self.disease_health_impact = params["disease_health_impact"] self.allow_natural_deaths = params["allow_natural_deaths"] self.life_expectancy = params["life_expectancy"] self.rebirth_chance = params["rebirth_chance"] self.allow_rebirths = params["allow_rebirths"] self.expected_death_rate = death_rate( 5 - self.disease_health_impact) * self.infection_length print( f"You have provided a disease health impact of {self.disease_health_impact} and ", end="") print( f"an infection length of {self.infection_length}. With a normal health of 5 this gives ", end="") print( f"the disease an expected death rate of {self.expected_death_rate:.4f}." ) self.im = Image.open(f"{os.getcwd()}/{mapfile}") self.mapfile = mapfile self.map_array = np.array(self.im) self.sim_name = sim_name self.world = World( self.map_array, num_inhabitants=self.num_inhabitants, worker_ratio=self.worker_ratio, day_length=self.day_length, work_length_factor=self.work_length_factor, workend_common_chance=self.workend_common_chance, home_common_chance=self.home_common_chance, infection_chance=self.infection_chance, initial_infected=self.initial_infected, infection_length=self.infection_length, object_infection_modifiers=self.object_infection_modifiers, infected_stay_home_chance=self.infected_stay_home_chance, disease_health_impact=self.disease_health_impact, allow_natural_deaths=self.allow_natural_deaths, life_expectancy=self.life_expectancy, rebirth_chance=self.rebirth_chance, allow_rebirths=self.allow_rebirths) max_frames = self.max_frames day_length = self.day_length num_inhabitants = self.num_inhabitants self.day_array = np.arange(max_frames + 1) / day_length self.position_history = np.zeros((max_frames + 1, num_inhabitants, 2)) self.position_history[0] = self.world.get_actor_plotpositions() self.state_history = np.zeros((max_frames + 1, 5)) self.color_history = np.empty((max_frames + 1, num_inhabitants), dtype=str) self.state_history[0], self.color_history[ 0] = self.world.get_states_and_colors() self.R_history = np.full(max_frames + 1, np.nan) self.mult_history = np.full(max_frames + 1, np.nan) self.frame_time = np.zeros(max_frames) self._has_simulated = False self.infection_heatmap = None self.recovered_stats = None