def start(self): self._game_maps = [] self._current_map = None tmx_path_i = os.path.join('assets', 'maps', 'indoor.tmx') tmx_path_o = os.path.join('assets', 'maps', 'field.tmx') self.indoor_tiles_resource = tiles.load(tmx_path_i) self.outdoor_tiles_resource = tiles.load(tmx_path_o) self.collision_manager = CollisionManagerGrid(**constants.collision_params) self.scrolling_manager = ScrollingManager() self.player = self._init_player() self._game_maps.append(GameMap(self.indoor_tiles_resource, self.scrolling_manager, self.collision_manager)) self._game_maps.append(GameMap(self.outdoor_tiles_resource, self.scrolling_manager, self.collision_manager)) self.change_map(0) self._spawn_player() self.add(self.scrolling_manager, z=0) self.add(MessageBox(), name='msg_box', z=2) # there's only one message box in the scene self.schedule(self._current_map.update) self.schedule(self.player.update) director.run(self)
def main(): global keyboard global scroller # This variable is going to become a scrolling manager to enable us to scroll along the map # Initialize director director.init(width=800, height=600, caption="In the beginning everything was Kay-O", autoscale=True, resizable=True) # Create player layer and add player onto it # This time make it a ScrollableLayer type rather than simply Layer player_layer = layer.ScrollableLayer() player = sprite.Sprite('images/mr-saturn.png') player_layer.add(player) # Sets initial position and velocity of player player.position = (750, 1200) player.velocity = (0, 0) # Set the sprite's movement class player.do(Player()) # Create a new ScrollingManager object so we can scroll the view along with the player # The ScrollingManager object lets us separate "world" coordinates and "screen" coordinates # In this way, we can keep track of where the player is across the entire map but keep the viewport local #(http://python.cocos2d.org/doc/api/cocos.layer.scrolling.html#cocos.layer.scrolling.ScrollingManager) scroller = layer.ScrollingManager() # Now we will create a map layer based on our TMX file # I called the ground layer "Ground" in the tmx file, which is what we specify here as an identifier # This is located in the <layer> tags in map.tmx # We do the same thing for TopLayer # See README in this folder for more information ground_layer = tiles.load('tiles/map.tmx')['Ground'] top_layer = tiles.load('tiles/map.tmx')['TopLayer'] # Creates a text layer and adds an instance of BigText() to it text_layer = BigText() # Add player sprite and player_layer to the ScrollingManager # We have also added a second argument to the add() calls # This is the z-index, which explicity determines the order of layers. # Here, the player has a z-index of 1 and the text has an index of 2 so it will overlay the player. # And 0 will be the background scroller.add(ground_layer, z = 0) scroller.add(top_layer, z = 1) scroller.add(player_layer, z = 1) # Here we initialize the scene with initial layer "scroller" which holds all of the layers main_scene = scene.Scene(scroller) # Here we add the text_layer containing the instance of BigText() to the main scene main_scene.add(text_layer, z = 2) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # Run the scene we've built in the window director.run(main_scene)
def __init__(self, edit_level_xml): super(EditorScene, self).__init__() self.manager = tiles.ScrollingManager(director.window) #if bg_level_xml: #level = tiles.load(bg_level_xml)[bg_level_id] #self.manager.append(level) #level.opacity = 100 #self.add(level, z=0) level_to_edit = tiles.load(edit_level_xml) mz = 0 for id, layer in level_to_edit.find(tiles.MapLayer): self.manager.add(layer, z=layer.origin_z) mz = max(layer.origin_z, mz) self.add(self.manager) s = TileSetLayer(level_to_edit) self.add(s, z=mz+2) e = TileEditorLayer(self.manager, level_to_edit, s, edit_level_xml) self.manager.add(e, z=mz+1) self.manager.set_focus(0, 0)
def main(): global keyboard, scroller from cocos.director import director director.init(width=600, height=300, do_not_scale=True, resizable=True) car_layer = layer.ScrollableLayer() car = cocos.sprite.Sprite('car.png') car_layer.add(car) car.position = (200, 100) car.max_forward_speed = 200 car.max_reverse_speed = -100 car.do(DriveCar()) scroller = layer.ScrollingManager() test_layer = tiles.load('road-map.xml')['map0'] scroller.add(test_layer) scroller.add(car_layer) main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == .75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(.75, 2)) elif key == pyglet.window.key.D: test_layer.set_debug(True) director.window.push_handlers(on_key_press) director.run(main_scene)
def main(): global keyboard, scroller from cocos.director import director director.init(width=960, height=640, autoscale=False, resizable=True) scroller = layer.ScrollingManager() test_layer = tiles.load('road-map.tmx')['map0'] scroller.add(test_layer) main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == .75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(.75, 2)) elif key == pyglet.window.key.D: test_layer.set_debug(True) director.window.push_handlers(on_key_press) director.run(main_scene)
def __init__(self): """initializer""" Scene.__init__(self) self.config = Config() self.gallery = Gallery() # creating map raw_map = tiles.load("{}/{}.{}".format(self.config.resources, "combat", self.config.map_format) ) self.tw = self.config.tile_width = raw_map.contents["combat"].tw snow_base = ColorLayer( 250, 250, 250, 255, director.window.width, director.window.height) self.add(snow_base, name="display_worldmap_snow") cz = 1 self.add(DisplayCombatMapscroll(0), z=cz, name="display_combat_mapscroll") cz +=1 padding_x, padding_y = self.get_initial_padding(raw_map) print('e') for layer_name in [ "combat"]: # TODO remove this hardcoded stuff, where is the Z value? cz += 1 self.get("display_combat_mapscroll").add(raw_map.contents[layer_name], z=cz, name=layer_name) #z=len(self.children), name=layer_name) self.get("display_combat_mapscroll").get(layer_name).set_view(padding_x, padding_y, director.window.width + padding_x, director.window.height + padding_y) print('e') cz +=1 self.get("display_combat_mapscroll").init_tactical_map() print('e') # self.add(DisplayWorldmapLauncher(), z=cz, name="display_worldmap_launcher") # cz +=1 self.MapInZoom=True print('e') self.display_combat_mapscroll=self.get("display_combat_mapscroll") print('e')
def __init__(self, hud): super().__init__() try: fullmap = load("mario-world1-1.tmx") except Exception as e: raise SystemExit(e) bg_map = fullmap["Background"] fg_map = fullmap["Foreground"] ob_map = fullmap["Objects"] tileset = fullmap["Mario"] fg_map.do(BlinkBricks()) fg_map.set_cell_opacity(64, 5, 0) scroller = ScrollingManager() scroller.add(bg_map, z=0) scroller.add(fg_map, z=2) scroller.add(GameLayer(hud, fg_map, ob_map, tileset), z=1) scroller.scale = 2.5 self.add(ColorLayer(107, 140, 255, 255), z=0) self.add(scroller, z=1) self.add(hud, z=10)
def main(): global keyboard, scroller director.init(width=800, height=600, autoscale=False, resizable=True) """ car_layer = layer.ScrollableLayer() car = cocos.sprite.Sprite('car.png') car_layer.add(car) car.position = (200, 100) car.max_forward_speed = 200 car.max_reverse_speed = -100 car.do(DriveCar()) """ # scroller.add(car_layer) level_map = tiles.load('test-field.tmx') bg_layer = level_map['bg'] walls_layer = level_map['walls'] scroller = layer.ScrollingManager() scroller.add(bg_layer) scroller.add(walls_layer) main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) """ def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == .75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(.75, 2)) elif key == pyglet.window.key.D: bg_layer.set_debug(True) director.window.push_handlers(on_key_press) """ director.run(main_scene)
def CreateTileMap(self): # First load the file - This seems awfully slow... self.test_layer = tiles.load('Maps/Map-Ch1-St1.tmx') # Extract the background layer bg_layer = self.test_layer['Background'] # Add background layer to the scroller. DG.scroller.add(bg_layer) # Extract the properties into a dictionary tileDataArray = {} x = 0 y = 0 for col in bg_layer.cells: for cell in col: tileDataArray[x,y] = TileData(cell.position,cell.tile.properties['MovementCost'],cell.tile,cell) y += 1 x += 1 y = 0 DG.tileData = tileDataArray # Add the background layer as a permanent field DG.bg = bg_layer
def map(self, width, height): """ Creates and returns a new randomly generated map """ template = ti.load(os.path.join(script_dir, 'assets', 'template.tmx'))['map0'] #template.set_view(0, 0, template.px_width, template.px_height) template.set_view(0, 0, width * template.tw, height * template.th) # TODO: Save the generated map. #epoch = int(time.time()) #filename = 'map_' + str(epoch) + '.tmx' # Draw borders border_x = template.cells[width] for y in xrange(0, height + 1): border_x[y].tile = template.cells[0][0].tile for x in xrange(0, width): template.cells[x][height].tile = template.cells[0][0].tile # Start within borders #self.recursive_division(template.cells, 3, (template.px_width/template.tw)-1, (template.px_height/template.th)-1, 0, 0) self.recursive_division(template.cells, 3, width, height, 0, 0) return template
def __init__(self): super(World, self).__init__() self.player = Car(self) self.newMap(30, 20) self.map = tiles.load('tilemap.xml')['map0'] self.checkSpawnPoint() self.exitPoint = self.checkExitPoint() self.blockKeys = 0.0 self.blockKeysFull = 0.3 self.bindings = { key.LEFT: 'left', key.RIGHT: 'right', key.UP: 'up', key.DOWN: 'down', key.E: 'down_level', key.Z: 'scale', } buttons = {} for k in self.bindings: buttons[self.bindings[k]] = 0 self.buttons = buttons self.overlaidCells = [] #self.overlay = layer.util_layers.ColorLayer(0, 0, 0, 128, 20*128, 30*128) #self.map.add(self.overlay) self.carLayer = layer.ScrollableLayer() self.carLayer.add(self.player) self.manager = layer.ScrollingManager() self.manager.add(self.map) self.manager.add(self.carLayer) self.add(self.manager) self.schedule(self.update)
def __init__(self, edit_level_xml): super(EditorScene, self).__init__() self.manager = tiles.ScrollingManager(director.window) #if bg_level_xml: #level = tiles.load(bg_level_xml)[bg_level_id] #self.manager.append(level) #level.opacity = 100 #self.add(level, z=0) level_to_edit = tiles.load(edit_level_xml) mz = 0 for id, layer in level_to_edit.find(tiles.MapLayer): self.manager.add(layer, z=layer.origin_z) mz = max(layer.origin_z, mz) self.add(self.manager) s = TileSetLayer(level_to_edit) self.add(s, z=mz + 2) e = TileEditorLayer(self.manager, level_to_edit, s, edit_level_xml) self.manager.add(e, z=mz + 1) self.manager.set_focus(0, 0)
def main(): global keyboard, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False, resizable=True) car_layer = layer.ScrollableLayer() car = cocos.sprite.Sprite('car.png') car_layer.add(car) car.position = (200, 100) car.max_forward_speed = 200 car.max_reverse_speed = -100 car.do(DriveCar()) scroller = layer.ScrollingManager() test_layer = tiles.load('road-map.tmx')['map0'] scroller.add(test_layer) scroller.add(car_layer) main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == .75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(.75, 2)) elif key == pyglet.window.key.D: test_layer.set_debug(True) director.window.push_handlers(on_key_press) director.run(main_scene)
def __init__(self): super().__init__() level_map = tiles.load('test-field.tmx') bg_layer = level_map['bg'] walls_layer = level_map['walls'] scroller = scrolling.ScrollingManager() scroller.add(bg_layer) scroller.add(walls_layer) self.add(scroller)
def main(): global keyboard, tilemap, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) # create a layer to put the player in player_layer = layer.ScrollableLayer() # NOTE: the anchor for this sprite is in the CENTER (the cocos default) # which means all positioning must be done using the center of its rect player = cocos.sprite.Sprite('witch-standing.png') player_layer.add(player) player.do(PlatformerController()) # add the tilemaps and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() fullmap = tiles.load('platformer-map.xml') tilemap_walls = fullmap['walls'] scroller.add(tilemap_walls, z=0) tilemap_decoration = fullmap['decoration'] scroller.add(tilemap_decoration, z=1) scroller.add(player_layer, z=2) # set the player start using the player_start token from the map start = tilemap_decoration.find_cells(player_start=True)[0] r = player.get_rect() # align the mid bottom of the player with the mid bottom of the start cell r.midbottom = start.midbottom # player image anchor (position) is in the center of the sprite player.position = r.center # give a collision handler to the player mapcollider = mapcolliders.RectMapCollider(velocity_on_bump='slide') player.collision_handler = mapcolliders.make_collision_handler( mapcollider, tilemap_walls) # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # allow display info about cells / tiles def on_key_press(key, modifier): if key == pyglet.window.key.D: tilemap_walls.set_debug(True) director.window.push_handlers(on_key_press) # run the scene director.run(platformer_scene)
def main(): global keyboard, tilemap, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) # create a layer to put the player in player_layer = layer.ScrollableLayer() # NOTE: the anchor for this sprite is in the CENTER (the cocos default) # which means all positioning must be done using the center of its rect player = cocos.sprite.Sprite('witch-standing.png') player_layer.add(player) player.do(PlatformerController()) # add the tilemaps and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() fullmap = tiles.load('platformer-map.xml') tilemap_walls = fullmap['walls'] scroller.add(tilemap_walls, z=0) tilemap_decoration = fullmap['decoration'] scroller.add(tilemap_decoration, z=1) scroller.add(player_layer, z=2) # set the player start using the player_start token from the map start = tilemap_decoration.find_cells(player_start=True)[0] r = player.get_rect() # align the mid bottom of the player with the mid bottom of the start cell r.midbottom = start.midbottom # player image anchor (position) is in the center of the sprite player.position = r.center # give a collision handler to the player mapcollider = mapcolliders.RectMapCollider(velocity_on_bump='slide') player.collision_handler = mapcolliders.make_collision_handler( mapcollider, tilemap_walls) # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # allow display info about cells / tiles def on_key_press(key, modifier): if key == pyglet.window.key.D: tilemap.set_debug(True) director.window.push_handlers(on_key_press) # run the scene director.run(platformer_scene)
def main(): global keyboard, walls, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) # create the scrolling manager that will hold all game entities scroller = layer.ScrollingManager() # load the map layer of interest and add to the level walls = tiles.load('tmx_collision.tmx')['walls'] assert isinstance(walls, tiles.TmxObjectLayer) scroller.add(walls, z=0) # create a layer to put the player in; it will care for player scroll player_layer = layer.ScrollableLayer() # NOTE: the anchor for this sprite is in the CENTER (the cocos default) # which means all positioning must be done using the center of its rect player = cocos.sprite.Sprite('witch-standing.png') player_layer.add(player) player.do(PlatformerController2()) scroller.add(player_layer, z=1) # set the player start using the object with the 'player_start' property player_start = walls.find_cells(player_start=True)[0] # for convenience the player start was give the same dimensions as player, # so put player.center over player start center player.position = player_start.center # set focus so the player is in view scroller.set_focus(*player.position) # extract the player_start, which is not a wall walls.objects.remove(player_start) # give a collision handler to the player mapcollider = mapcolliders.TmxObjectMapCollider() mapcollider.on_bump_handler = mapcollider.on_bump_slide player.collision_handler = mapcolliders.make_collision_handler( mapcollider, walls) # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # run the scene director.run(platformer_scene)
def __init__(self, buildSelectScene): super(MainMap, self).__init__() self.build_select_scene = buildSelectScene self.map_loaded = tiles.load('background_map.tmx')['tile_layer_1'] self.add(self.map_loaded, z=0) center = self.map_loaded.cells[10][7].center self.map_loaded.set_view(5, 5, 15, 15, 0, 0) self.set_focus(center[0], center[1]) self.hexes = []
def main(): global keyboard, walls, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) # create the scrolling manager that will hold all game entities scroller = layer.ScrollingManager() # load the map layer of interest and add to the level walls = tiles.load('tmx_collision.tmx')['walls'] assert isinstance(walls, tiles.TmxObjectLayer) scroller.add(walls, z=0) # create a layer to put the player in; it will care for player scroll player_layer = layer.ScrollableLayer() # NOTE: the anchor for this sprite is in the CENTER (the cocos default) # which means all positioning must be done using the center of its rect player = cocos.sprite.Sprite('witch-standing.png') player_layer.add(player) player.do(PlatformerController2()) scroller.add(player_layer, z=1) # set the player start using the object with the 'player_start' property player_start = walls.find_cells(player_start=True)[0] # for convenience the player start was give the same dimensions as player, # so put player.center over player start center player.position = player_start.center # set focus so the player is in view scroller.set_focus(*player.position) # extract the player_start, which is not a wall walls.objects.remove(player_start) # give a collision handler to the player mapcollider = mapcolliders.TmxObjectMapCollider() mapcollider.on_bump_handler = mapcollider.on_bump_slide player.collision_handler = mapcolliders.make_collision_handler(mapcollider, walls) # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # run the scene director.run(platformer_scene)
def __init__(self): super(Level1Scene, self).__init__() global keyboard, scroller, game_controller, map_layer scroller = ScrollingManager() keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) map_layer = load("tiles/map1/map_3.tmx")['base'] map_h = (map_layer.cells[-1][-1].y // map_layer.tw + 1) map_layer_bg_0 = load("tiles/map1/map_3.tmx")['background'] map_layer_bg_1 = load("tiles/map1/map_3.tmx")['decorations'] main_layer = MainLayer() scroller.add(map_layer_bg_0, z=-2) scroller.add(map_layer_bg_1, z=-1) scroller.add(map_layer, z=0) scroller.add(main_layer, z=1) self.add(scroller)
def load_from_file_location(self, filename): """ Create scrollable Level from tmx map """ scroller = self.scroller data = tiles.load(filename) back = data['Background'] force = data['Player Level'] scripts = data['Scripts'] player_layer = Location_Layer(scripts, force, scroller, self.keyboard, self.mouse) self.locations[self.x][self.y] = [force, back, player_layer] return self._create_location(force, back, player_layer)
def newLevel(self): # TODO Make this better self.killChildren() self.manager = layer.ScrollingManager() self.newMap(30, 30) self.map = tiles.load('tilemap.xml')['map0'] self.checkSpawnPoint() self.carLayer = layer.ScrollableLayer() self.carLayer.add(self.player) self.manager = layer.ScrollingManager() self.manager.add(self.map) self.manager.add(self.carLayer) self.add(self.manager)
def main(): global keyboard, walls, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) # add the tilemap and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() walls = tiles.load('tmx_collision.tmx')['walls'] assert isinstance(walls, tiles.TmxObjectLayer) scroller.add(walls, z=0) # make the function to handle collision between actors and walls mapcollider = TmxObjectMapCollider() mapcollider.on_bump_handler = mapcollider.on_bump_bounce fn_collision_handler = mapcolliders.make_collision_handler( mapcollider, walls) # make the function to set visual focus at position fn_set_focus = scroller.set_focus # create a layer to put the player in actors_layer = layer.ScrollableLayer() ball = Ball((300, 300), (600, 600), fn_collision_handler, fn_set_focus, (255, 0, 255)) actors_layer.add(ball) scroller.add(actors_layer, z=1) # set the player start using the object with the 'player_start' property player_start = walls.find_cells(player_start=True)[0] ball.position = player_start.center # set focus so the player is in view scroller.set_focus(*ball.position) # extract the player_start, which is not a wall walls.objects.remove(player_start) # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # run the scene director.run(platformer_scene)
def __init__(self): super(TestScene, self).__init__() scroller = layer.ScrollingManager() scrollable = tiles.load('road-map.tmx')['map0'] scroller.add(scrollable) self.add(scroller) template_action = (CallFunc(scroller.set_focus, 0, 0) + Delay(1) + CallFunc(scroller.set_focus, 768, 0) + Delay(1) + CallFunc(scroller.set_focus, 768, 768) + Delay(1) + CallFunc(scroller.set_focus, 1500, 768) + Delay(1) + ScaleTo(0.75, 1) + Delay(1) + CallFunc(scrollable.set_debug, True) + Delay(1) + CallFunc(director.window.set_size, 800, 600)) scroller.do(template_action)
def main(): director.init(800, 600, resizable=True) bg = cocos.layer.ColorLayer(0, 127, 127, 255) map_layer = load("maps/world.tmx")["tiles"] # cocos.tiles.RectMapLayer car_layer = CarLayer() scroller = ScrollingManager() # cocos.layer.scrolling.ScrollingManager scroller.add(map_layer) scroller.add(car_layer) print(scroller) # main_scene = Scene(ActionMenu(actions)) main_scene = Scene(TransitionMenu(transitions)) director.run(Scene(scroller))
def main(): global keyboard, tilemap, scroller from cocos.director import director director.init(width=960, height=540, autoscale=True, fullscreen=False) print(description) # create a layer to put the player in player_layer = layer.ScrollableLayer() # NOTE: the anchor for this sprite is in the CENTER (the cocos default) # which means all positioning must be done using the center of its rect player = cocos.sprite.Sprite("res/fez.png") player_layer.add(player) player.do(PlatformerController()) # add the tilemap and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() tilemap = tiles.load("res/tile_map1.xml")["level0"] # tilemap = tiles.load('platformer-map.xml')['level0'] scroller.add(tilemap, z=0) scroller.add(player_layer, z=1) # set the player start using the player_start token from the tilemap start = tilemap.find_cells(player_start=True)[0] r = player.get_rect() # align the mid bottom of the player with the mid bottom of the start cell r.midbottom = start.midbottom # player image anchor (position) is in the center of the sprite player.position = r.midtop # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(70, 200, 255, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # allow display info about cells / tiles def on_key_press(key, modifier): if key == pyglet.window.key.D: tilemap.set_debug(True) director.window.push_handlers(on_key_press) # run the scene director.run(platformer_scene)
def __init__(self, g_c): super(Level1Scene, self).__init__() global scroller, game_controller, map_layer game_controller = g_c scroller = ScrollingManager() director.window.push_handlers(keyboard) map_layer = load("tiles/map1/map_3.tmx")['base'] map_h = (map_layer.cells[-1][-1].y // map_layer.tw + 1) map_layer_bg_0 = load("tiles/map1/map_3.tmx")['background'] map_layer_bg_1 = load("tiles/map1/map_3.tmx")['decorations'] main_layer = MainLayer((500, 500)) scroller.add(map_layer_bg_0, z=-2) scroller.add(map_layer_bg_1, z=-1) scroller.add(map_layer, z=0) scroller.add(main_layer, z=1) self.add(scroller) self.schedule_interval(main_layer.update, 1 / 30) # 30 times per second
def main(): global keyboard, walls, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) # add the tilemap and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() walls = tiles.load('tmx_collision.tmx')['walls'] assert isinstance(walls, tiles.TmxObjectLayer) scroller.add(walls, z=0) # make the function to handle collision between actors and walls mapcollider = TmxObjectMapCollider() mapcollider.on_bump_handler = mapcollider.on_bump_bounce fn_collision_handler = mapcolliders.make_collision_handler(mapcollider, walls) # make the function to set visual focus at position fn_set_focus = scroller.set_focus # create a layer to put the player in actors_layer = layer.ScrollableLayer() ball = Ball((300, 300), (600, 600), fn_collision_handler, fn_set_focus, (255, 0, 255)) actors_layer.add(ball) scroller.add(actors_layer, z=1) # set the player start using the object with the 'player_start' property player_start = walls.find_cells(player_start=True)[0] ball.position = player_start.center # set focus so the player is in view scroller.set_focus(*ball.position) # extract the player_start, which is not a wall walls.objects.remove(player_start) # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # run the scene director.run(platformer_scene)
def __init__(self,level_xml,speed=30, contents=None): super(GameMapBaseScene, self).__init__(contents) self.manager = ScrollingManager() self.add(self.manager) level = tiles.load(level_xml) mz = 0 mx = 0 for id, layer in level.find(tiles.MapLayer): self.manager.add(layer, z=layer.origin_z) mz = max(layer.origin_z, mz) mx = max(layer.px_width, mx) self.level = level self.px_width = mx
def __init__(self): super(TestScene, self).__init__() scroller = layer.ScrollingManager() scrollable = tiles.load('road-map.xml')['map0'] scroller.add(scrollable) self.add(scroller) template_action = ( CallFunc(scroller.set_focus, 0, 0) + Delay(1) + CallFunc(scroller.set_focus, 768, 0) + Delay(1) + CallFunc(scroller.set_focus, 768, 768) +Delay(1) + CallFunc(scroller.set_focus, 1500, 768) +Delay(1) + ScaleTo(0.75, 1) + CallFunc(scrollable.set_debug, True) + Delay(1) + CallFunc(director.window.set_size, 800, 600) ) scroller.do(template_action)
def __init__(self, level_xml, speed=30, contents=None): super(GameMapBaseScene, self).__init__(contents) self.manager = ScrollingManager() self.add(self.manager) level = tiles.load(level_xml) mz = 0 mx = 0 for id, layer in level.find(tiles.MapLayer): self.manager.add(layer, z=layer.origin_z) mz = max(layer.origin_z, mz) mx = max(layer.px_width, mx) self.level = level self.px_width = mx
def main(): from cocos.director import director director.init(width=800, height=600, autoscale=False, resizable=True) glClearColor(255, 255, 255, 255) scroller = layer.ScrollingManager() maploaded = tiles.load('obj.tmx') test_layer = maploaded["tiles_layer_1"] scroller.add(test_layer) object_layer = maploaded['test_object_layer'] scroller.add(object_layer) main_scene = cocos.scene.Scene(scroller) print(test_layer.px_width, test_layer.px_height) scroller.set_focus(test_layer.px_width // 2, test_layer.px_height // 2) director.run(main_scene)
def main(): from cocos.director import director director.init(width=800, height=600, autoscale=False, resizable=True) glClearColor(255, 255, 255, 255) scroller = layer.ScrollingManager() maploaded = tiles.load('obj.tmx') test_layer = maploaded["tiles_layer_1"] scroller.add(test_layer) object_layer = maploaded['test_object_layer'] scroller.add(object_layer) main_scene = cocos.scene.Scene(scroller) print(test_layer.px_width , test_layer.px_height) scroller.set_focus(test_layer.px_width // 2, test_layer.px_height //2) director.run(main_scene)
def main(): global keyboard, walls, scroller from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) car_layer = layer.ScrollableLayer() car = cocos.sprite.Sprite('car.png') car_layer.add(car) car.position = (200, 100) car.max_forward_speed = 200 car.max_reverse_speed = -100 worker_action = car.do(DriveCar()) # add the map and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() walls = tiles.load('tmx_collision.tmx')['walls'] assert isinstance(walls, tiles.TmxObjectLayer) worker_action.walls = walls scroller.add(walls, z=0) scroller.add(car_layer, z=1) player_start = walls.find_cells(player_start=True)[0] # extract the player_start, which is not a wall walls.objects.remove(player_start) # give car access to the walls so it can change colors car.walls = walls # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # run the scene director.run(platformer_scene)
def main(): global walls, scroller, platformer_scene from cocos.director import director director.init(width=800, height=600, autoscale=False) print(description) # add the tilemap and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() walls = tiles.load('tmx_collision.tmx')['walls'] assert isinstance(walls, tiles.TmxObjectLayer) scroller.add(walls, z=0) # make the function to handle collision between actors and walls mapcollider = TmxObjectMapCollider() mapcollider.on_bump_handler = mapcollider.on_bump_bounce fn_collision_handler = mapcolliders.make_collision_handler(mapcollider, walls) # make the function to set visual focus at position fn_set_focus = scroller.set_focus scroller.add(Actors(fn_collision_handler), z=1) # set the player start using the object with the 'player_start' property player_start = walls.find_cells(player_start=True)[0] # extract the player_start, which is not a wall walls.objects.remove(player_start) # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # set focus scroller.set_focus(300, 300) # handle zoom and pan commands director.window.push_handlers(on_key_press) # run the scene director.run(platformer_scene)
def main(): global keyboard, tilemap, scroller from cocos.director import director director.init(width=800, height=600, do_not_scale=True) print description # create a layer to put the player in player_layer = layer.ScrollableLayer() # NOTE: the anchor for this sprite is in the CENTER (the cocos default) # which means all positioning must be done using the center of its rect player = cocos.sprite.Sprite('witch-standing.png') player_layer.add(player) player.do(PlatformerController()) # add the tilemap and the player sprite layer to a scrolling manager scroller = layer.ScrollingManager() tilemap = tiles.load('platformer-map.xml')['level0'] scroller.add(tilemap, z=0) scroller.add(player_layer, z=1) # set the player start using the player_start token from the tilemap start = tilemap.find_cells(player_start=True)[0] r = player.get_rect() # align the mid bottom of the player with the mid bottom of the start cell r.midbottom = start.midbottom # player image anchor (position) is in the center of the sprite player.position = r.center # construct the scene with a background layer color and the scrolling layers platformer_scene = cocos.scene.Scene() platformer_scene.add(layer.ColorLayer(100, 120, 150, 255), z=0) platformer_scene.add(scroller, z=1) # track keyboard presses keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # run the scene director.run(platformer_scene)
def loadLvl(level, gamemode): global scroller global player_layer global player global fullmap global gamemoderun global start global r global mapcollider global tilemap_decorations, tilemap_walls global bgLayer try: fullmap = tiles.load(level.datapath) tilemap_walls = fullmap["walls"] tilemap_decorations = fullmap["decorations"] scroller.add(bgLayer, z=-2) scroller.add(tilemap_decorations, z=-1) scroller.add(tilemap_walls, z=0) scroller.add(player_layer, z=1) start = tilemap_walls.find_cells(player_start=True)[0] r = player.get_rect() r.midbottom = start.midbottom player.position = r.center mapcollider = mapcolliders.RectMapCollider(velocity_on_bump="slide") player.collision_handler = mapcolliders.make_collision_handler( mapcollider, tilemap_walls) gamemoderun = player.do(gamemode.main()) except Exception as e: # TODO: if cfg.configuration["Debug"]["developer"] == "False": logger.addLog( "An error was caught rendering the level.\n" + str(e), logger.loglevel["error"]) else: raise e
def main(): global tilemap, keyboard, scroller from cocos.director import director director.init(width=800,height=600, do_not_scale=True, resizable=True) actor_layer = layer.ScrollableLayer() actor = cocos.sprite.Sprite('car.png') actor_layer.add(actor) actor.position = (200,100) actor.do(ActorController()) scroller = layer.ScrollingManager() tilemap = tiles.load('desert.tmx')['Ground'] scroller.add(tilemap) scroller.add(actor_layer) main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) director.run(main_scene)
def main(): # Declare these as global so they can be accessed within class methods. global keyboard global scroller # Initialize the window. director.init(width=800, height=600, do_not_scale=True, resizable=True) # Create a layer and add a sprite to it. player_layer = layer.ScrollableLayer() me = sprite.Sprite('human-female.png') player_layer.add(me) # Set initial position and velocity. me.position = (100, 100) me.velocity = (0, 0) # Set the sprite's movement class. me.do(Me()) # Create scroller object and load tiles. scroller = layer.ScrollingManager() map_layer = tiles.load('tiles/map.xml')['map0'] # Add map and player layers. scroller.add(map_layer) scroller.add(player_layer) # Create a scene and set its initial layer. main_scene = scene.Scene(scroller) # Attach a KeyStateHandler to the keyboard object. keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # Play the scene in the window. director.run(main_scene)
def load_xml(self, level_xml): try: self.remove(self.manager) self.remove(self.dialog_layer) self.map_layer.walk(self.map_layer.remove) except: pass self.manager = cocos.layer.ScrollingManager() self.add(self.manager) level = tiles.load(level_xml) mz = 0 mx = 0 my = 0 for id, layer in level.find(tiles.MapLayer): self.manager.add(layer, z=layer.origin_z) self.active_layer = layer mz = max(layer.origin_z, mz) mx = max(layer.px_width, mx) my = max(layer.px_height, my) self.level = level self.mx = mx self.my = my self.mz = mz self.add(self.dialog_layer,z = mz + 2) self.tilesets = [] for id,t in level.findall(tiles.TileSet): self.tilesets.append(t) # print "id is %s"%id # print "t is %s"%t # print dir(t) self.reload_tileset() self.level_xml = level_xml self.level_edited = level
def main(): global keyboard, scroller, old_ij, old_cell, old_highlighted_color from cocos.director import director director.init(width=600, height=300, autoscale=False, resizable=True) car_layer = layer.ScrollableLayer() car = cocos.sprite.Sprite('car.png') car_layer.add(car) car.position = (200, 100) car.max_forward_speed = 200 car.max_reverse_speed = -100 car.do(DriveCar()) scroller = layer.ScrollingManager() map_loaded = tiles.load('hexmap.tmx') # In Tiled we named 'tile_layer_1' our sample layer test_layer = map_loaded['tile_layer_1'] tint_green_hexmap_borders(test_layer) scroller.add(test_layer) scroller.add(car_layer) old_ij = 'nonexist' old_highlighted_color = None old_cell = None main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == .75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(.75, 2)) elif key == pyglet.window.key.D: test_layer.set_debug(True) elif key == pyglet.window.key.Q: tint_red_hexmap_borders(test_layer) director.window.push_handlers(on_key_press) def on_mouse_motion(x, y, dx, dy ): global scroller, old_ij, old_cell, old_highlighted_color #vh, vy = director.get_virtual_coordinates(x, y) vx, vy = scroller.screen_to_world(x,y) ij = test_layer.get_key_at_pixel(vx, vy) if ij == old_ij: return # restore color if old_cell: p, q = old_ij if old_highlighted_color is None: test_layer.set_cell_color(p, q, (255, 255, 255)) del old_cell.properties['color4'] else: test_layer.set_cell_color(p, q, old_highlighted_color[:3]) # record info and set color old_ij = ij i, j = ij print(i,j) old_cell = test_layer.get_cell(i, j) if old_cell is None: return old_highlighted_color = old_cell.properties.get('color4', None) test_layer.set_cell_color(i, j, (255, 0, 0)) director.window.push_handlers(on_mouse_motion) director.run(main_scene)
from cocos import tiles, layer, actions class HelloWorld(cocos.layer.Layer): def __init__(self): self.back_layer = tiles.load('test.tmx')['Background'] scroller = layer.ScrollingManager() scroller.add(self.back_layer) if __name__ == '__main__': # director init takes the same arguments as pyglet.window cocos.director.director.init() # We create a new layer, an instance of HelloWorld #hello_layer = HelloWorld () tilemap = tiles.load('test.tmx') back_layer = tilemap['Background'] objects = tilemap['Objects'] start = objects['SpawnPoint'] scroller = layer.ScrollingManager() scroller.add(back_layer) # A scene that contains the layer hello_layer main_scene = cocos.scene.Scene (scroller) # And now, start the application, starting with main_scene cocos.director.director.run (main_scene) # or you could have written, without so many comments: # director.run( cocos.scene.Scene( HelloWorld() ) )
class GameObj: my_director = director my_director.init() map_layer = load('map01.tmx')['solid'] scroller = ScrollingManager() keyboard = key.KeyStateHandler()
self.y += math.cos(r) * s scroller.set_focus(self.x, self.y) if __name__ == "__main__": from cocos.director import director director.init(width=600, height=300, do_not_scale=True) car_layer = tiles.ScrollableLayer() car = CarSprite('car.png') car.x=200 car.y=100 car.schedule(car.update) car_layer.add(car) scroller = tiles.ScrollingManager() test_layer = tiles.load('road-map.xml')['map0'] scroller.add(test_layer) scroller.add(car_layer) main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == .75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(.75, 2)) elif key == pyglet.window.key.D:
# For this scene, we'll be using a map with a high rectangular block that we don't want the player to be able to pass # Just as before, I start by initializing the director director.init(width=700, height=500, autoscale=False, resizable=True) # This is because, as stated before, many other objects depend on the director being initialized # And, one again, we set the keyboard and scrolling managers scroller = ScrollingManager() keyboard = key.KeyStateHandler() # I'll also throw in the line that pushes Cocos's handlers to the keyboard object director.window.push_handlers(keyboard) mapLayer = load("mapa.tmx")["platformy"] # This time we'll make an action that extends both the Action class and the new RectMapCollider # The RectMapCollider, you guessed it, lets us collide with rectmaps (A.K.A. tilemaps) class GameAction(Action, RectMapCollider): # To begin, we'll add a function for when the Action starts # I use the start function instead of an __init__ function because of the way the Action parent class is structured def start(self): # We simply set the velocity of the target sprite to zero self.target.velocity = 0, 0 # We also tell the game that our sprite is starting on the ground self.on_ground = True def on_bump_handler(self, vx, vy):
def __init__(self): self.back_layer = tiles.load('test.tmx')['Background'] scroller = layer.ScrollingManager() scroller.add(self.back_layer)
position = self.target.get_rect().copy() # get rekt position.x += dx position.y += dy self.target.position = position.center scroller.set_focus(*position.center) class PlayerLayer(ScrollableLayer): def __init__(self): super(PlayerLayer, self).__init__() spritesheet = image.load('dude.png') frames = image.ImageGrid(spritesheet, 4, 3) self.sprite = PlayerSprite() self.add(self.sprite) self.sprite.do(PlayerAction()) player_layer = PlayerLayer() MapLayer = load('test.tmx')['base'] scroller.add(MapLayer) scroller.add(player_layer) director.window.push_handlers(keyboard) director.run(Scene(scroller))
__author__ = 'fyabc' from cocos.tiles import load from cocos.layer import ScrollingManager from cocos.director import director from cocos.scene import Scene # This code might seem odd as there are no classes or functions or anything... # That's because when we load a map, it generates that Layer for us # We start off by initializing the director. This is important, as we need the director for the rest of the code to work director.init() # Next we load the map, and we specifically state what layer of the map we want to load MapLayer = load("assets/mapmaking.tmx")["map0"] # If you want to, check the mapmaking.tmx file in the assets folder to see where I declare map0 # Otherwise, make sure you name the map properly in Tiled and refer to that name in the brackets after the load function # Here is something new! I make a ScrollingManager object to contain my map layer scroller = ScrollingManager() # What the ScrollingManager does is, you guessed it, manage scrolling from us # Cocos spares us the pain of having to deal with adding support for the map scrolling when you move to the sides of it # From here we simply add the MapLayer we made out of the map to the ScrollingManager scroller.add(MapLayer) # And then we make a scene out of the ScrollingManager and run it in the director! director.run(Scene(scroller)) # I highly recommend you try making an easy program like this with your own map
def __init__(self, *args, **kwargs): super(ScrollingManager, self).__init__(*args, **kwargs) self.map_layer = load("maps/world.tmx")["tiles"] self.add(self.map_layer)
from cocos.tiles import load from cocos.layer import ScrollingManager from cocos.director import director from cocos.scene import Scene director.init() MapLayer = load("assets/mapmaking.tmx")["map0"] scroller = ScrollingManager() scroller.add(MapLayer) director.run(Scene(scroller))
def on_key_release(self, k, _): self.pressed[k] = 0 def on_mouse_press(self, x, y, buttons, modifiers): world_x, world_y = self.scroller.screen_to_world(x, y) cell = self.obstacle_layer.get_at_pixel(world_x, world_y) cell.tile = self.tileset[46] self.obstacle_layer.set_dirty() def update(self, dt): self.actor.update_position(dt, self.pressed) if __name__ == "__main__": director.init(caption="Ball Drops", width=320, height=416) map = load("map.tmx") background_layer = map["background"] obstacle_layer = map["obstacle"] objects = map["objects"] tileset = map["tileset"] scroller = ScrollingManager() scroller.add(background_layer, z=0) scroller.add(obstacle_layer, z=1) scroller.add(GameLayer(obstacle_layer, objects, tileset), z=2) scene = Scene() scene.add(scroller) director.run(scene)
def main(): global keyboard, scroller, game_map # 初始化创建窗口 director.init(width=800, height=640, do_not_scale=True, resizable=True) # 创建坦克图层 tank_layer = layer.ScrollableLayer() # 创建坦克对象 tank = cocos.sprite.Sprite(image=resources.tank_image, position=(340, 80)) # 把坦克对象添加到坦克图层中 tank_layer.add(tank) # 设置坦克的最大前进和后退速度 tank.max_forward_speed = 200 tank.max_reverse_speed = -100 # 坦克对象执行一个action tank.do(TankController()) # 创建滚动图层管理器,添加游戏背景图层和坦克图层到图层管理器 scroller = layer.ScrollingManager() tank_map = tiles.load("test_tank.tmx") print type(tank_map) game_map = tank_map["backgroud"] # print tank_map.get_resource('tank_object') # tank_flag = tank_map['tank_object'] # scroller.add(tank_flag, z=0) print type(game_map), len(game_map.cells) print len(game_map.cells[0]), type(game_map.cells) # for cell in game_map.cells: # print cell scroller.add(game_map, z=0) scroller.add(tank_layer, z=1) # set the player start using the player_start token from the tilemap print len(game_map.cells) start = game_map.cells[21] print len(start) print type(start[4]) # 为了不让RectCell显示,可以使其tile为None,这样就可以不加载tile图片到窗口中 start[3].tile = None start = start[3] print game_map.is_visible(start) r = tank.get_rect() # align the mid bottom of the player with the mid bottom of the start cell # r.midbottom = start.midbottom # player image anchor (position) is in the center of the sprite # tank.position = r.center # 创建游戏主场景scene main_scene = cocos.scene.Scene() main_scene.add(scroller) # keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == 0.75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(0.75, 2)) elif key == pyglet.window.key.D: game_map.set_debug(True) director.window.push_handlers(on_key_press) director.run(main_scene)
# For this scene, we'll be using a map with a high rectangular block that we don't want the player to be able to pass # Just as before, I start by initializing the director director.init(width=700, height=500, autoscale=False, resizable=True) # This is because, as stated before, many other objects depend on the director being initialized # And, one again, we set the keyboard and scrolling managers scroller = ScrollingManager() keyboard = key.KeyStateHandler() # I'll also throw in the line that pushes Cocos's handlers to the keyboard object director.window.push_handlers(keyboard) # We'll also load the tilemap here for clarity, as I will be using it in the class below map_layer = load("assets/platformer_map.xml")['map0'] # I use Cocos's XML spec for this map! Check it out if you want to see how to code your own Cocos style maps # This time we'll make an action that extends both the Action class and the new RectMapCollider # The RectMapCollider, you guessed it, lets us collide with rectmaps (A.K.A. tilemaps) class GameAction(Action, RectMapCollider): # To begin, we'll add a function for when the Action starts # I use the start function instead of an __init__ function because of the way the Action parent class is structured def start(self): # We simply set the velocity of the target sprite to zero self.target.velocity = 0, 0 # We also tell the game that our sprite is starting on the ground self.on_ground = True