Esempio n. 1
0
    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)
Esempio n. 2
0
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)
Esempio n. 3
0
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
Esempio n. 4
0
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)
Esempio n. 5
0
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))
Esempio n. 6
0
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
Esempio n. 7
0
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
Esempio n. 8
0
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 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)
Esempio n. 10
0
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)
Esempio n. 11
0
    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, 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
Esempio n. 13
0
    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)
Esempio n. 14
0
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) 		
Esempio n. 15
0
		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))
Esempio n. 16
0
        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}")
        if event.type == Event.CREATE_TYPE:
Esempio n. 17
0
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))
Esempio n. 18
0
# Essentially, we need to find the cell where I marked for the player to start, and set the sprite as starting there
# We do this by first finding that cell I marked (check the source code of the map to see how it's done)
start = map_layer.find_cells(player_start=True)[0]

# Then I get that bounded rectangle we talked about earlier from the sprite
rect = sprite_layer.sprite.get_rect()

# After that I set the middle bottom of the sprite's bounded rectangle equal to the middle bottom of the start cell
rect.midbottom = start.midbottom

# And lastly I set the position of the sprite to the center of the rectangle
sprite_layer.sprite.position = rect.center

# From here it's pretty easy sailing
# First I add the map, and set the "z" to 0
scroller.add(map_layer, z=0)
# The z is the vertical axis, so the highest z value layer will always show on top of the others

# Then I add the sprite, and set the z to 1 so that it shows on top of the map layer
scroller.add(sprite_layer, z=1)

# Then I make a ColorLayer, just to spice up the background a bit (which for now is just transparent)
bg_color = ColorLayer(52, 152, 219, 1000)

# Then I make a scene
scene = Scene()
# And I add the scroller to it and put it on top of the stack of layers
scene.add(scroller, z=1)

# And I add the background color (I don't need to define a z because by default it's 0)
scene.add(bg_color)
Esempio n. 19
0
        if (symbol == key.LEFT):
            self.sprite.image = self.animationLeft

    def shoot(self):
        accBullet = bullet(self.sprite.position)
        super().add(accBullet.returnSprite())
        self.collision_manager.add(accBullet.returnSprite())
        self.bullets.append(accBullet)


# And lastly I set the position of the sprite to the center of the rectangle

spriteLayer = SpriteLayer()
spriteLayer.sprite.position = 100, 600

scroller.add(spriteLayer, z=1)
scroller.add(mapLayer, z=0)
scroller.add(bg, z=-1)

# From here it's pretty easy sailing
# First I add the map, and set the "z" to 0
#scroller.add(map_layer, z=0)
# The z is the vertical axis, so the highest z value layer will always show on top of the others

# Then I add the sprite, and set the z to 1 so that it shows on top of the map layer

bg_color = ColorLayer(52, 152, 219, 1000)

# Then I make a scene
scene = Scene()
# And I add the scroller to it and put it on top of the stack of layers
Esempio n. 20
0
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
class Testing(cocos.layer.Layer):
    is_event_handler = True
Esempio n. 21
0
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
        self.sprite.max_reverse_speed = -100
        self.add(self.sprite)
        self.sprite.do(cardriver())


car_layer = carlayer()
map_layer = load("assets/road_map.tmx")["map0"]
scroller.add(map_layer)
scroller.add(car_layer)
scene = Scene(scroller)
director.window.push_handlers(keeb)
director.run(scene)
Esempio n. 22
0
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
# Essentially, we need to find the cell where I marked for the player to start, and set the sprite as starting there
# We do this by first finding that cell I marked (check the source code of the map to see how it's done)
start = map_layer.find_cells(player_start=True)[0]

# Then I get that bounded rectangle we talked about earlier from the sprite
rect = sprite_layer.sprite.get_rect()

# After that I set the middle bottom of the sprite's bounded rectangle equal to the middle bottom of the start cell
rect.midbottom = start.midbottom

# And lastly I set the position of the sprite to the center of the rectangle
sprite_layer.sprite.position = rect.center

# From here it's pretty easy sailing
# First I add the map, and set the "z" to 0
scroller.add(map_layer, z=0)
# The z is the vertical axis, so the highest z value layer will always show on top of the others

# Then I add the sprite, and set the z to 1 so that it shows on top of the map layer
scroller.add(sprite_layer, z=1)

# Then I make a ColorLayer, just to spice up the background a bit (which for now is just transparent)
bg_color = ColorLayer(52, 152, 219, 1000)

# Then I make a scene
scene = Scene()
# And I add the scroller to it and put it on top of the stack of layers
scene.add(scroller, z=1)

# And I add the background color (I don't need to define a z because by default it's 0)
scene.add(bg_color)
Esempio n. 24
0
def update(dt):
	""" Update game"""
	last = layer.sprite.get_rect()
	new = last.copy()
	new.x += layer.sprite.dx
	new.y += layer.sprite.dy
	collider.collide_map(tilemap, last, new, layer.sprite.dy, layer.sprite.dx)
	layer.sprite.position = new.center
	print('center, dy, bottom:', new.center, layer.sprite.dy, new.bottom)
	scroller.set_focus(*new.center)

# Schedule Updates
layer.schedule(update)

# Add map to scroller
scroller.add(tilemap)

#Create Scene
scene = Scene()

# Create and add background
background = Background()
scene.add(background)

#Add main layer to scroller
scroller.add(layer)
scroller.add(ShowCollision())

# Add scroller to scene
scene.add(scroller)
Esempio n. 25
0
            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')
Esempio n. 26
0
    """ Update game"""
    last = layer.sprite.get_rect()
    new = last.copy()
    new.x += layer.sprite.dx
    new.y += layer.sprite.dy
    # dont care about velocity, pass 0, 0
    collider.collide_map(tilemap, last, new, 0.0, 0.0)
    layer.sprite.position = new.center
    scroller.set_focus(*new.center)


# Schedule Updates
layer.schedule(update)

# Add map to scroller
scroller.add(tilemap)

#Create Scene
scene = Scene()

# Create and add background
background = Background()
scene.add(background)

#Add main layer to scroller
scroller.add(layer)
scroller.add(ShowCollision())

# Add scroller to scene
scene.add(scroller)
Esempio n. 27
0
    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)
Esempio n. 28
0
        # Then we add it
        self.add(self.sprite)

        # And lastly we make it do that CarDriver action we made earlier in this file (yes it was an action not a layer)
        self.sprite.do(CarDriver())

# Now to the code that actually runs this game!
# Here I make a layer out of that CarLayer we defined before
car_layer = CarLayer()

# Next I load the map of the racetrack just as I did in the last tutorial
map_layer = load("assets/road_map.tmx")["map0"]

# Then we add them to the ScrollingManager
scroller.add(map_layer)
scroller.add(car_layer)
# Order is important! If we added the car layer first, the map would go on top and you wouldn't see the car

# Then we make a scene out of the scroller (just like we did before)
scene = Scene(scroller)

# This line is a bit random here but...
# I also need to push the handlers from the window to the object from Pyglet
# If I don't, it won't be able to handle the Cocos2D keyboard input!
director.window.push_handlers(keyboard)

# And finally we run the scene
director.run(scene)

# Now our games are actually starting to seem like, well, games!