class BoidLayer(ScrollableLayer): """Where the boids fly. """ is_event_handler = True def __init__(self, how_many): super(BoidLayer, self).__init__() self.how_many = how_many self.manager = ScrollingManager() self.manager.add(self) self.active = None self.blackboard = blackboard.Blackboard("boids") self.boids = None def makeBoids(self): boids = [] for x in xrange(int(self.how_many)): boid = Boid(self.blackboard) boid.position = (random.randint(0, 200), random.randint(0, 200)) boid.rotation = random.randint(1, 360) self.add(boid) boids.append(boid) return boids def on_enter(self): """Code to run when the Layer enters the scene. """ super(BoidLayer, self).on_enter() self.boids = self.makeBoids() # Place flock in the center of the window self.manager.set_focus(-512, -384)
class Game( Scene): """ Return a Scene containing the active game layers """ def __init__(self): """ DUMMY MAP FOR NOW """ super(Game,self).__init__() self.scroller = ScrollingManager() bg = ColorLayer(172,144,255,255) self.add( bg, z=0, name="background" ) test_layer = cocos.tiles.load('testcard.xml')['testmap'] self.scroller.add(test_layer) #This loads a cocos2d XML format map #map = ImageLayer('test2.png') #scroller.add(map, z=1, name='map') self.add(self.scroller,z=1) inputlayer = GameController(self) self.add(inputlayer, z=5) def build_layers(self): pass
def __init__(self, how_many): super(BoidLayer, self).__init__() self.how_many = how_many self.manager = ScrollingManager() self.manager.add(self) self.active = None self.blackboard = blackboard.Blackboard("boids") self.boids = None
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 __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
class GameMapBaseScene(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, tree_name): super(TreeLayer, self).__init__() self.tree_name = tree_name self.manager = ScrollingManager() self.manager.add(self) self.active = None self.tree = None
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)
class TreeLayer(ScrollableLayer): is_event_handler = True def __init__(self, tree_name): super(TreeLayer, self).__init__() self.tree_name = tree_name self.manager = ScrollingManager() self.manager.add(self) self.active = None self.tree = None # self.blackboard = blackboard.Blackboard() def makeTree(self): self.tree = Tree(self.tree_name) def on_enter(self): super(TreeLayer, self).on_enter() self.makeTree() self.manager.set_focus(0, 0)
def __init__(self, viewport_h): self.viewport_height = viewport_h viewport = Rect(0, self.viewport_height, director.window.width, director.window.height - self.viewport_height) #director.window ScrollingManager.__init__(self, viewport) self.config = Config() self.gallery = Gallery() self.is_event_handler = True self.sprite_list = {} # scrolling self.inscroll = False self.scroll_direction = (0, 0) self.marked_tile = (-1, -1) self.combatants = {} self.valid_squares = {} self.move_path = [] #self.fire_path = [] self.spawn_unit = "na" self.bracket = Sprite(self.gallery.content["trn"]["bracket"]) self.bracket.image_anchor = 0, 0 self.bracket.scale = 1 self.bracket.x = -1000 self.bracket.y = -1000 self.bracket_sel = Sprite(self.gallery.content["trn"]["bracket_sel"]) self.bracket_sel.image_anchor = 0, 0 self.bracket_sel.scale = 1 self.bracket_sel.x = -1000 self.bracket_sel.y = -1000 self.adjacent_tiles = OrderedDict() self.adjacent_tiles["N"] = (0, 1) self.adjacent_tiles["E"] = (1, 0) self.adjacent_tiles["S"] = (0, -1) self.adjacent_tiles["W"] = (-1, 0) self.adjacent_tiles["B"] = (1, 1) self.adjacent_tiles["C"] = (1, -1) self.adjacent_tiles["D"] = (-1, -1) self.adjacent_tiles["A"] = (-1, 1)
def __init__(self, viewport_h): """ initializer """ self.viewport_height = viewport_h viewport = Rect(0, self.viewport_height, director.window.width, director.window.height - self.viewport_height) #director.window ScrollingManager.__init__(self, viewport) self.config = Config() self.gallery = Gallery() self.is_event_handler = True # scrolling self.inscroll = False self.scroll_direction = () if len(self.config.loaded_objects) > 0: self.POI = self.config.loaded_objects["POI"] else: self.POI = {} self.transarctica_actor = TransarcticaActor(self) self.transarctica = director.core.query_mover("Transarctica") self.vutrain = [] self.vutrain_actor = [] for id in range(self.config.vutrain_count): self.vutrain_actor.append(id) self.vutrain_actor[id] = VUTrainActor(self, id) self.vutrain.append(id) self.vutrain[id] = director.core.query_mover("VUTrain" + str(id)) self.roamer = [] self.roamer_actor = [] for id in range(self.config.roamer_count): self.roamer_actor.append(id) self.roamer_actor[id] = RoamerActor(self, id) self.roamer.append(id) self.roamer[id] = director.core.query_mover("Roamer" + str(id))
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 __init__(self, game): super(ScrollerManager, self).__init__() # add a scrolling manager, and a game instance # and add the game to the scrolling manager self.scroller = ScrollingManager() self.game = game self.scroller.add(self.game) self.add(self.scroller) self.scroller.set_scale(1) size = director.get_window_size() self.p1_score = Label("Score: ", (size[0] / 64,size[1] / 32), font_name = "David", font_size = 24) self.p2_score = Label("Score: ", (size[0] / 1.1,size[1] / 32), font_name = "David", font_size = 24) self.health = Label("Hull: ", (size[0] / 7,size[1] / 32), font_name = "David", font_size = 24) self.health2 = Label("Hull: ", (size[0] / 1.5,size[1] / 32), font_name = "David", font_size = 24) self.add(self.p1_score) self.add(self.p2_score) self.add(self.health) self.add(self.health2) self.schedule(self.update)
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 m director.init() m = ScrollingManager() fg = ScrollableLayer() l = Label('foreground') l.position = (100, 100) fg.add(l) m.add(fg) bg = ScrollableLayer(parallax=.5) l = Label('background, parallax=.5') l.position = (100, 100) bg.add(l) m.add(bg) if autotest: m.do( Delay(1) + CallFunc(update_focus, 100, 200) + Delay(1) + CallFunc(update_focus, 200, 100) + Delay(1) + CallFunc(update_focus, 200, 200) ) main_scene = cocos.scene.Scene(m) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def update(dt): m.fx += (keyboard[key.RIGHT] - keyboard[key.LEFT]) * 150 * dt m.fy += (keyboard[key.DOWN] - keyboard[key.UP]) * 150 * dt m.set_focus(m.fx, m.fy) main_scene.schedule(update) director.run (main_scene)
def __init__(self, *args, **kwargs): super(MyWitch, self).__init__(*args, **kwargs) # add a background layer self.add(ColorLayer(100, 100, 100, 255)) scroller = ScrollingManager() self.fullmap = cocos.tiles.load('maps/platformer-map.xml') # add the walls (labyrinth) self.walls = self.fullmap['walls'] scroller.add(self.walls, z=0) # add the items (bushes cauldron) self.decoration = self.fullmap['decoration'] scroller.add(self.decoration, z=1) # add the player player_layer = layer.ScrollableLayer() self.player = cocos.sprite.Sprite('img/witch-standing.png') self.player.do(MyWitchController()) player_layer.add(self.player) scroller.add(player_layer, z=2) self.add(scroller) # set the player start position using the player_start token from the map start = self.decoration.find_cells(player_start=True)[0] r = self.player.get_rect() r.midbottom = start.midbottom self.player.position = r.center # give a collision handler to the player mapcollider = cocos.mapcolliders.RectMapCollider(velocity_on_bump='slide') self.player.collision_handler = mapcolliders.make_collision_handler( mapcollider, self.walls)
from cocos.actions import Action from cocos.sprite import Sprite from cocos.tiles import load from cocos.layer import ScrollingManager, ScrollableLayer from cocos.director import director from cocos.scene import Scene from pyglet.window import key from pyglet import image window_width, window_height = 320, 320 director.init(width=320, height=320) scroller = ScrollingManager() keyboard = key.KeyStateHandler() class PlayerSprite(Sprite): # facing UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 def __init__(self, facing=2): spritesheet = image.load('dude.png') frames = image.ImageGrid(spritesheet, 4, 3) super(PlayerSprite, self).__init__(frames[10]) self.facing = facing self.animating = False self.up = image.Animation.from_image_sequence(frames[:2], 0.7, False)
import cocos from cocos.layer import ScrollableLayer, ScrollingManager from cocos.sprite import Sprite from cocos.scene import Scene from Level3_Hero import Level3_Hero from pyglet.window import key from cocos.actions import * from cocos.director import director from cocos.scenes.transitions import * import Sound import PauseScene scroller_3 = ScrollingManager() class Level3_Background(ScrollableLayer): is_event_handler = True #: enable director.window events def __init__(self): super(Level3_Background, self).__init__() bg = Sprite('res/maps/Level3/level3.png') bg.position = bg.width // 2, bg.height // 2 self.px_width = bg.width self.px_height = bg.height self.add(bg) lvl3 = Sprite('res/maps/Level3/LVL3.png')
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))
from cocos.tiles import load from cocos.mapcolliders import RectMapCollider from cocos.layer import ScrollingManager, ScrollableLayer, ColorLayer from cocos.director import director from cocos.scene import Scene from cocos.actions import Action from pyglet.window import key # 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 timer(self): self.liveTime = self.liveTime - 1 def terminator(self): if (self.liveTime < 0): return True # 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
class GameObj: my_director = director my_director.init() map_layer = load('map01.tmx')['solid'] scroller = ScrollingManager() keyboard = key.KeyStateHandler()
from cocos.tiles import load, RectMapCollider from cocos.layer import ScrollingManager, ScrollableLayer, ColorLayer from cocos.director import director from cocos.scene import Scene from cocos.actions import Action from pyglet.window import key # 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
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 # It is very easy to mess up this code, as Cocos doesn't provide a lot of leeway # Putting the code in the wrong order, not declaring the name of the map, # not initializing the director, etc all break this program
from cocos.mapcolliders import RectMapWithPropsCollider from cocos.layer import Layer, ColorLayer, ScrollingManager, ScrollableLayer from cocos.sprite import Sprite from cocos.actions import * from cocos.scene import Scene from cocos.director import director from pyglet.window import key from pyglet.window.key import symbol_string, KeyStateHandler from menu import GameMenu import blinker director.init(width=1920, height=480, autoscale=True, resizable=True) Map = load("mapmaking.tmx") scroller = ScrollingManager() tilemap = Map['map0'] assert tilemap.origin_x == 0 assert tilemap.origin_y == 0 class Background(ColorLayer): def __init__(self): super(Background, self).__init__(65, 120, 255, 255) class ShowCollision(ScrollableLayer): """ A layer to show the cells a RectMapCollider considers potentially colliding with the 'new' rect.
print(__doc__) if len(sys.argv) < 2: selector = 0 else: selector = 1 collider_cls = [RectMapCollider, RectMapWithPropsCollider][selector] director.init() tile_filled = Tile('z', {}, pyglet.image.load('white4x3.png')) maps_cache = aux.generate_maps(tile_filled) cases = [ d for d in aux.case_generator(aux.first_expansion(maps_cache, aux.common_base_cases))] model = Model(cases) scene = cocos.scene.Scene() label = Label("-----------------", anchor_x='center', anchor_y='center', color=(255, 255, 255, 160)) label.position = 320, 20 scene.add(label, z=10) model.label = label scroller = ScrollingManager() model.scroller = scroller scroller.scale = 8.0 scene.add(scroller, z=1) controller = ControllerLayer() controller.model = model scene.add(controller) director.run(scene)
else: selector = 1 collider_cls = [RectMapCollider, RectMapWithPropsCollider][selector] director.init() tile_filled = Tile('z', {}, pyglet.image.load('white4x3.png')) maps_cache = aux.generate_maps(tile_filled) cases = [ d for d in aux.case_generator( aux.first_expansion(maps_cache, aux.common_base_cases)) ] model = Model(cases) scene = cocos.scene.Scene() label = Label("-----------------", anchor_x='center', anchor_y='center', color=(255, 255, 255, 160)) label.position = 320, 20 scene.add(label, z=10) model.label = label scroller = ScrollingManager() model.scroller = scroller scroller.scale = 8.0 scene.add(scroller, z=1) controller = ControllerLayer() controller.model = model scene.add(controller) director.run(scene)
import cocos from cocos.layer import ScrollableLayer, ScrollingManager from cocos.sprite import Sprite from cocos.scene import Scene from cocos.actions import * from Level2_Hero import Level2_Hero from pyglet.window import key from cocos.director import director from cocos.scenes.transitions import * import Sound import PauseScene scroller_2 = ScrollingManager() class Level2_Background(ScrollableLayer): is_event_handler = True #: enable director.window events def __init__(self): super(Level2_Background, self).__init__() bg = Sprite('res/maps/Level2/level2.png') bg.position = bg.width // 2, bg.height // 2 self.px_width = bg.width self.px_height = bg.height lvl2 = Sprite('res/maps/Level2/LVL2.png') lvl2.position = (420, 500) lvl2.scale = 0.7
from cocos.tiles import load, RectMapLayer, RectMapCollider from cocos.layer import Layer, ColorLayer, ScrollingManager, ScrollableLayer from cocos.sprite import Sprite from cocos.actions import * from cocos.scene import Scene from cocos.director import director from pyglet.window import key from pyglet.window.key import symbol_string, KeyStateHandler from menu import GameMenu import blinker director.init(width=1920, height=480, autoscale = True, resizable = True) Map = load("mapmaking.tmx") scroller = ScrollingManager() tilemap = Map['map0'] assert tilemap.origin_x == 0 assert tilemap.origin_y == 0 class Background(ColorLayer): def __init__(self): super(Background, self).__init__(65,120,255,255) class ShowCollision(ScrollableLayer): """ A layer to show the cells a RectMapCollider considers potentially colliding with the 'new' rect.
class ScrollerManager(Layer): """ Handle camera""" is_event_handler = True def __init__(self, game): super(ScrollerManager, self).__init__() # add a scrolling manager, and a game instance # and add the game to the scrolling manager self.scroller = ScrollingManager() self.game = game self.scroller.add(self.game) self.add(self.scroller) self.scroller.set_scale(1) size = director.get_window_size() self.p1_score = Label("Score: ", (size[0] / 64,size[1] / 32), font_name = "David", font_size = 24) self.p2_score = Label("Score: ", (size[0] / 1.1,size[1] / 32), font_name = "David", font_size = 24) self.health = Label("Hull: ", (size[0] / 7,size[1] / 32), font_name = "David", font_size = 24) self.health2 = Label("Hull: ", (size[0] / 1.5,size[1] / 32), font_name = "David", font_size = 24) self.add(self.p1_score) self.add(self.p2_score) self.add(self.health) self.add(self.health2) self.schedule(self.update) def update(self,dt): self.p1_score.element.text = "Score: " + str(self.game.player.score) self.p2_score.element.text = "Score: " + str(self.game.player2.score) self.health.element.text = "Player 1 | Hull: " + str(int(self.game.player.health)) self.health2.element.text = "Player 2 | Hull: " + str(int(self.game.player2.health)) player_distance = eu.LineSegment2( eu.Point2(self.game.player.body.position[0], self.game.player.body.position[1]), eu.Point2(self.game.player2.body.position[0], self.game.player2.body.position[1]) ) #print player_distance scale = 1 / player_distance.length * 1024 self.scroller.set_focus((player_distance.p1[0] + player_distance.p2[0]) / 2, (player_distance.p1[1] + player_distance.p2[1]) / 2) if scale >= 0.28: self.scroller.set_scale(scale) ''' # Set a player's speed based on its velocity self.game.player.speed = math.sqrt(math.pow(self.game.player.body.velocity[0], 2) + math.pow(self.game.player.body.velocity[1], 2) ) ''' # Warp Control if self.game.player.get_rect().center[0] >= self.game.px_width: self.game.player.body.position = 0 , self.game.player.body.position[1] if self.game.player.get_rect().center[0] <= 0: self.game.player.body.position = self.game.px_width , self.game.player.body.position[1] if self.game.player.get_rect().center[1] >= self.game.px_height: self.game.player.body.position = self.game.player.body.position[0], 0 if self.game.player.get_rect().center[1] <= 0: self.game.player.body.position = self.game.player.body.position[0], self.game.px_height if self.game.player2.get_rect().center[0] >= self.game.px_width: self.game.player2.body.position = 0 , self.game.player2.body.position[1] if self.game.player2.get_rect().center[0] <= 0: self.game.player2.body.position = self.game.px_width , self.game.player2.body.position[1] if self.game.player2.get_rect().center[1] >= self.game.px_height: self.game.player2.body.position = self.game.player2.body.position[0], 0 if self.game.player2.get_rect().center[1] <= 0: self.game.player2.body.position = self.game.player2.body.position[0], self.game.px_height for asteroid in self.game.asteroids.asteroid_count: if asteroid.body.position[0] >= self.game.px_width: asteroid.body.position = 0 , asteroid.body.position[1] elif asteroid.body.position[0] <= 0: asteroid.body.position = self.game.px_width , asteroid.body.position[1] elif asteroid.body.position[1] >= self.game.px_height: asteroid.body.position = asteroid.body.position[0], 0 elif asteroid.body.position[1] <= 0: asteroid.body.position = asteroid.body.position[0], self.game.px_height for laser in self.game.laser_count: if laser.position[0] >= self.game.px_width: self.game.laser_count = self.game.remove_from_set(laser, self.game.laser_count) self.game.weapon_batch.remove(laser) elif laser.position[0] <= 0: self.game.laser_count = self.game.remove_from_set(laser, self.game.laser_count) self.game.weapon_batch.remove(laser) elif laser.position[1] >= self.game.px_height: self.game.laser_count = self.game.remove_from_set(laser, self.game.laser_count) self.game.weapon_batch.remove(laser) elif laser.position[1] <= 0: self.game.laser_count = self.game.remove_from_set(laser, self.game.laser_count) self.game.weapon_batch.remove(laser)
# Imports as usual from cocos.sprite import Sprite from cocos.tiles import load from cocos.layer import ScrollingManager, ScrollableLayer from cocos.director import director from cocos.scene import Scene from cocos.actions import Driver from pyglet.window import key director.init(width=800, height=600, autoscale=False, resizable=False) keeb = key.KeyStateHandler() scroller = ScrollingManager() class cardriver(Driver): def step(self, dt): self.target.rotation += (keeb[key.RIGHT] - keeb[key.LEFT]) * 100 * dt self.target.acceleration = (keeb[key.UP] - keeb[key.DOWN]) * 500 if keeb[key.SPACE]: self.target.speed -= self.target.speed / 10 super(cardriver, self).step(dt) scroller.set_focus(self.target.x, self.target.y) class carlayer(ScrollableLayer): def __init__(self): super(carlayer, self).__init__() self.sprite = Sprite("assets/img/car.png") self.sprite.position = 200, 100 self.sprite.max_forward_speed = 200
if args['--debug']: level = logging.DEBUG logging.basicConfig(level=level) logger.info("start scrolling") WIDTH = 800 HEIGHT = 600 director.init(width=WIDTH, height=HEIGHT, autoscale=False, resizable=False) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) mapTMX = load("assets/map.tmx") mapLayer = mapTMX["terrain"] collideLayer = mapTMX['blocks'] scroller = ScrollingManager() scroller.add(mapLayer, z=1) # scroller.add(collideMap, z=1) collide_manager = cm.CollisionManagerGrid(0.0, mapLayer.px_width, 0.0, mapLayer.px_height, TILE_WIDTH * 3, TILE_WIDTH * 3) player = PlayerActor(collide_manager, keyboard) # ActorPlayer(collideMap) scrollLayer = ActorsLayer(player, mapLayer.px_width, mapLayer.px_height, collide_manager, collideLayer) scroller.add(scrollLayer, z=2) scrollLayer.addCollidable(player) def layer_subscriber(event: Event): logger.debug(f"handle event {event}")
## global variable for audio audiomixer = pygame.mixer audiomixer.init() clicksound = audiomixer.Sound('sounds/click.ogg') bgmplayed = False ## global list for plotting num_flowers_list = [0] * 7 volumes = [] pitches = [] time_data = [] director.init(width=WIDTH, height=HEIGHT, autoscale=False, resizable=False) #scroller for testing background scroller_test = ScrollingManager() mapLayer_test = load("assets/map/wood_blocker.tmx")["TileLayer1"] scroller_test.add(mapLayer_test) #scroller for game background scroller = ScrollingManager() mapLayer = load("assets/map/map_garden_back_01.tmx")["TileLayer1"] scroller.add(mapLayer) #scroller_menu for menu background scroller_menu = ScrollingManager() mapLayer_menu = load("assets/map/map_menu.tmx")["TileLayer1"] scroller_menu.add(mapLayer_menu) # class for testing voice
if self.keys_pressed and key in self.keys_pressed: self.keys_pressed.remove(key) #def draw(self): # self.image.blit(0, 0) if __name__ == '__main__': # change the working dir to the exe temp dir # when you use pyinstaller to make a one-file exe package, you need doing this above if getattr(sys, 'frozen', False): os.chdir(sys._MEIPASS) my_game = Game() game_screen = ScrollingManager() # the tile map 'map.tmx' which has a layer called 'start' # use the editor software called 'Tiled' to make a tile map map_layer = cocos.tiles.load('./data/map.tmx')['start'] my_main = Main_Screen(my_game) my_menu = Menu_Screen(my_game) # the order of the 'add' makes sense! game_screen.add(map_layer) game_screen.add(my_main) main_scene = Scene(my_menu) #print ('game initialised') cocos.director.director.run(main_scene) #print('game end')
import cocos from cocos.layer import ScrollableLayer, ScrollingManager, MultiplexLayer, Layer from cocos.sprite import Sprite from cocos.actions import * from cocos.scene import Scene from Level1_Hero import Level1_Hero from pyglet.window import key from cocos.director import director from cocos.scenes.transitions import * from cocos.text import Label import PauseScene import Sound scroller_1 = ScrollingManager() class Level1_Background(ScrollableLayer): is_event_handler = True #: enable director.window events def __init__(self): super(Level1_Background, self).__init__() bg = Sprite('res/maps/Level1/level1.png') bg.position = bg.width // 2, bg.height // 2 lvl1 = Sprite('res/maps/Level1/LVL1.png') lvl1.position = (420, 500) lvl1.scale = 0.7 blink = Blink(10, 3) lvl1.do(blink)
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)
# Let's make a simple game where you drive around a track in a car # This code is a simplified version of the one that exists in the cocos examples # The first thing I need to do is initialize the director, because many other objects in this program depend on it # This time I'm going to pass in a few more parameters than usual into the initialize function director.init(width=800, height=600, autoscale=False, resizable=True) # I simply set an X and Y for the window, and allow it to be resized # Here I set a scroller and a key manager # The key manager is something new you haven't seen! # It allows me to get the keys being pressed, globally (unlike event handling layers). Pretty neat! keyboard = key.KeyStateHandler() # And the scrolling manager like you saw last time scroller = ScrollingManager() # Here's something you haven't scene before! # We'll be using the Driver class from the "move_actions" provided by Cocos, and editing it slightly for our needs # The driver class is built to help make having sprites behave like vehicles much simpler class CarDriver (Driver): # We don't need to call the init function because the Driver class already does that for us! # Instead I only want to overload this step function. This is what controls the movement of the sprite def step(self, dt): # This line might seem pretty complicated, but it's really not at all self.target.rotation += (keyboard[key.RIGHT] - keyboard[key.LEFT]) * 100 * dt # Essentially what I do here is take the right value minus the left value (remember that moving left is negative) # And then I multiply it by 100 so it's more visible, and multiply it by the dt value passed in by the step function # Finally, I add it to the rotation of the "target", which would be the sprite we tell to do this action