def main(): global keyboard # Declare this as global so it can be accessed within class methods. # Initialize the window. director.init(width=500, height=300, do_not_scale=True, resizable=True) # Create a layer and add a sprite to it. player_layer = layer.Layer() 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 a scene and set its initial layer. main_scene = scene.Scene(player_layer) # 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 get_deck_scene(controller): deck_scene = scene.Scene() deck_scene.add(DeckMenu(controller)) deck_scene.add(CardsLayer(controller)) return deck_scene
def cocos_main(): # [NOTE]: Must import cocos and pyglet in only one process, see <https://github.com/los-cocos/cocos/issues/281>. from cocos import scene, layer, text, director class HelloWorld(layer.Layer): def __init__(self): super(HelloWorld, self).__init__() label = text.Label( 'Hello World', font_name='Microsoft YaHei UI', font_size=32, anchor_x='center', anchor_y='center', ) label.position = 320, 240 self.add(label) director.director.init( caption='Hello World', resizable=True, ) hello_layer = HelloWorld() main_scene = scene.Scene(hello_layer) director.director.run(main_scene)
def main(): global keyboard # initialzing the director. the director creates the window for the game director.init(width=400, height= 600, autoscale=True, resizable = True) # creating a layer using the cocos2d platform # different layers are used for each aspect of the game, i.e. the main character or background game_layer = layer.Layer() #creating a Sprite for the main character heroimage = pyglet.resource.image('hero.png') player = HeroShip(heroimage) #heroShip.cshape = cm.AARectShape(eu.Vector2(heroShip.position), 32, 32) #adding the main character to the 'player_layer' layer game_layer.add(player) #initializing the main character's position and velocity #heroShip.position = (100, 100) #heroShip.velocity = (0, 0) #creating a background layer background_layer = layer.Layer() background = sprite.Sprite('space_wallpaper.png') #adding backgound image to background layer background_layer.add(background) AsteroidImage = pyglet.resource.image('asteroid.png') asteroid = Asteroid(AsteroidImage, (200, 400)) #adding asteroids to game layer game_layer.add(asteroid) game_layer.add(CollisionManager(player, asteroid)) #initializing pyglet, which allows for keyboard import for character movement keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) #assigning the movement class to the heroShip sprite player.do(HeroShipMovement()) #asteroid_1.do(actions.MoveBy( (0, -600), 4) ) #asteroid_2.do(actions.MoveBy( (100, -600), 8) ) main_scene = scene.Scene(background_layer, game_layer) director.run(main_scene)
def main(): director.director.init(width=640, height=480) layer_ = layer.Layer() # Try animation sprite. explosion = image.load('explosion.png') explosion_seq = image.ImageGrid(explosion, 1, 8) explosion_animation = image.Animation.from_image_sequence( explosion_seq, 0.1) explosion_sprite = sprite.Sprite( explosion_animation, position=(320, 240), ) layer_.add(explosion_sprite) # Try move action. # [NOTE]: Can overwrite `on_animation_end` method to implement the same thing. def move_sprite(_): explosion_sprite.position = (random.randint(0, 640), random.randint(0, 480)) explosion_sprite.schedule_interval(move_sprite, 0.1 * 8) director.director.run(scene.Scene(layer_))
def __init__(self): self.list = MenuListLayer() self.backgrounds = map.generate_cover() self.scroller = ccly.ScrollingManager() for i in range(1, len(self.backgrounds)): self.scroller.add(self.backgrounds[i]) self.scroller.scale = 0.7 self.scene = ccsc.Scene(self.backgrounds[0], self.scroller, self.list)
def main(): """thecoin. The Coin hackaton game Usage: thecoin [options] Options: -h --help Show this screen. --species=<config> Species definition file """ options = docopt(main.__doc__) species_config = configparser.ConfigParser() species_config.read(options['--species']) species = [] for name, spcfg in species_config.items(): if name == "DEFAULT": continue specie = Species( name=spcfg.get('name'), beings=[], factor_death_by_age=spcfg.getfloat('factor_death_by_age'), factor_reproductive_arity=spcfg.getfloat( 'factor_reproductive_arity'), factor_tech_development=spcfg.getfloat('factor_tech_development'), avg_number_children=spcfg.getfloat('avg_number_children')) elements = spcfg.getint('initial_members') specie.beings = [ Being(0, 0, 0, specie, False) for _ in range(elements) ] species.append(specie) initial_world = World(species, 0) game = Game(state=[initial_world]) move_to(game, 0, 5) director.init() interface = Interface(5, game.state[0].characters, *director.get_window_size()) meta = {} runner = RunnerLayer(game, interface, meta) toaster = ToasterLayer(game, interface, meta) meta['scenes'] = { 'runner': scene.Scene(runner), 'toaster': scene.Scene(toaster) } director.run(meta['scenes']['runner'])
def _test(): director.director.init() main_layer = layer.Layer() main_layer.add(center_label('Click Me!', ActiveLabel)) main_scene = scene.Scene(main_layer) director.director.run(main_scene)
def test_transition(): end_layer = HelloLayer(None, THECOLORS['green4']) end_scene = scene.Scene(end_layer) hello_layer = HelloLayer(end_scene) hello_scene = scene.Scene(hello_layer) goodbye_label = center_label('Goodbye') def on_text_press(self, x, y, buttons, modifiers): print('The text {} is pressed'.format(self.element.text)) setattr(goodbye_label, 'on_mouse_press', on_text_press) hello_layer.add(center_label('Click to go to end')) end_layer.add(goodbye_label) return hello_scene
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 get_game_scene(controller): game_scene = scene.Scene() game_scene.add(get_game_bg(), z=0, name='background') board = GameBoardLayer(controller) game_scene.add(GameButtonsLayer(controller, board), z=1, name='buttons') game_scene.add(board, z=2, name='board') return game_scene
def get_select_deck_scene(controller): select_deck_scene = scene.Scene() select_deck_scene.add(get_select_deck_bg(), z=0, name='background') select_deck_scene.add(BasicButtonsLayer(controller), z=1, name='basic_buttons') select_deck_scene.add(SelectDeckLayer(controller), z=2, name='main') return select_deck_scene
def main(): global keyboard global collision_manager collision_manager = cm.CollisionManagerBruteForce() director.init(width=MAP_SIZE[0], height=MAP_SIZE[1], autoscale=True, resizable=True) # Create a layer player_layer = Mqtt_layer(collision_manager) # create an obstacle and add to layer obstacle1 = CollidableSprite('sprites/obstacle.png', 200, 200, 0) player_layer.add(obstacle1) obstacle1.velocity = (0, 0) collision_manager.add(obstacle1) # create an obstacle and add to layer obstacle2 = CollidableSprite('sprites/obstacle.png', 320, 240, 0) player_layer.add(obstacle2) obstacle2.velocity = (0, 0) collision_manager.add(obstacle2) # create an obstacle and add to layer obstacle4 = CollidableSprite('sprites/obstacle.png', 490, 490, 0) player_layer.add(obstacle4) obstacle4.velocity = (0, 0) collision_manager.add(obstacle4) # create the car and add to layer car = CollidableSprite('sprites/Black_viper.png', 100, 100, 10) action = actions.interval_actions.ScaleBy(0.25, 0) car.do(action) player_layer.add(car) car.velocity = (0, 0) # Set the sprite's movement class. car.do(Car()) # Create a scene and set its initial layer. main_scene = scene.Scene(player_layer) # collisions collision_manager.add(car) # 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 on_key_press(self, key, modifiers): # If you don't know what these next couple lines do, go check the previous tutorials move_left = MoveBy((-50, 0), .5) move_up = MoveBy((0, 50), .5) # Check if they want to go left, and then actually make the sprite go left if symbol_string(key) == "LEFT": self.sprite.do(move_left) # Or maybe if they want to move right? elif symbol_string(key) == "RIGHT": self.sprite.do(Reverse(move_left)) # Lastly we need to make it move up elif symbol_string(key) == "UP": self.sprite.do(move_up) # Oh yeah don't forget about down elif symbol_string(key) == "DOWN": self.sprite.do(Reverse(move_up)) # That's it for movements! # Now let's look at transitioning to a new scene # Let's make the game all trippy when they hit space elif symbol_string(key) == "SPACE": # I need to stop the music before we transition to the next scene so that two songs aren't playing at once self.bg_music.stop() # If you were paying attention, you would've noticed I take three parameters in the init function # I get the X and Y coordinates of the sprite to figure out where to place it when the scenes transition coordinates = self.sprite.position # You should try printing the X and Y coordinates yourself to see the type of object that it returns if self.is_trippy: # This line only runs when the layer is already trippy, and by default the layer makes itself not trippy # This line only needs to give the X and Y coordinates in that case director.replace( scene.Scene(InputLayer(coordinates[0], coordinates[1]))) else: # This huge line makes a new scene, with a transition, and inputs the coordinates and makes it trippy! director.replace( scene.Scene( InputLayer(coordinates[0], coordinates[1], True)))
def get_main_scene(controller): main_scene = scene.Scene() main_scene.add(BackgroundLayer(), z=0, name='background') main_scene.add(BasicButtonsLayer(controller, back=False), z=1, name='basic_buttons') main_scene.add(MainLayer( MainMenu(controller), OptionsMenu(controller), ), z=2, name='main') return main_scene
def get_main_scene(controller): main_scene = scene.Scene() main_scene.add(layer.MultiplexLayer( MainMenu(controller), OptionsMenu(controller), ), z=1) main_scene.add(BackgroundLayer(), z=0) return main_scene
def main(): # Director is a singleton object of cocos. director.director.init( caption='Hello World', resizable=True, ) hello_layer = HelloWorld() main_scene = scene.Scene(hello_layer) director.director.run(main_scene)
def __init__(self, dst, duration=1.25, src=None): """Initializes the transition :Parameters: `dst` : Scene Incoming scene, the one that remains visible when the transition ends. `duration` : float Duration of the transition in seconds. Default: 1.25 `src` : Scene Outgoing scene. Default: current scene """ super(TransitionScene, self).__init__() if src is None: src = director.scene # if the director is already running a transition scene then terminate # it so we may move on if isinstance(src, TransitionScene): tmp = src.in_scene.get('dst') src.finish() src = tmp if src is dst: raise Exception( "Incoming scene must be different from outgoing scene") envelope = scene.Scene() envelope.add(dst, name='dst') self.in_scene = envelope #: envelope with scene that will replace the old one envelope = scene.Scene() envelope.add(src, name='src') self.out_scene = envelope #: envelope with scene that will be replaced self.duration = duration #: duration in seconds of the transition if not self.duration: self.duration = 1.25 self.start()
def main(): # Director is a singleton object of cocos. director.director.init( caption='Hello World', resizable=True, ) hello_layer = HelloActions() # [LEARN] layers (in fact, all CocosNode objects) can take actions. hello_layer.do(actions.RotateBy(360, duration=10)) main_scene = scene.Scene(hello_layer) director.director.run(main_scene)
def on_key_press(self, key, modifiers): move_left = MoveBy((-50, 0), .5) move_up = MoveBy((0, 50), .5) if symbol_string(key) == "LEFT": self.sprite.do(move_left) elif symbol_string(key) == "RIGHT": self.sprite.do(Reverse(move_left)) elif symbol_string(key) == "UP": self.sprite.do(move_up) elif symbol_string(key) == "DOWN": self.sprite.do(Reverse(move_up)) elif symbol_string(key) == "SPACE": self.bg_music.stop() coordinates = self.sprite.position if self.trippy: self.do(FadeOutTRTiles(grid=(16, 12), duration=1)) director.replace( scene.Scene(InputLayer(coordinates[0], coordinates[1]))) else: self.stop() director.replace( scene.Scene( InputLayer(coordinates[0], coordinates[1], True)))
def get_collection_scene(controller): collection_scene = scene.Scene() collection_scene.add(get_collection_bg(), z=0, name='background') collection_scene.add(CollectionsBBLayer(controller), z=1, name='basic_buttons') collection_scene.add(CollectionsLayer(controller), z=2, name='collections') collection_scene.add(layer.MultiplexLayer( DeckSelectLayer(controller), DeckEditLayer(controller), ), z=3, name='deck') return collection_scene
def get_adventure_scene(controller): adventure_scene = scene.Scene() adventure_scene.add(get_adventure_bg(), z=0, name='background') adventure_scene.add(BasicButtonsLayer(controller), z=1, name='basic_buttons') main_layer = layer.MultiplexLayer(PracticeModeLayer(controller), ) adventure_scene.add(main_layer, z=2, name='main') adventure_scene.add(AdventureSelectLayer(controller, main_layer), z=3, name='select') return adventure_scene
def draw_game(game, **kwargs): """Draw the game board using cocos2d. :param game: :param kwargs: :return: """ if kwargs.pop('subprocess', False): info('Creating a Cocos2d-Python drawing window in a new process') # Do some initialization in the new process. # Overwrite global configuration with the configuration from parent process. parent_config = kwargs.pop('parent_config', None) if parent_config is not None: constants.C = parent_config setup_logging(level=constants.C.Logging.Level, scr_log=constants.C.Logging.ScreenLog) from ..utils.package_io import reload_packages reload_packages() else: info('Creating a Cocos2d-Python drawing window in the main process') try: preprocess() director.director.init( caption='HearthStone Board', resizable=False, autoscale=True, width=Width, height=Height, ) main_layer = HSGameBoard(game, **kwargs) main_scene = scene.Scene(main_layer) director.director.run(main_scene) except Exception as e: error('Error "{}" when running the Cocos2d-Python app: {}'.format( type(e), e)) director.director.window.close() finally: info('The Cocos2d-Python drawing window exited')
def main(): path = os.path.join(os.path.dirname(__file__), '../Map/assets/img') resource.path.append(path) resource.reindex() director.director.init(width=640, height=480) layer_ = layer.Layer() layer_.add( MultipleSprite( Sprite('grossini.png', position=(50, 40)), Sprite('sky.gif', position=(-60, -30)), position=(320, 240), )) director.director.run(scene.Scene(layer_))
def main(): global keyboard # This is declared as global so that it can be accessed by all class methods # Initialize director and create scene. # Arguments passed set the size of the window. # autoscale allows the graphics to be scaled according to the window being resized. # Caption sets window title. Have some fun with that! # (http://python.cocos2d.org/doc/api/cocos.director.html) director.init(width=800, height=600, caption="In the beginning everything was Kay-O", autoscale=True, resizable=True) # Create a layer and add a sprite to the layer. # Layers help to separate out different parts of a scene. # Typically, the highest layer will go to dialogue boxes and menus # Followed by the player layer with the background on the bottom player_layer = layer.Layer() # Creates an instance of a new layer player = sprite.Sprite( 'images/mr-saturn.png' ) #initializes a sprite object and includes a path to default image. player_layer.add( player) # Adds player to instance of layer we just created # Sets initial position and velocity of player player.position = (250, 150) player.velocity = (0, 0) # Set the sprite's movement class player.do(Player()) # Create a scene and set its initial layer main_scene = scene.Scene(player_layer) # Creates a KeyStateHandler on the keyboard object so we can accept input from the keyboard (KeyStateHandler is part of the pyglet library) # And pushes it to director keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # Run the scene we've built in the window director.run(main_scene)
def on_key_press(self, key, modifiers): # only need to define one move in the x and y directions because we can use Reverse() move_left = MoveBy((-20, 0), .25) move_up = MoveBy((0, 20), .25) #handle moving the sprite if symbol_string(key) == "LEFT": self.sprite.do(move_left) elif symbol_string(key) == "RIGHT": self.sprite.do(Reverse(move_left)) elif symbol_string(key) == "UP": self.sprite.do(move_up) elif symbol_string(key) == "DOWN": self.sprite.do(Reverse(move_up)) #handle the users has made it to the goal elif symbol_string(key) == "SPACE": director.replace(SplitColsTransition(scene.Scene(CongratsScreen())))
def createInterface(): director.director.init(width=3000, height=960, autoscale=True, resizable=True) MainLayer = MainSceneLayer() # set_main_layer(MainLayer) main_scene = scene.Scene(MainLayer) main_scene.schedule(MainLayer.buttonsHandler) MainLayer.register_event_type('on_clicked') MainLayer.register_event_type('add_tank') MainLayer.register_event_type('add_animation') MainLayer.register_event_type('add_bullet') MainLayer.register_event_type('remove_animation') MainLayer.dispatch_event('on_clicked', '12314124') director.director.on_resize = MainLayer.resize director.director.window.push_handlers(CurrentKeyboard) director.director.run(main_scene)
def main(): global keyboard # Declare this as global so it can be accessed within class methods. # Initialize the window director.init(width=size[0], height=size[1], autoscale=True, resizable=True) # Create a layer and add a sprite to it. player_layer = layer.Layer() molecule = sprite.Sprite('sprites/molecule.png') molecule.scale = 2 player_layer.add(molecule, z=1) scale = actions.ScaleBy(3, duration=2) # Add a Label, because we can. label = cocos.text.Label('Hello, world@' + str(deltaTime), font_name='Times New Roman', font_size=32, anchor_x='left', anchor_y='center') label.position = 0, size[1]/2 label.velocity = 0, 0 player_layer.add(label) # Set initial position and velocity. molecule.position = (size[0]/2, size[1]/2) molecule.velocity = (0, 0) # Set the sprite's movement class and run some actions. molecule.do(actions.Repeat(scale + actions.Reverse(scale))) label.do(Me()) # Rotate the entire player_layer (includes ALL nodes, will rotate ONCE) player_layer.do(actions.RotateBy(360, duration=10)) # Create a scene and set its initial layer. main_scene = scene.Scene(player_layer) # Set the sprite's movement class. keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) # Play the scene in the window. 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 main(): """ Every program needs a main function. This is it. """ # Instantiate and Initialize main director maindirector = director.director maindirector.init(resizable=True) # Instantiate main scene mainscene = scene.Scene() # Instantiate main menu layer - main menu at start of game mainmenulayer = menu.MainMenu() # Instantiate gameview, a CocosNode containing layers for actual gameplay maingameview = gameview.GameView() # Add our layers in a multiplex (only 1 layer per multiplex can be visible at a time) # The default visible layer is the first in the multiplex (mainmenu) # This multiplex layer is indexed z = 1 mainscene.add(layer.base_layers.MultiplexLayer(mainmenulayer, maingameview), z=1) # Instantiate background layer - just a colored layer # Note: The * (splat operator) unpacks the tuple returned by rgba() backgroundlayer = layer.ColorLayer(*colors.rgba(colors.base3)) # Add background, always visible, indexed at z = 0 mainscene.add(backgroundlayer, z=0) # DEBUG - shows what key is pressed and mouse coords # scene.add( mousedisplay.MouseDisplay(), z = 2) # scene.add( keydisplay.KeyDisplay(), z = 3) # Tell director to run our scene (start game!) maindirector.run(mainscene)