def create_mob(world: World, mob_id: str, x: int, y: int, *args): """Create a new mob instance and add it to the world based on the mob_id. Parameters: world (World): The world where the mob should be added to. mob_id (str): The mob identifier of the mob to create. x (int): The x coordinate of the mob. y (int): The y coordinate of the mob. """ mob_id = MOBS[mob_id] if mob_id == "cloud": mob = CloudMob() elif mob_id == "fireball": mob = Fireball() elif mob_id == "mushroom": mob = Mushroom() elif mob_id == 'gang': mob = Gang() elif mob_id == 'bullet_l': mob = BulletLeft() elif mob_id == 'bullet_r': mob = BulletRight() else: mob = Mob(mob_id, size=(1, 1)) world.add_mob(mob, x * BLOCK_SIZE, y * BLOCK_SIZE)
def create_block(world: World, block_id: str, x: int, y: int, *args): """Create a new block instance and add it to the world based on the block_id. Parameters: world (World): The world where the block should be added to. block_id (str): The block identifier of the block to create. x (int): The x coordinate of the block. y (int): The y coordinate of the block. """ block_id = BLOCKS[block_id] if block_id == "mystery_empty": block = MysteryBlock() elif block_id == "mystery_coin": block = MysteryBlock(drop="coin", drop_range=(3, 6)) elif block_id == "bounce_block": # Adding bounce, tunnel and flag to the game world block = BounceBlock() elif block_id == "flag": block = FlagpoleBlock() elif block_id == "tunnel": block = TunnelBlock() elif block_id == "switch" : block = switch() else: block = Block(block_id) world.add_block(block, x * BLOCK_SIZE, y * BLOCK_SIZE)
def getWorldByName(self, worldName): """ Gets a L{World} domain object by its name """ w = World() w.name = worldName self.worldRepository.getWorld(w) return w
def blocks_recover(self, brick_list, world: World): """Recover the hidden bricks Parameters: brick_list (list): store the bricks to be recovered and their coordinate looks like this : [(brick_object, x, y),] """ for n in brick_list: brick, x, y = n world.add_block(brick, x, y)
def handle(self, context, packet): gameWorld = World() channel = context.channel session = channel.context.session session.gameSession.world = gameWorld aid = session.account.id gameWorld.wctx.channels[aid] = channel gameWorld.addSystem(LockLoadSystem(1)) gameWorld.eventCenter.fire(LoadInfoEvent(packet.characterId, channel))
def create_item(world: World, item_id: str, x: int, y: int, *args): """Create a new item instance and add it to the world based on the item_id. Parameters: world (World): The world where the item should be added to. item_id (str): The item identifier of the item to create. x (int): The x coordinate of the item. y (int): The y coordinate of the item. """ item_id = ITEMS[item_id] if item_id == "coin": item = Coin() else: item = DroppedItem(item_id) world.add_item(item, x * BLOCK_SIZE, y * BLOCK_SIZE)
def __init__(self, world_size, resource_mgr): # Inputs self.world_size = world_size self.resource_mgr = resource_mgr self.world = World(resource_mgr, world_size) self.debugging = False
def build(self) -> World: """Construct a new world containing all the added entities. The size of the world is determined by the maximum entity space occupied. Each entity builder is called during this construction. Raises: KeyError: If there is no associated builder for an entity id and no fallback builder has been set. """ world = World((self._width, self._height), self._block_size, gravity=self._gravity) for entity in self._entities: entity_id, x, y, *args = entity if entity_id not in self._builders: if self._fallback is None: raise KeyError(f"Unable to build world," f"no matching processor for entity id of {entity_id}") self._fallback(world, *entity) continue processor = self._builders[entity_id] processor(world, *entity) return world
class WorldPreparedTest(TestCase): def setUp(self): super(WorldPreparedTest, self).setUp() srcCharacter = Character.character(skill=ISkill.skill()) srcMockedContext = MockedChannelContext() self.srcMc = MoveController(srcCharacter) self.srcCc = CharacterController(srcMockedContext.session.account, srcCharacter) self.srcLc = LifeController(srcCharacter.maxLife) self.srcCardController = CardController(srcCharacter) self.srcECC = EffectChainController() self.srcEntity = Entity(0, components=[ self.srcMc, self.srcCc, self.srcLc, self.srcCardController, self.srcECC ]) desCharacter = Character.character(skill=ISkill.skill()) desMockedContext = MockedChannelContext() self.desMc = MoveController(desCharacter) self.desCc = CharacterController(desMockedContext.session.account, desCharacter) self.desLc = LifeController(srcCharacter.maxLife) self.desCardController = CardController(desCharacter) self.desECC = EffectChainController() self.desEntity = Entity(1, components=[ self.desMc, self.desCc, self.desLc, self.desCardController, self.desECC ]) self.turnSystem = TurnSystem() self.world = World() self.world.gameMap = GameMapPrefab().getMap() self.world.addSystem(self.turnSystem) coord = AxisCoord(row=0, col=0) self.srcLattice = self.world.gameMap.getLattice(coord) self.srcEntity.coord = coord coord = AxisCoord(row=0, col=-1) self.desLattice = self.world.gameMap.getLattice(coord) self.desEntity.coord = coord self.world.addEntity(self.srcEntity) self.world.addEntity(self.desEntity)
def get_world(self): for world_name in self._worlds: w = self._worlds[world_name] if w.can_accept: return world_name new_name = u'world#'.encode('utf-8') + str(self._next_world) self._next_world += 1 new_world = World(new_name, 64, 64, 2000, 10) self._worlds.setdefault(new_name, new_world) return new_name
def tmpDebugWorldRemoveMe(): # THIS IS FOR DEBUG ONLY!! w = World(platformClock=reactor) w.time = 13500.0 w.name = "Debug" w.width = 800 w.height = 600 w.spawn = (100, 199) w.isDay = True w.worldSurface = 200 w.rockLayer = 400 topLeftTs = TileSection() for y in range(4): w.tileSections.append([]) for x in range(6): ts = TileSection() ts.x = x ts.y = y for ty in range(50, SECTION_HEIGHT): for tx in range(SECTION_WIDTH): ts.setTile(tx, ty, ironTile) w.tileSections[y].append(ts) return w
def __init__(self, **kwargs): super(PlayWidget, self).__init__(**kwargs) # 330, 220 playRect = Rectangle(pos=(50, 40), size=(610, 400)) self.enemyGroup = InstructionGroup() self.world = World() # Create Players self.player1 = Player('p1') self.player2 = Player('p2') # Create Beam self.beam = Beam(self.player1, self.player2) # Create Score Label self.scoreLabel = Label(text='', pos=(295, 400)) self.timerLabel = Label(text='', pos=(560, 350), font_size=100, halign='right') self.updateScoreDisplay() self.updateTimerDisplay() # Background self.canvas.add(Color(0.2, 0.2, 0.2)) #self.canvas.add(playRect) self.canvas.add(self.enemyGroup) self.canvas.add(self.beam.canvas) self.canvas.add(self.player1.canvas) self.canvas.add(self.player2.canvas) self.canvas.add(self.scoreLabel.canvas) self.canvas.add(self.timerLabel.canvas) self.timeOfLastSpawn = 0 self.nextSpawnIn = 0 self.shouldClose = False
class GameScene(object): def __init__(self, world_size, resource_mgr): # Inputs self.world_size = world_size self.resource_mgr = resource_mgr self.world = World(resource_mgr, world_size) self.debugging = False def generate_world(self): self.world.supply = 20 # Spawn a few graveyards for _ in range(0, 5): graveyard = Graveyard(self.world, self.resource_mgr) graveyard.location = Vector2(randint(0, self.world_size[0]), randint(0, self.world_size[1])) graveyard.brain.set_state("spawning") self.world.add_entity(graveyard) def tick(self, time_passed): self.world.tick(time_passed) # ############## DRAWING ############## # def draw(self, surface): self.world.draw(surface) self._draw_ui(surface) def _draw_ui(self, surface): w_bound, h_bound = self.world.bounds zombies = "Zombies: " + str(self.world.get_entity_count("zombie")) surface.blit(self.resource_mgr.font.render(zombies, True, (0, 0, 0)), Vector2(5, h_bound - 20)) survivors = "Survivors: " + str(self.world.get_entity_count("survivor")) surface.blit(self.resource_mgr.font.render(survivors, True, (0, 0, 0)), Vector2(120, h_bound - 20)) res_str = "Supply Remaining: " + str(int(self.world.supply)) surface.blit(self.resource_mgr.font.render(res_str, True, (0, 0, 0)), Vector2(w_bound - 330, h_bound - 20)) if self.debugging: debug_text = 'Debugging' surface.blit(self.resource_mgr.font.render(debug_text, True, (0, 0, 0)), (0, 0)) # ############ MOUSE INPUT MGMT ############### # def handle_mouse_left_down(self, mouse_pos): self.world.spawn_entity(Survivor, mouse_pos[0], mouse_pos[1]) def handle_mouse_right_down(self, mouse_pos): self.world.spawn_entity(Supplies, mouse_pos[0], mouse_pos[1]) # ############ KEYBOARD INPUT MGMT ############### # def handle_tilde_key_down(self): """ Tilde key indicates a toggling of the debug mode. """ self.debugging = not self.debugging self.world.set_debug_mode(self.debugging)
class PlayWidget(Widget): frameNum = 0 score = 0 enemies = [] player1 = None player2 = None world = None roundFrames = FRAMERATE * 30 def __init__(self, **kwargs): super(PlayWidget, self).__init__(**kwargs) # 330, 220 playRect = Rectangle(pos=(50, 40), size=(610, 400)) self.enemyGroup = InstructionGroup() self.world = World() # Create Players self.player1 = Player('p1') self.player2 = Player('p2') # Create Beam self.beam = Beam(self.player1, self.player2) # Create Score Label self.scoreLabel = Label(text='', pos=(295, 400)) self.timerLabel = Label(text='', pos=(560, 350), font_size=100, halign='right') self.updateScoreDisplay() self.updateTimerDisplay() # Background self.canvas.add(Color(0.2, 0.2, 0.2)) #self.canvas.add(playRect) self.canvas.add(self.enemyGroup) self.canvas.add(self.beam.canvas) self.canvas.add(self.player1.canvas) self.canvas.add(self.player2.canvas) self.canvas.add(self.scoreLabel.canvas) self.canvas.add(self.timerLabel.canvas) self.timeOfLastSpawn = 0 self.nextSpawnIn = 0 self.shouldClose = False def setKeyReport(self, keyReport): self.keyReport = keyReport self.beam.setKeyReport(keyReport) def reset(self): self.shouldClose = False self.frameNum = 0 self.world.reset() self.player1.reset() self.player2.reset() self.beam.reset() self.player1.setCenterPos((200, 220)) self.player2.setCenterPos((460, 220)) self.score = 0 self.timeOfLastSpawn = 0 self.nextSpawnIn = 0 def cleanup(self): self.enemyGroup.clear() self.enemies = [] def spawnEnemy(self, enemyType): enemy = Enemy(enemyType) enemy.reset(False) enemy.setWorld(self.world) self.enemyGroup.add(enemy.canvas) centerPos = self.world.nextEnemyPos(enemy.offsetTheta) enemy.setCenterPos(centerPos) self.enemies.append(enemy) def update(self, dt): self.frameNum += 1 if self.frameNum > self.roundFrames: self.shouldClose = True return if self.frameNum % FRAMERATE == 0: self.updateTimerDisplay() self.world.update(dt) # Update Players self.player1.update(dt) self.player2.update(dt) self.spawnNewEnemies() # Update Enemies for enemy in self.enemies: enemy.update(dt) if self.beam.beamState == 0: self.beam.setIsColliding(False) else: collisions = self.getCollisions() if len(collisions) > 0: self.beam.setIsColliding(True) self.consumeEnemies(collisions, self.beam.beamState) else: self.beam.setIsColliding(False) self.clearDeadEnemies() # Update Beam self.beam.update(dt) def consumeEnemies(self, collisions, beamState): totalDelta = 0 for enemy in collisions: delta = enemy.decrement(beamState) totalDelta += delta if not totalDelta == 0: self.score += totalDelta self.updateScoreDisplay() def updateScoreDisplay(self): self.scoreLabel.text = 'Score: ' + str(self.score) def updateTimerDisplay(self): seconds = int(math.ceil((self.roundFrames - self.frameNum) / FRAMERATE)) if seconds > 5: self.timerLabel.color[3] = 0.3 else: self.timerLabel.color[3] = 1 if seconds > 3: self.timerLabel.color[0] = 1 self.timerLabel.color[1] = 1 self.timerLabel.color[2] = 1 else: self.timerLabel.color[0] = 0.6 self.timerLabel.color[1] = 0 self.timerLabel.color[2] = 0 self.timerLabel.text = str(seconds) def spawnNewEnemies(self): if self.timeOfLastSpawn + self.nextSpawnIn > self.frameNum: return enemyType = 'normal' if random.random() < 0.3: enemyType = 'other' self.spawnEnemy(enemyType) self.timeOfLastSpawn = self.frameNum if self.frameNum < 200: self.nextSpawnIn = 10 def clearDeadEnemies(self): deadEnemies = [] for enemy in self.enemies: if enemy.shouldRemove: deadEnemies.append(enemy) if len(deadEnemies) == 0: return aliveEnemies = [] for enemy in self.enemies: if not enemy.shouldRemove: aliveEnemies.append(enemy) # rebuild self.enemyGroup.clear() for enemy in aliveEnemies: self.enemyGroup.add(enemy.canvas) self.enemies = aliveEnemies def getCollisions(self): beamLineCoords = (self.player2.pos[0], self.player2.pos[1], self.player1.pos[0], self.player1.pos[1]) collisions = [] for enemy in self.enemies: if enemy.sprite.collidesWithLine(beamLineCoords): collisions.append(enemy) return collisions
raise NeverCallMeError, "Received excess data" def connectionLost(self): assert self.state == 'never', "Premature closure" print "Successful transaction with the game world!" reactor.stop( ) class TestClientFactory(ClientFactory): def __init__(self, world): self.world = world def startedConnecting(self, connector): print "Connecting" def buildProtocol(self, addr): return StatefulTestRig(self.world) def clientConnectionLost(self, connector, reason): print "Connection lost:", reason def clientConnectionFailed(self, connector, reason): raise ConnectionError, "Could not connect: "+reason if __name__ == '__main__': world = World(None) clientFactory = TestClientFactory(world) reactor.listenTCP(8001, world.getFactory( )) reactor.connectTCP('localhost', 8001, clientFactory) reactor.run( )
from game import plants from game.animals import Animal from brains.rand import RandomBrain import cProfile PLANTS = 50 ANIMALS = 40 PRECALC = 0 AUTO = True PROFILE = False def clear(): os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] ) world = World(); plants.generate_at_random(world, PLANTS) if PRECALC > 0: print "Precalculating %i moves..." % PRECALC for x in range(PRECALC): world.iterate() world.turn = 0 for x in range(ANIMALS): world.spawn(Animal, randrange(world.WIDTH), randrange(world.HEIGHT), RandomBrain()) x = '' while True:
#!/usr/bin/env python2 # Distributed under the terms of the GNU GPLv3 # Copyright 2010 Berin Smaldon from game.world import World from twisted.internet import reactor import sys if __name__ == '__main__': if len(sys.argv) > 1: bq = World(sys.argv[1]) else: bq = World('data/bq.meta') s = reactor.listenTCP(bq.getPort( ), bq.getFactory( )) bq.animate(reactor, s) reactor.run( )
def setUp(self): assertRaises(IOError, World, "doesnotexist.meta") self.world = World("wtester.meta")
def create_unknown(world: World, entity_id: str, x: int, y: int, *args): """Create an unknown entity.""" world.add_thing(Entity(), x * BLOCK_SIZE, y * BLOCK_SIZE, size=(BLOCK_SIZE, BLOCK_SIZE))
def readWorld(self): w = World() self.fileHandle = open(self.worldFilePath, 'rb') w.version = self.readInt32() worldNameLen = self.readUChar() w.name = self.fileHandle.read(worldNameLen) w.worldId = self.readInt32() w.leftWorld = self.readInt32() w.rightWorld = self.readInt32() w.topWorld = self.readInt32() w.bottomWorld = self.readInt32() w.height = self.readInt32() w.width = self.readInt32() spawnX = self.readInt32() spawnY = self.readInt32() w.spawn = (spawnX, spawnY) w.worldSurface = self.readDouble() w.rockLayer = self.readDouble() w.time = self.readDouble() w.isDay = self.readBoolean() w.moonPhase = self.readInt32() w.isBloodMoon = self.readBoolean() w.dungeonX = self.readInt32() w.dungeonY = self.readInt32() w.bossOneDowned = self.readBoolean() w.bossTwoDowned = self.readBoolean() w.bossThreeDowned = self.readBoolean() w.shadowOrbSmashed = self.readBoolean() w.spawnMeteor = self.readBoolean() w.shadowOrbCount = self.readUChar() w.invasionDelay = self.readInt32() w.invasionSize = self.readInt32() w.invasionType = self.readInt32() w.invasionX = self.readDouble() self.fileHandle.close() return w
controllerManager = GameControllerManager() controllerManager.load_joysticks_database('resources/gamecontrollerdb.txt') # debug: add keyboard num_joysticks = max(controllerManager.num_joysticks, 1) controllers = [ controllerManager.grab_controller() for n in range(num_joysticks) ] screen = Screen(args.width, args.height, 'Space Madness') if args.fullscreen: screen.full_screen = True screen.print_info() world = World(bounds=screen.viewport, controllers=controllers, stage=StageSky(screen.width, screen.height)) font = Font() font.load_bmfont_file('resources/fonts/prosto_one_16.txt') def draw_frame(screen): world.draw(screen) font.draw_string(screen, 16, f'fps:{app.fps}', 2, 2) def update_frame(delta_ms): world.bullet_mgr.recycle_all() world.physicsWorld.ClearForces()
class WorldTester(unittest.TestCase): def setUp(self): assertRaises(IOError, World, "doesnotexist.meta") self.world = World("wtester.meta") def test_basicInit(self): o = self.world.getByID(self, 1) unittest.assertNotEqual(o, None) o = self.world.getByID(self, 14890141) unittest.assertEqual(o, None) def test_store(self): r = self.world.getByID(1) o = BerinObject(self.world, r, oshort="umquloaxatl") # no confusion i = o.getID() o.setAttribute("id", 51421) self.world.store(o) unittest.assertEquals(r.getItem("umquloaxatl"), None) o = self.world.retrieve(i) unittest.assertEquals(o.getID(), i) o.pushItem(o) self.world.store(o) o = self.world.retrieve(i) unittest.assertEquals(o, o.getItem("umquloaxatl")) self.o = o def test_destroy(self): r = self.world.getByID(1) b = BerinObject(self.world, r, oshort="doomed object") b.moveTo(self.o) world.destroy(self.o) unittest.assertEquals(r.getItem(self.o.getAttribute("oshort")), None) unittest.assertEquals(self.world.getByID(self.o.getID()), None) unittest.assertEquals(self.world.getByID(b.getID()), None) unittest.assertFalse(b in self.o.contents) unittest.assertFalse(o in self.o.contents)