def __init__(self): pygame.init() pygame.mixer.init() pygame.display.set_caption('My Game') self.screen = pygame.display.set_mode(RESOLUTION) self.running = False self.world = esper.World()
def build_simulation_from_map(file, line_width=10): # Load map from .drawio file window_name, map_content = loader.mapFromDrawio(file) width = int(map_content.attrib.get('pageWidth', 500)) height = int(map_content.attrib.get('pageHeight', 500)) BKGD = helpers.hex_to_rgb('#FFFFFF') if 'background' in map_content.attrib: BKGD = helpers.hex_to_rgb(map_content.attrib['background']) content_root = map_content[0] # Create pyglet window window = pyglet.window.Window(width=width, height=height, caption=window_name) batch = pyglet.graphics.Batch() # Define default line width pyglet.gl.glLineWidth(line_width) # Define background clear color pyglet.gl.glClearColor(BKGD[0], BKGD[1], BKGD[2], BKGD[3]) pyglet.gl.glClear(pyglet.gl.GL_COLOR_BUFFER_BIT | pyglet.gl.GL_DEPTH_BUFFER_BIT) world = esper.World() simulation = world.create_entity() # Simulation is always the first entity draw_map, objects, interactive = build_simulation_objects( content_root, batch, world, ((width, height), line_width)) world.add_component(simulation, Inventory(interactive)) return { 'world': world, 'window': window, 'batch': batch, 'window_props': (window_name, (width, height), BKGD), 'draw_map': draw_map, 'objects': objects }
def main() -> None: pygame.init() window = pygame.display.set_mode((256, 256)) pygame.display.set_caption('BLOCKS') clock = pygame.time.Clock() window.fill((0xFF, 0xFF, 0xFF)) pygame.display.flip() world = esper.World() entity = world.create_entity() world.add_component(entity, BoundingBox(50, 50, 20, 20)) world.add_component(entity, Velocity(10, -10)) world.add_processor(Gravity()) world.add_processor(Renderer(window)) world.process() while True: for _ in range(30): world.process() time.sleep(.1) #print(world.components_for_entity(entity)) pygame.display.flip() comp = world.component_for_entity(entity, BoundingBox) comp.top_left_y = 50 comp = world.component_for_entity(entity, Velocity) comp.speed_y = -10 input()
def run(): # Initialize Pygame stuff pygame.init() window = pygame.display.set_mode(RESOLUTION) pygame.display.set_caption("Breakout") clock = pygame.time.Clock() # Initialize Esper world, and create a "player" Entity with a few Components. world = esper.World() player = world.create_entity( Velocity(), Position(360.0, 450), Shape(0, rect=pygame.Rect((360, 450), (100, 20))), Renderable(pygame.Color(255, 0, 0)), Input() ) world.add_processor(InputProcessor(player)) world.add_processor(MovementProcessor(0, 720, 0, 450)) world.add_processor(RenderProcessor(window)) running = True p_t = pygame.time.get_ticks() while running: t = pygame.time.get_ticks() # deltaTime in seconds. delta = (t - p_t) / 1000.0 p_t = t for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # A single call to world.process() will update all Processors: world.process(delta=delta)
def esper_setup_ABC(hparams): """Setup a world with entities that have (ABC) components.""" world = esper.World() eids = [world.create_entity(A(), B(), C()) for _ in range(hparams.count)] return world, eids
def esper_setup_empty(hparams): """Setup a world with empty entities.""" world = esper.World() eids = [world.create_entity() for _ in range(hparams.count)] return world, eids
def __init__(self): self.world = esper.World() self.event_handler = EventHandler() self.screen = Screen(self.world) self.sidebar = Sidebar(self.world) self.console = Console(self.world) self.last_update = time.monotonic() self.accumulator = 0 rand_x = Random() rand_y = Random() # Add player ship self.player_ship = factory.player_ship(self.world) self.world.component_for_entity(self.player_ship, Selectable).selected_main = True # Add some asteroids for i in range(20): asteroid = factory.asteroid(self.world) position = Position(int(50 * rand_x.guass(0, 0.3)), int(50 * rand_y.guass(0, 0.3))) self.world.add_component(asteroid, position) # Add patroling enemy enemy = factory.enemy_fighter(self.world) enemy_behaviour: Behaviour = self.world.component_for_entity( enemy, Behaviour) enemy_behaviour.behaviours.append( BehaviourPatrol((10, 10), (10, -10), 2)) # Add processors self.__initialize_processors()
def test_process_transaction(buyer_money, seller_money, buy_price, sell_price): world = esper.World() exchange = Exchange() exchange.world = world buyer, buy_order, seller, sell_order = prepare_transaction_arguments( world, buyer_money, seller_money, buy_price, sell_price) transaction_price = exchange.process_transaction(buy_order, sell_order) # buy and sell price ar as close as possible assert transaction_price.creds - transaction_price.creds <= 1, "Transaction prices differ too much" # amount of transferred money is same as mount of total offer assert abs((transaction_price + transaction_price).creds - (buy_price + sell_price) ) <= 1, "Amount of money in transaction other then offering" assert world.component_for_entity( seller, Wallet ).money.creds == seller_money + transaction_price.creds, "Seller did not got correct amount of money" assert world.component_for_entity( seller, Wallet).last_transaction_details_for(Resource.FOOD) == ( transaction_price, OrderStatus.SOLD ), "Seller did not register his transaction correctly" assert sell_order.status == OrderStatus.SOLD # buyer gets a refund as he had locked some money before transaction assert world.component_for_entity( buyer, Wallet).money.creds == buyer_money + ( buy_price - transaction_price.creds), "Buyer did not get a refund" assert world.component_for_entity( buyer, Wallet).last_transaction_details_for(Resource.FOOD) == ( transaction_price, OrderStatus.BOUGHT ), "Buyer did not register his transaction correctly" # buyer did not have anything before exchange assert world.component_for_entity(buyer, Storage).amount( Resource.FOOD) == 1, "Buyer did not get what he bought" assert buy_order.status == OrderStatus.BOUGHT
def __init__(self, app): super(Game, self).__init__() self.app = app self.world = esper.World() self.players = {} # indexed by session key from sockjs self.processors = [] self.running = True self.elapsed = 0.0 asyncio.ensure_future(self.game_loop())
def setUp(self): self.db = init_db() self.world = esper.World() self.world.add_processor(MovementProcessor()) self.world.add_processor(LocationHistoryProcessor()) self.world.add_processor(InventoryProcessor()) self.world.add_processor(PersistentProcessor(self.db))
def run(): # Initialize Pygame stuff pygame.init() window = pygame.display.set_mode(RESOLUTION) pygame.display.set_caption("Esper Pygame example") clock = pygame.time.Clock() pygame.key.set_repeat(1, 1) # Initialize Esper world, and create a "player" Entity with a few Components. world = esper.World() goalOrder, lapGoal = loadMap(world, MAP_SAVE) loadProcessors(world, window, goalOrder, lapGoal) players = world.get_component(Driver) player, _ = players[0] running = True game_processor = world.get_processor(GameProcessor) game_processor.startRace() while not game_processor.hasGameEnded() and running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: world.component_for_entity(player, Driver).isTurningLeft = True elif event.key == pygame.K_RIGHT: world.component_for_entity(player, Driver).isTurningRight = True elif event.key == pygame.K_UP: world.component_for_entity(player, Driver).isAccelerating = True elif event.key == pygame.K_DOWN: world.component_for_entity(player, Driver).isDecelerating = True elif event.key == pygame.K_ESCAPE: running = False elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: world.component_for_entity(player, Driver).isTurningLeft = False elif event.key == pygame.K_RIGHT: world.component_for_entity(player, Driver).isTurningRight = False elif event.key == pygame.K_UP: world.component_for_entity(player, Driver).isAccelerating = False elif event.key == pygame.K_DOWN: world.component_for_entity(player, Driver).isDecelerating = False elif event.key == pygame.K_s: world.component_for_entity(player, Slowdown).nextCycle() # A single call to world.process() will update all Processors: world.process() clock.tick(FPS)
def _build_world(self) -> esper.World: """do this before the classes are used, after screen setup """ world = esper.World() # Initialize Game Groups all_group = pg.sprite.LayeredDirty() # pool set self.ent_pools: Dict[str, ent.EntityPool] = dict() # static ground self.ent_pools["ground_pool"] = ent.GroundPool(all_group, world, pool_num=1) # land entity setup self.ent_pools["land_pool"] = ent.LandPool( containers=all_group, world=world, pool_num=1, screen_width=self.screen.get_width()) # bird entity pool self.ent_pools["bird_pool"] = ent.BirdPool(containers=all_group, world=world, pool_num=1) # score entity pool setup self.ent_pools["score_pool"] = ent.ScorePool(containers=all_group, world=world, pool_num=1) # systems world.add_processor(sys.SysRenderClear(all_group=all_group, screen=self.screen, background=self.background), priority=Global_Param['Sys_Priority_Top']) world.add_processor(sys.SysIntroControlBird(scene=self), priority=Global_Param['Sys_Priority_High']) world.add_processor(sys.SysLandCircle(), priority=Global_Param['Sys_Priority_Default']) world.add_processor(sys.SysFrameAnimate(), priority=Global_Param['Sys_Priority_Default']) world.add_processor(sys.SysMove(), priority=Global_Param['Sys_Priority_Default']) world.add_processor(sys.SysRender(all_group=all_group, screen=self.screen), priority=Global_Param['Sys_Priority_Background']) return world
def __init__(self, game, path): self.game = game self.path = path self.world = esper.World() self.scripts = [] self.camera = None self.game_info = None
def main() -> None: pg.init() screen = pg.display.set_mode((int(WORLD_SIZE.x), int(WORLD_SIZE.y))) clock = pg.time.Clock() running = True world = esper.World() home = world.create_entity() home_pos = WORLD_SIZE.elementwise() * Vector2(random(), random()) world.add_component(home, Home()) world.add_component(home, Stinky(10, SCENT_TO_HOME)) world.add_component(home, Movable(home_pos, Vector2())) world.add_component(home, Renderable(10, pg.Color(0, 200, 0))) for _ in range(N_FOODS): food = world.create_entity() world.add_component(food, Food(FOOD_SIZE)) world.add_component(food, Stinky(1, SCENT_TO_FOOD)) world.add_component( food, Movable(WORLD_SIZE.elementwise() * Vector2(random(), random()), Vector2())) world.add_component(food, Renderable(1, pg.Color(0, 0, 200))) for _ in range(N_ANTS): ant = world.create_entity() world.add_component(ant, Ant()) world.add_component(ant, Stinky(1, None)) world.add_component( ant, Movable(home_pos, Vector2(1, 0).rotate(randint(0, 360)))) world.add_component(ant, Renderable(3, pg.Color(200, 0, 0))) scent_processor = ScentProcessor(WORLD_SIZE, 2) food_processor = FoodProcessor(WORLD_SIZE) ant_processor = AntProcessor(food_processor, scent_processor) movement_processor = MovementProcessor(WORLD_SIZE) render_processor = RenderProcessor(WORLD_SIZE, screen, scent_processor) world.add_processor(ant_processor) world.add_processor(scent_processor) world.add_processor(movement_processor) world.add_processor(render_processor) world.add_processor(food_processor) while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False world.process() clock.tick(60)
def test_example3(self): world = esper.World() problem04_ecs.WorldSetup(world) problem04_ecs.ParseFile(VALID_PASSPORTS.splitlines(), world) world.process() for e, (p, pid) in world.get_components( problem04_ecs.Passport, problem04_ecs.PassportID ): self.assertTrue( p.valid, f"Passport with PID {pid.pid} should be valid" )
def run(args=None): world = esper.World() window = WindowProcessor(1280, 720, "A Window", resizable=True) world.add_processor(window) world.add_processor(MoveProcessor()) world.add_processor(EditorProcessor(window)) factory = Factory(world, window) factory.create_world() pyglet.clock.schedule_interval(world.process, 1 / 60.0) pyglet.app.run()
def init(): new_world = esper.World() createManyEntities(new_world) createGlobalEntities(new_world) new_world.add_processor(Timeflow()) new_world.add_processor(Consumption()) new_world.add_processor(Production()) new_world.add_processor(Ordering()) new_world.add_processor(Exchange()) new_world.add_processor(OrderCancellation()) new_world.add_processor(TurnSummaryProcessor()) return new_world
def __init__(self, width=640, height=480, caption="PyXmon", fps=60): pygame.init() self.width = width self.height = height self.caption = caption self.FPS = fps self.dt = 0 self.prev_time = time.time() self.running = True # Starting ECS self.world = esper.World()
def esper_setup(hparams): """Setup a world with entities that have (AB), (ABC), (CDE), (DE) component sets.""" world = esper.World() ab = [world.create_entity(A(), B()) for _ in range(hparams.count // 4)] abc = [ world.create_entity(A(), B(), C()) for _ in range(hparams.count // 4) ] cde = [ world.create_entity(C(), D(), E()) for _ in range(hparams.count // 4) ] de = [world.create_entity(D(), E()) for _ in range(hparams.count // 4)] return world, (ab, abc, cde, de)
def load_game(self): with open('data/save/components.pickle', 'rb') as file: components = pickle.load(file) with open('data/save/entities.pickle', 'rb') as file: entities = pickle.load(file) with open('data/save/game_map.pickle', 'rb') as file: game_map = pickle.load(file) world = esper.World() world._components = components world._entities = entities self.scenes['game'] = Game(world, game_map) self.current_scene = self.scenes['game']
def __init__(self, game: Game) -> None: super().__init__() self.world = esper.World() for translation in ( (20, 0, 0, 0), (-20, 0, 0, 0), (0, 20, 0, 0), (0, -20, 0, 0), (0, 0, 20, 0), (0, 0, -20, 0), ): sphere = Translate(translation)(Sphere4( 2, colours=[tuple(random() for _ in range(3)) + (1, )])) game.render.attach_new_node(sphere.node)
class SceneBase: world = esper.World() def __init__(self): self.next = self def init(self): print("uh-oh, you didn't override this in the child class") def SwitchToScene(self, next_scene): if next_scene is not None: next_scene.init() self.next = next_scene def Terminate(self): self.SwitchToScene(None)
def setup(self): #Create a World Object self.newworld = esper.World() #Add the processor self.movement_processor = MovementProcessor() self.newworld.add_processor(self.movement_processor) #Create a couple of entities self.player = self.newworld.create_entity() self.newworld.add_component(self.player, Renderable(parent=self, texture='plc:Character_Boy', position=(100, 100))) self.newworld.add_component(self.player, Velocity(x=1, y=.5)) self.enemy = self.newworld.create_entity() self.newworld.add_component(self.enemy, Renderable(parent=self, texture='plc:Character_Pink_Girl', position=(200, 200))) self.newworld.add_component(self.enemy, Velocity(x=.5, y=0))
def init(): new_world = esper.World() #create2Entities(new_world) #createFewEntities(new_world) createManyEntities(new_world) createGlobalEntities(new_world) new_world.add_processor(Timeflow()) new_world.add_processor(Production()) new_world.add_processor(Ordering()) new_world.add_processor(Exchange()) new_world.add_processor(OrderCancellation()) new_world.add_processor(Consumption()) new_world.add_processor(Maturity()) new_world.add_processor(Death()) new_world.add_processor(InheritanceLottery()) new_world.add_processor(WealthRedistribution(0.1)) new_world.add_processor(TurnSummaryProcessor()) new_world.add_processor(Cleanup()) return new_world
def test_example1(self): world = esper.World() world.add_processor(problem04_ecs.FieldPresenceValidator()) problem04_ecs.ParseFile(DATA_1.splitlines(), world) world.process() validities = { "860033327": True, "028048884": False, "760753108": True, "166559648": False, } for e, (p, pid) in world.get_components( problem04_ecs.Passport, problem04_ecs.PassportID ): target = validities[pid.pid] self.assertEqual( p.valid, target, f"Passport with PID {pid.pid} should have validity {target}", )
def main(file_yml): global keyboard # from test_tiles.py of cocos2d dict_yml = loadSpritesheetAsAnimation.load_yml(file_yml) spritesheet_img = pyglet.image.load('../images/' + dict_yml['image']) #director.init(width = spritesheet_img.width, height = spritesheet_img.height, resizable = True) director.init(width=WIDTH, height=HEIGHT, resizable=True) main_scene = cocos.scene.Scene() # Create layer with spritesheet layer = cocos.layer.Layer() main_scene.add(layer) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # Initialize Esper world, and create a "player" Entity with a few Components: world = esper.World() player = world.create_entity() world.add_component(player, Velocity(x=0, y=0)) player_animation = SpriteSheetAnimation(dict_yml) world.add_component(player, player_animation) player_sprite = cocos.sprite.Sprite( player_animation.animations['walk_down'], (WIDTH // 2, HEIGHT // 2)) world.add_component(player, Renderable(sprite=player_sprite)) # Create some Processor instances, and asign them to the World to be processed: movement_processor = MovementProcessor(minx=0, miny=0, maxx=WIDTH, maxy=HEIGHT) player_key_processor = PlayerKeyProcessor(keyboard) world.add_processor(player_key_processor) world.add_processor(movement_processor) layer.add(player_sprite) pyglet.clock.schedule_interval(world.process, interval=1.0 / FPS) director.run(main_scene)
def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption('Dirt II') clock = pygame.time.Clock() pygame.mixer.music.load( os.path.join('data', 'music', 'meadow_thoughts.ogg')) pygame.mixer.music.play(loops=-1) world = esper.World() render_processor = RenderProcessor(screen=screen) world.add_processor(render_processor) while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() world.process() clock.tick(FPS)
def main(): inter = Interface() world = esper.World() random.seed() creature = {} tree = {} for i in range(15): creature[i] = world.create_entity( Life(), Mind(), Position(random.randint(40, 80), random.randint(10, 50)), Paint(125, 125, 125, 100)) tree[i] = world.create_entity( Life(), Tree(20), Position(random.randint(40, 80), random.randint(10, 50)), Paint(50, 150, 50, 100)) world.add_processor(Show()) world.add_processor(Move()) world.add_processor(Grow()) world.add_processor(Bear_Fruit()) #keyboard.add_hotkey('r', print, args=[world.component_for_entity(user, Relations).relations2others]) keyboard.on_release_key('enter', inter.pause_pressed) # A dummy main loop: try: while True: inter.step_number += 1 inter.step() time.sleep(0.1) world.process() graph.flip() while (inter.pause): pass except KeyboardInterrupt: return
def main(): # Create a World instance to hold everything: world = esper.World() # Instantiate a Processor (or more), and add them to the world: movement_processor = MovementProcessor() world.add_processor(movement_processor) # Create entities, and assign Component instances to them: player = world.create_entity() world.add_component(player, Velocity(vx=0.9, vy=1.2)) world.add_component(player, Position(x=5, y=5)) # A dummy main loop: try: while True: # Call world.process() to run all Processors. world.process(1.0) time.sleep(1) except KeyboardInterrupt: return
def test_stun(self): game.isunittest.setIsUnitTest() self.world = esper.World() attackable = Attackable( initialHealth=100, stunTime=0.75, stunCount=2, stunTimeFrame=3) entity = self.world.create_entity() self.world.add_component(entity, attackable) gametimeProcessor = GametimeProcessor() attackableProcessor = AttackableProcessor() self.world.add_processor(attackableProcessor) self.world.add_processor(gametimeProcessor) # 0 self.assertTrue(attackable.isStunnable()) attackable.addStun(0.75) # 1 self.assertTrue(attackable.isStunnable()) self.world.process(0.5) attackable.addStun(0.75) # 2 self.assertTrue(attackable.isStunnable()) self.world.process(0.5) self.assertTrue(attackable.isStunnable()) attackable.addStun(0.75) # 3 self.world.process(0.5) self.assertFalse(attackable.isStunnable()) # 3seconds to reset, so 1.5+1.6 > 3.0 self.world.process(1.6) self.assertTrue(attackable.isStunnable())