def test_tenTiers(self): """A large number of tiers""" wconf = copy.copy(self.wconf) wconf.hexTiers = 10 wconf.usersPerCell = 0 wconf.sectorsPerBS = 3 world1 = world.World(wconf, self.phy) # Distribution self.assertEqual(len(world1.baseStations), 121) # test cell access world1.cells
def init_world(self, w=None, h=None, marg=None): if w != None: gui.init(w, h, marg) self.world = world.World(self.generator_slider.get(), self.consumer_slider.get()) self.ga_init() #self.mutate_tokens.options(to=self.world.gene_length) gui.draw_world_init(self.world, self.canvas) self.clear_graph()
def initialize_levels(): """ load LVL_SPRITES, LVL_WORLDS, LVL_CAMERAS, and tile images for each level """ for lvl in range(len(LVL_FILES)): build_level(lvl) build_spritelist(lvl) # World object created based on Global tiles object load_tiles(LVL_TILES[(lvl)]) LVL_WORLDS.append(world.World(LVL_MAPS[(lvl)]))
def test_unsolvable_maze(self): def unsolvable_maze(): maze = [[Legend.START, Legend.WALL, Legend.END, Legend.WALL], [Legend.CORRIDOR, Legend.CORRIDOR, Legend.WALL, Legend.CORRIDOR], [Legend.CORRIDOR, Legend.WALL, Legend.WALL, Legend.CORRIDOR], [Legend.CORRIDOR, Legend.CORRIDOR, Legend.CORRIDOR, Legend.CORRIDOR], ] return Position(0, 0), Position(3, 3), maze self.world = world.World(unsolvable_maze, SimpleSolver) self.assertEqual(self.world._maze.start_pos, self.world._position) self.assertFalse(self.world.solve_maze())
def reset(self): ctrl.setup.toFile('./save/exp_setup') __setupGlut__() __setupOpenGL__() # setup world and agent ctrl.modules.world = world.World(ctrl.setup.world) ctrl.state.initPos = ctrl.modules.world.randomPosition() ctrl.modules.rat = ratbot.RatBot(ctrl.state.initPos, ctrl) return [ctrl.save.nextPos, ctrl.state.last_view, ctrl.save.touch], ctrl.save.reward
def __initWorld__(self): self.resources = { '_': view.Resource('resources/grass.png'), '#': view.Resource('resources/wall.png'), 'e': view.Resource('resources/cheese.png'), '@': view.Resource('resources/mouse.png')} self.scene = world.World() self.worldRenderer = world.WorldRenderer( resources = self.resources, cellSize = np.array([32, 32]) )
def dr_agents(): '''Draws the ovals contained in the "list_ovals" attributes of the "WorldView" object''' global sc_size, sc_agents, sc_frac_inf, sc_pisc_pr, sc_pd, myworld, mysquare myworld = wd.World(sc_size.get(), sc_size.get()) myworld.create_agents(nb=sc_agents.get(), prop_infectious=sc_frac_inf.get(), p_i=sc_pi.get(), p_r=sc_pr.get(), p_d=sc_pd.get()) mysquare.draw_ovals(myworld.pop) newstats = myworld.stats() update_counters(newstats)
def get_kitchen(): w = world.World() water = Water(w) kettle = Kettle(w) tap = Tap(w) kettle.tap = tap tap.kettle = kettle tap.water = water counter = world.Thing(w, 'COUNTER', ['COUNTER']) on_counter = world.Location('ON', counter) w.put(kettle, [on_counter]) return w
def main(argv): root = Tkinter.Tk() worldmap = world.World(BOARDWIDTH, BOARDHEIGHT) mainview = view.View(root, BOARDWIDTH, BOARDHEIGHT) simthread = SimThread(mainview, worldmap) mainview.createcontrolbutton(root, simthread.controlsim) simthread.start() root.mainloop() simthread.end = True simthread.join() mixer.quit()
def run(): "Genera el objeto World y le asigna una escena." w = world.World() #new_scene = intro.Intro1(w) #new_scene = presents.Presents(w) new_scene = game.Game(w) #new_scene = demo_game.DemoGame(w) #new_scene = end.End(w) #new_scene = title.Title(w) w.change_scene(new_scene) w.loop()
def on_world_reload(self, worldcode): """ This will return a world object representing the logic from the world code, it also makes it a class attribute. @worldcode must be a list of strings.""" #print self.__class__,'on_world_reload called' try: logicworld = world.World() # worldMap changes/sets the logicworld attributes worldMap.readWorld(worldcode, logicworld) except Exception, info: #print info self.controller.give_error(str(info)) return None
def test_get_entity_at(self): new_world = world.World("new world") coords = (1, 1) lichen = make_lichen(coords) new_world = add_entity(new_world, lichen.id, lichen) assert world.get_entity_at(new_world, coords) == lichen other_lichen = make_lichen((1, 2)) new_world = add_entity(new_world, other_lichen.id, other_lichen) assert world.get_entity_at(new_world, (1, 2)) == other_lichen assert world.get_entity_at(new_world, (1, 3)) == None
def test_pickup(self): the_world = world.World() man = character.Pc() key = items.Bone() the_world.current.arena.get_location(spatial.Point(5, 5)).additem(man) the_world.current.arena.get_location(spatial.Point(5, 5)).items.append(key) world.pickup(the_world.current, man.id, lambda x: x) self.assertGreater(len(man.inventory), 0) kitty = bestiary.Cat() the_world.current.arena.get_location(spatial.Point(5, 7)).additem(kitty) kitty.kill() the_world.attempt(man.id, actions.Move('E')) the_world.attempt(man.id, actions.Move('E')) world.pickup(the_world.current, man.id, lambda x: x)
def __init__(self, master=None): super().__init__(master) self.master = master self.master.resizable(False, False) self.master.title("PyGOL") self.pack() self.button_start = Button(self, text="Start", command=self.button_start) self.button_start.grid(row=1, column=1, padx=8, pady=8) Button(self, text="Rest", command=self.button_reset).grid(row=2, column=1) self.world = world.World(self, 60, on_stop=self.button_start_text_reset) self.world.grid(row=1, column=2, rowspan=50)
def create_world(map_filename): f = open(map_filename, 'r') mapdata = json.read(f.read()) f.close() w = world.World(create_init_msg(mapdata)) for b in mapdata['boulders']: pos = (b['x'], b['y']) boulder = world.Boulder(pos, b['r']) w.boulders[pos] = boulder for c in mapdata['craters']: pos = (c['x'], c['y']) crater = world.Crater(pos, c['r']) w.craters[pos] = crater return w
def __init__(self): self.info = info.InfoBar() self.world = world.World(50, 50, self.info) self.player = player.Player("Frederico", self.world) self.world.create_enemies() self.gui = gui.GUI(self.player) terminal.open() terminal.set("window: title='Frederico', size={0}x{1}".format( vars.CONSOLE_WIDTH, vars.CONSOLE_HEIGHT)) terminal.set( "0xE000: resources/materials.png, size=16x16, resize=32x32, spacing=2x1" ) self.game_loop() self.quit = False
def test_death(self): the_world = world.World() the_world.genMobs = lambda x: [] man = character.Pc() world.spawn(the_world.current, man) location = the_world.current.arena.find_character_location(man) location.characters[0].kill() loc = the_world.current.arena.find_character(man) the_world.attempt(man.id, actions.Move('E')) new_man = the_world.current.arena.find(man.id) self.assertIsNone(new_man) self.assertEqual(0, len(the_world.current.pcs)) if the_world.current.arena.in_grid(loc.add(spatial.Point(0, 1))): self.assertGreater(len(the_world.current.arena.get_location(loc.add(spatial.Point(0, 1))).items), 0)
def main(): pygame.init() # World info--------------------------------------------------------- gSize = 8 # size of each square wdt = 100 # width hgt = 75 # height size = width, height = gSize * wdt, gSize * hgt # screen sizes screen = pygame.display.set_mode(size) # create a screen mainWorld = world.World() mainWorld.MakeGrid(wdt, hgt) # make list of grid places grid_free = [] grid_free = mainWorld.worldgrid.copy( ) # make copy of the list to use in continent areas con1 = world.Continent("A", colors.blue, wdt, hgt, grid_free) # ------------------ con2 = world.Continent("B", colors.red, wdt, hgt, grid_free) # create continents con3 = world.Continent("C", colors.green, wdt, hgt, grid_free) # con4 = world.Continent("D", colors.white, wdt, hgt, grid_free) # con5 = world.Continent("E", colors.gray, wdt, hgt, grid_free) # # con6 = world.Continent("F", colors.yellow, wdt, hgt, grid_free) # con7 = world.Continent("G", colors.pink, wdt, hgt, grid_free) # con8 = world.Continent("H", colors.purple, wdt, hgt, grid_free) # con9 = world.Continent("I", colors.d_red, wdt, hgt, grid_free) # con0 = world.Continent("J", colors.d_blue, wdt, hgt, grid_free) # ------------------ c_list = [con0, con1, con2, con3, con4, con5, con6, con7, con8, con9] for x in range(0, 100): #cover the screen with continents for x in c_list: x.spread() if not grid_free: break mainWorld.Waterlevels(c_list) # set waterlevels for x in c_list: x.drawSelf(screen) # draw the coordinates pygame.display.update() # update screen while True: for event in pygame.event.get(): # -------------------------- if event.type == pygame.QUIT: # close down without a fight pygame.display.quit() # sys.exit() # ---------------------------
def main(): """Set up the world and run it.""" metadesc = OrderedDict([ ("colors", "0.3 0.8 0.8 0.3 0.8 0.8 0.8 0.3 0.8 0.8 0.3 0.8"), ("fuzziness", "1.0"), ("const_bounds", "-5.0 5.0"), ("fun_gen_depth", "3"), ("incr_range", "5.0"), ("mult_range", "2.0") ]) muterates = OrderedDict([("mute", "0.1"), ("genome", "0.2"), ("gene_action", "0.5"), ("struct_mod", "0.5"), ("leaf_type", "0.3"), ("genome_rel", "2 1 1 1 2"), ("const_rel", "1 1 1 1"), ("leaf_rel", "1 1 4 4"), ("enum_rel", "1 1 1"), ("struct_rel", "1 1 1")]) meta1 = " ".join(metadesc.values()) + " " + " ".join(muterates.values()) metadesc["colors"] = "1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0" meta2 = " ".join(metadesc.values()) + " " + " ".join(muterates.values()) gen = " 12 + 1 $10 | 4 * = 0 % $10 23 * 100 $1 | " \ " 5 * 100 $2 | " \ " 4 * 90 $4 | 3 * 90 $3 | 1 * 100 $5 | " \ " 3 * * 80 $1 $0 | 4 * * 80 $1 - 1 $0 | " \ " 1 20 " # Increment state per step, random turn # Suck up stuff if it's present underneath bot # Turn towards food # If bumped, turn away from obstacle # Baseline instinct to move forward #gen = " | 1 1 | 3 * 2 $0 | 4 * 3 $1 | 5 * 4 $2 | 12 + 1 $10 | 5 * = 0 % $10 7 * 100 $1" print("Generating Goombas") gen2 = [genome.Genome(*genome.cross_genome_sequences((meta2, gen), (meta1, gen))) \ for _ in range(30)] for gen in gen2: gen.mutate() gen2 = [g.sequences() for g in gen2] print("Building World") #wrld = world.World.random_goombas(40, 40, 10, meta1, [3, 10]) wrld = world.World((100, 100), gen2, meta1, [3, 10], 1000) print("Constructing geometry (can take a bit because I'm a retard)") #canv = display.get_canvas(wrld) #canv.title = "Genetic Roombas!" #canv.show() #app.run() while True: wrld.step()
def init(): global time, theWorld, cmap, plots, dirName, num_households, times l = L.Landscape() theWorld = W.World(size=L.width, numagents=W.starting_agents, landscape=l) time = 0 num_households = [len(theWorld.households)] times = [0] cmap = matplotlib.colors.LinearSegmentedColormap(name='G', segmentdata=cdict, N=256) plots = None if MOVIES: openFolder()
def __init__(self, displayWidth, displayHeight, dataModule=None): self.mode = None self.displayWidth = displayWidth self.displayHeight = displayHeight pyui.desktop.getRenderer().setBackMethod(self.draw) self.events = [] self.paused = 0 # initialize data self.dm = datamanager.DataManager() if dataModule: dataModule.initialize(self.dm) # create the world self.world = world.World(displayWidth, displayHeight)
def parse_world_list(world_path_list): """ Parses a world list checking if they exists and are a minecraft world folders. Returns a list of World objects. """ tmp = [] for d in world_path_list: if exists(d): w = world.World(d) if w.isworld: tmp.append(w) else: print "Warning: The folder {0} doesn't look like a minecraft world. I'll skip it.".format(d) else: print "Warning: The folder {0} doesn't exist. I'll skip it.".format(d) return tmp
def __init__(self, surface, settings): self.surface = surface self.settings = settings self.world = world.World(surface, settings) self.width = self.world.width self.height = self.world.height self.clock = pygame.time.Clock() self.level = 1 try: self.player = player.Player(settings.driver) self.player.write("%i %i" % (self.width, self.height)) except PlayerError as e: self.world.reset() self.world.add_text(e.value, scale=20) raise
def __init__(self): self.screen_width = 255 self.screen_height = 255 #Initialize the window pyxel.init(self.screen_width, self.screen_height, caption="Rogue Like") #Load assets pyxel.load("assets/rogue_like.pyxel") #Create world constructor self.w = world.World(self.screen_width, self.screen_height, 0) #Run the game pyxel.run(self.update, self.draw)
def test_twoTiers(self): """ A typical network size """ wconf = copy.copy(self.wconf) wconf.hexTiers = 2 wconf.usersPerCell = 1 world1 = world.World(wconf, self.phy) # omnidirectionality requires more BS self.assertEqual(len(world1.baseStations),19) wconf.sectorsPerBS = 3 wconf.consideredTiers = 2 world2 = world.World(wconf, self.phy) # number of mobiles self.assertEqual(len(world2.mobiles), 1*19) # cells self.assertEqual(len(world2.hexagons), 19) # BS self.assertEqual(len(world2.baseStations), 9) world2.associatePathlosses() world2.calculateSINRs() # each mobile sees signals from all BS for mob in world2.mobiles: # mobile has data on all BS self.assertEqual(len(world2.baseStations), len(mob.baseStations)) # check that the mobile's cell matches the mobile's BS mob.cell in mob.BS.cells for BS in world2.baseStations: for cell in mob.baseStations[BS].cells: # each mobile has CSI data in the right shape np.testing.assert_array_equal(mob.baseStations[BS]['cells'][cell]['CSI_OFDMA'].shape, (2,2,50,10)) # the mobiles have data on all cells for mob in world2.mobiles: self.assertEqual( sum(len(mob.baseStations[BS]['cells']) for BS in world2.baseStations), len(world2.hexagons))
def tick(blackboard): # Update all blackboard dependent helper modules. Global.update(blackboard) TeamStatus.update(blackboard) FieldGeometry.update(blackboard) Timer.update(blackboard) Sonar.update(blackboard) global skill_instance if not skill_instance: skill = blackboard.behaviour.skill # Load the module and the class we're going to use. found_skill = False SkillClass = None behaviour_packages = ["roles", "skills", "test"] for package in behaviour_packages: if skill not in [ name for _, name, _ in pkgutil.iter_modules( ["/home/nao/data/behaviours/%s" % package]) ]: Log.info("%s wasn't in %s, skipping import attempt.", skill, package) continue try: skill_module = __import__("%s.%s" % (package, skill), fromlist=[skill]) # Access the class so we can do some reflection. SkillClass = getattr(skill_module, skill) found_skill = True Log.info("Successfully imported %s from %s.%s", skill, package, skill) break except ImportError, e: Log.error("%s %s", package, e) Log.error(traceback.format_exc()) if not found_skill: raise ImportError( "Could not find skill: %s in any of our behaviour folders." % skill) if issubclass(SkillClass, BehaviourTask): new_world = world.World(blackboard) # It's a whole new world. skill_instance = SkillClass(new_world) else: parentSkill = DummySkill(blackboard) skill_instance = SkillClass(blackboard, parentSkill)
def main(): WIDTH = 40 wrld = world.World(WIDTH) # TODO: args wrld.add_entity(world.SoundSource(), 30, 30) # add a sound source at (30, 30) wrld.add_entity(world.SimpleHarmonium(), 25, 10) # add a harmonium wrld.add_entity(world.SimpleHarmonium(), 25, 25) # add a harmonium close TURNS = 4000 jump = 8 for i in xrange(TURNS): wrld.turn() if i % jump == 0: state = wrld.get_state() image = state_to_image(state) # maybe edit image image.save("test_{}.png".format(str(i).zfill(4)), "PNG")
def world_setup(self, start_zone, *args): """ run after one edits all the dictionaries. it generates a world object that is made of the stuff with in the dictionaries. start_zone is a tuple the represents the matrix coordinates of the starting zone. *args are dictionaries representing the npcs, enemys, and items. the keys to all these dictionaries is the a tuple representing the location of the value, which would be the object its self. """ for arg in args: self.distribute_stuff(arg) self.world = world.World(self.zones) self.world.set_start(start_zone)
def main(): world_turtle = turtle.Turtle() screen = world_turtle.getscreen() screen.setworldcoordinates(0, 0, WIDTH - 1, HEIGHT - 1) screen.tracer(NUM_BIRDS) world_turtle.hideturtle() sky = w.World(WIDTH, HEIGHT) # create the world for index in range(NUM_BIRDS): # create the boids in myworld=sky bird = b.Boid(sky) for step in range(ITERATIONS): # run the simulation sky.step_all() screen.update() screen.exitonclick()
def update_world(self, m): try: #print m if m.type == mp.TYPE_INIT: self.world = world.World(m) elif m.type == mp.TYPE_TELEMETRY: self.world.update(m) elif m.type == mp.TYPE_END_OF_RUN: self.world.reset() else: # not handled yet pass except Exception, e: print e raise pass