def __init__(self): super().__init__() self.scale = 0.8 self.position = -50, -50 explosion_animation = image.Animation.from_image_sequence( image.ImageGrid(image.load('explosion.png'), 1, 8), 0.1, ) self.explosion = sprite.Sprite( explosion_animation, position=(320, 240), scale=1.5, ) self.explosion2 = sprite.Sprite( explosion_animation, position=(160, 120), scale=1.7, ) self.explosion3 = sprite.Sprite( explosion_animation, position=(32, 32), ) self.add(self.explosion) self.explosion.add(self.explosion2) self.explosion2.add(self.explosion3)
def step(self, dt): super(Me, self).step(dt) # Run step function on the parent class. # Determine velocity based on keyboard inputs. if keyboard[key.RIGHT] > keyboard[key.LEFT]: direction = 0 print("up here dummy") else: direction = 1 velocity_x = 100 * (keyboard[key.RIGHT] - keyboard[key.LEFT]) velocity_y = 100 * (keyboard[key.UP] - keyboard[key.DOWN]) # Set the object's velocity. self.target.velocity = (velocity_x, velocity_y) player_layer = layer.Layer() if direction == 0: print("0") me = sprite.Sprite('standing.png', scale=1.0) else: print('1') me = sprite.Sprite('standingleft.png', scale=2.0) player_layer.add(me)
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, resizable=True) # Create a layer and add a sprite to it. player_layer = layer.Layer() if direction == 0: print("0") me = sprite.Sprite('standing.png', scale=1.0) else: print('1') me = sprite.Sprite('standingleft.png', scale=1.0) 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 __init__(self, parent, is_enemy=False): super(Snake, self).__init__() self.parent = parent self.scale = 1.5 self.is_enemy = is_enemy self.is_dead = False self.rotation_rate = 90 self.move_time = 0.20 # 蛇移动单位距离需要的时间,时间越少,蛇移动得越快 self.max_move_time = 0.20 self.score_to_body = 1000 self.score = 5000 self.length = 5 window_size = director.director.get_window_size() self.center = (window_size[0] / 2, window_size[1] / 2 ) # center即主角蛇头相对于窗口的位置 # 主角: if not self.is_enemy: self.position = random.randrange(700, 900), random.randrange( 350, 450) # 设置出生的位置 self.color = define.LIGHT_PINK else: # 敌人 self.position = random.randrange(300, 1300), random.randrange(200, 600) if 600 < self.x < 1000: self.x += 400 self.schedule_interval(self.AI, random.randrange(1, 2) + 0.5) self.color = random.choice(define.ALL_COLOR) self.rotation = random.randrange(0, 360) # 增加头部 self.head = sprite.Sprite('circle.png', color=self.color) self.add(self.head) # 蛇身 self.body = [] # 增加一个眼球 eyeball = sprite.Sprite('circle.png', color=define.WHITE) eyeball.scale = 0.5 # 缩放是相对于父节点 eyeball.position = self.head.position eyeball.x = -5 # 偏移是相对于父节点 eyeball.y = 2 eye = sprite.Sprite('circle.png', color=define.BLACK) eye.scale = 0.5 eyeball.add(eye) self.head.add(eyeball) # 增加一个眼球 eyeball = sprite.Sprite('circle.png', color=define.WHITE) eyeball.scale = 0.5 # 缩放是相对于父节点 eyeball.position = self.head.position eyeball.x = 5 # 偏移是相对于父节点 eyeball.y = 2 eye = sprite.Sprite('circle.png', color=define.BLACK) eye.scale = 0.5 eyeball.add(eye) self.head.add(eyeball) # 开始初始化 self.init_body() self.schedule(self.update)
def __init__(self, card): self.card = card points = card.point card_type = card.__class__.__name__ self.selected = False self.sprite = ccsp.Sprite(sprite_path + card_type + ".png", anchor=(0, 0)) self.sprite.add( ccsp.Sprite(sprite_path + str(points) + ".png", scale=0.6, position=(32, 163)))
def __init__(self): super(BgLay, self).__init__() self.bp1 = sprite.Sprite("img/bg.png") self.bp2 = sprite.Sprite("img/bg.png") self.bp1.image_anchor = (0, 0) self.bp2.image_anchor = (0, 0) self.bp1.position = (0, 0) self.bp2.position = (0, config.WINDOS_HEIGHT - 1) self.add(self.bp1) self.add(self.bp2) self.schedule_interval(self.scroll_bg, 0.01)
def __init__(self, battle_btn): self.battle_btn = battle_btn self.chess = battle_btn.chess self.chess_type = self.chess.__class__.__name__ btn_size = gui_paras["battle-button-size"] base_height = gui_paras["margin-bottom"] + \ 2*gui_paras["hud-chess-size"] + gui_paras["battle-button-margin"] slot_vec = gui_paras["hud-chess-slot"][self.chess_type] i = slot_vec[0] * 4 + slot_vec[1] * 2 + slot_vec[2] pos = (resolution[0] - (i+0.5)*(btn_size+2*gui_paras["battle-button-margin"]), \ base_height + 0.5*btn_size) self.sprite = ccsp.Sprite(sprite_path + "ChipBlackYellow.png", position=pos) self.sprite.add(ccsp.Sprite(sprite_path+self.chess_type+str(self.chess.camp)+".png", \ scale=0.5))
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 __init__(self, image, itempack, item, x, y, scale=1): super().__init__() self.bgImage = sprite.Sprite("leveleditorItemHovered.png", scale=scale) self.bgImage.x = x self.bgImage.y = y self.px = 0 self.py = 0 #self.x = x #self.y = y self.itempack = itempack self.item = item self.width_range = [ int((self.px + self.bgImage.x) - (self.bgImage.width / 2)), int((self.px + self.bgImage.x) + (self.bgImage.width / 2)) ] self.height_range = [ int((self.py + self.bgImage.y) - (self.bgImage.height / 2)), int((self.py + self.bgImage.y) + (self.bgImage.height / 2)) ] self.active = False self.hovered = False self.bgImage.opacity = 0 self.add(self.bgImage) self.schedule_interval(self.setWH, 1) self.resume_scheduler()
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 add_background(): name = 'assets/backgrounds/fill.png' spriteObj = sprite.Sprite(name) spriteObj.src = name spriteObj.position = (0, 0) spriteObj.type = 0 spriteObj.image_anchor = (0, 0) Global.Layers.addWall(spriteObj)
def playShield(self, idx=0): def die(object): object.kill() if idx == 0: shield = sprite.Sprite( loadAnimation('data/graphics/ShieldAvatar.png', 4, 1, 0.05)) elif idx > 0: shield = sprite.Sprite( loadAnimation('data/graphics/ShieldAvatarRevived.png', 4, 1, 0.05)) elif idx < 0: shield = sprite.Sprite( loadAnimation('data/graphics/ShieldAvatarBlocked.png', 4, 1, 0.05)) self.add(shield) shield.do(adata['aDelay03'] + actions.CallFuncS(die))
def __init__(self): super(StartLayer, self).__init__() self.bg = sprite.Sprite('img/bg.png') self.bg.position = config.WINDOS_WIDTH // 2, config.WINDOS_HEIGHT // 2 self.add(self.bg, z=0) logo = sprite.Sprite('img/logo.png') logo.position = config.WINDOS_WIDTH // 2, config.WINDOS_HEIGHT // 2 + 300 logo.scale = 0.3 self.add(logo, z=2) feiji = sprite.Sprite('img/hero/hero2.png') feiji.position = config.WINDOS_WIDTH // 2, config.WINDOS_HEIGHT // 2 + 150 feiji.scale = 0.5 self.add(feiji, z=2) start_menu = StartMenu() self.add(start_menu, z=2)
def __init__(self): explosion = pyglet.image.load('assets/weapons/standart-bullet-explode.png') explosion_seq = pyglet.image.ImageGrid(explosion, 1, 12) explosion_tex_seq = pyglet.image.TextureGrid(explosion_seq) self.animation = pyglet.image.Animation.from_image_sequence(explosion_tex_seq, .05, loop=False) self.anim = sprite.Sprite(self.animation) self.anim.image_anchor = (self.animation.get_max_width() / 2, self.animation.get_max_height() / 4) self.anim.scale = 0.2
def __init__(self): super(StartMenuLayer, self).__init__() self.game_menu = GameStartMenu() self.add(self.game_menu) logo = sprite.Sprite('imgs/logo.png') logo.position = config.WIN_WIDTH // 2, config.WIN_HEIGHT // 2 + 130 logo.scale = 0.5 self.add(logo)
def __init__(self, position=(0, 0)): super().__init__() self.position = position self.tank = sprite.Sprite('tank.png', scale=C['TankScale']) self.add(self.tank) self.rotation = 0 self.speed = 0
def __init__(self, itempack, label, item_blocks=[]): super().__init__() self.packLbl = text.Label(label, font_size=14, anchor_x="center", anchor_y="center") self.packLbl.x = reswidth * 0.15 self.packLbl.y = resheight * 0.095 self.blocks = [] self._visible = False if item_blocks[0] == "empty": itemBlock = sprite.Sprite("emptyBlock.png", scale=1.2) itemBlock.x = reswidth * 0.05 itemBlock.y = resheight * 0.045 itemBlock.opacity = 0 itemSelectionBlock = self.ItemHoverBox( "leveleditorItemHovered.png", None, "empty", reswidth * 0.05, resheight * 0.045, scale=1.2) self.add(itemBlock, z=1) self.add(itemSelectionBlock, z=2) self.blocks.append([itemBlock, itemSelectionBlock]) else: for itemId in range(len(item_blocks)): itemBlock = sprite.Sprite(items.itempacks[ itempack.idx].item_data[item_blocks[itemId][:-4]].image, scale=1.2) itemBlock.x = (reswidth * 0.05) + (reswidth * (0.04 * itemId)) itemBlock.y = resheight * 0.045 itemBlock.opacity = 0 itemSelectionBlock = self.ItemHoverBox( "leveleditorItemHovered.png", itempack, item_blocks[itemId], (reswidth * 0.05) + (reswidth * (0.04 * itemId)), resheight * 0.045, scale=1.2) self.add(itemBlock, z=1) self.add(itemSelectionBlock, z=2) self.blocks.append([itemBlock, itemSelectionBlock]) self.add(self.packLbl)
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, score): super(GameOverLayer, self).__init__() self.bg = sprite.Sprite('img/bg.png') self.bg.position = config.WINDOS_WIDTH // 2, config.WINDOS_HEIGHT // 2 self.add(self.bg, z=0) feiji = sprite.Sprite('img/hero/hero1.png') feiji.position = config.WINDOS_WIDTH // 2, config.WINDOS_HEIGHT - 200 feiji.scale = 0.5 self.add(feiji) score_label = text.Label(u'得分:%d' % score, font_size=20, font_name="Microsoft Yahei", color=(10, 10, 10, 255), anchor_x="center", anchor_y="center") score_label.position = config.WINDOS_WIDTH // 2, config.WINDOS_HEIGHT - 300 self.add(score_label)
def __init__(self): win_width, win_height = config.WIN_WIDTH, config.WIN_HEIGHT super(GameLayer, self).__init__() self.bg1 = sprite.Sprite('imgs/bg.png') self.bg1.image_anchor = 0, 0 self.bg1.position = 0, 0 self.bg2 = sprite.Sprite('imgs/bg.png') self.bg2.image_anchor = 0, 0 self.bg2.position = 0, win_height # 添加背景 self.add(self.bg1) self.add(self.bg2) # 添加自己的飞机 self.hero = Hero() self.add(self.hero, z=1000) # 敌机 self.enemy_batch = batch.BatchNode() self.add(self.enemy_batch) self.resuable_small_enemy_set = set() self.active_small_enemy_set = set() self.all_small_enemy_set = set() # 积分榜 self.score_board = ScoreBoard() self.add(self.score_board) # 碰撞检测 self.enemy_collision = collision_model.CollisionManagerGrid( 0, config.WIN_WIDTH, 0, config.WIN_HEIGHT, 110, 110) self.enemy_bullet_collisoin = collision_model.CollisionManagerGrid( 0, config.WIN_WIDTH, 0, config.WIN_HEIGHT - 50, 10, 10) # 消息调度 self.schedule(self.run) self.schedule_interval(self.update_enemy, 0.2)
def __init__(self): super(Animation, self).__init__() self.cabbage = sprite.Sprite(image=settings.CABBAGE) self.cabbage.scale = 0.7 self.add(self.cabbage, z=1) self.sheep = sprite.Sprite(image=settings.SHEEP) self.sheep.scale = 1.5 self.add(self.sheep, z=1) self.wolf = sprite.Sprite(image=settings.WOLF) self.wolf.scale = 1.5 self.add(self.wolf, z=1) self.farmer = sprite.Sprite(image=settings.FARMER) self.farmer.scale_y = 1.3 self.add(self.farmer, z=1) self.boat = sprite.Sprite(image=settings.BOAT) self.add(self.boat, z=1) self.do_animate()
def __init__(self): super(BackgroundLayer,self).__init__() bg = sprite.Sprite('images/game_bg_2_hd.jpg') bg.position = WIN_WIDTH // 2,WIN_HEIGHT // 2 self.cannon = Cannon() self.add(bg) self.add(self.cannon) self.collision_manager = collision.CollisionManager(); self.fishs = [] for x in range(1,100): fish = Fish() self.add(fish) self.fishs.append(fish) self.nets = []
def add_body(self): # 增加身体长度的函数 body_part = sprite.Sprite('circle.png', color=self.color) if len(self.body) == 0: # 如果当前只有头部,根据当前头部的方向,确定新生成的身体的位置 x = -math.sin(self.rotation / 360 * 2 * math.pi) * body_part.width y = -math.cos(self.rotation / 360 * 2 * math.pi) * body_part.height last_x, last_y = self.position body_part.rotation = self.rotation else: # 如果已有一部分的身体,根据最后一个身体部分的位置,确定新生成的身体的位置 x = -math.sin( self.body[-1].rotation / 360 * 2 * math.pi) * body_part.width y = -math.cos( self.body[-1].rotation / 360 * 2 * math.pi) * body_part.height last_x, last_y = self.body[-1].position body_part.rotation = self.body[-1].rotation body_part.position = last_x + x, last_y + y body_part.scale = 1.5 self.body.append(body_part) # 将新生成的部分部分加入到身体中 self.parent.batch.add(body_part, define.SNAKE_FLOOR)
def loadPalitra(self): #imgs = sorted(glob.glob('assets/*')) imgs = sorted(scandir('assets')) names = [] for file in imgs: names.append(file.name) for src in sorted(names): src = 'assets/' + str(src) land = sprite.Sprite(src) land.cshape = cm.AARectShape(land.position, land.width // 2, land.height // 2) land.src = src self.palitra.add(land) self.palitraObject.append(land) self.palitraCollision.add(land)
def addBrick(self, x, y): x = x // 32 * 32 + 16 y = y // 32 * 32 + 16 spriteObj = sprite.Sprite(self.currentSprite.src) spriteObj.src = self.currentSprite.src spriteObj.position = (x, y) spriteObj.type = self.currentType spriteObj.cshape = cm.AARectShape(spriteObj.position, spriteObj.width // 2, spriteObj.height // 2) intersec = self.objectProvider.checkIntersec(spriteObj) if intersec: return self.walls.append(spriteObj) self.collision.add(spriteObj) self.add(spriteObj)
def loadMap(self, map): for block in map: try: x, y = block['position'] spriteObj = sprite.Sprite(block['src']) spriteObj.src = block['src'] spriteObj.position = (x, y) spriteObj.type = block['type'] spriteObj.cshape = cm.AARectShape(spriteObj.position, spriteObj.width // 2, spriteObj.height // 2) self.walls.append(spriteObj) self.add(spriteObj) if spriteObj.type: self.collision.add(spriteObj) except pyglet.resource.ResourceNotFoundException: pass
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 __init__(self, parallax=1, **kwargs): super().__init__(parallax=parallax) self.gridList = [] self.gridBatch = batch.BatchNode() self.scroller = kwargs["scroller"] self.level = kwargs["level"] self.walls = kwargs["walls"] self.decorations = kwargs["decorations"] self.hovered = None global selectedTiles selectedTiles = [] self.dragging = [] self.initialCell = None for column in kwargs["walls"].cells: self.gridList.append([]) for cell in column: gridCell = sprite.Sprite("leveleditorItem.png") gridCell.x = ((cell.i + 1) * 32) - 16 gridCell.y = ((cell.j + 1) * 32) - 16 self.gridBatch.add(gridCell) self.gridList[cell.i].append([gridCell, False]) self.add(self.gridBatch)
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 __init__(self): # Blueish color super(HelloActions, self).__init__( r=64, g=64, b=224, a=255, ) 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) # Add a cocos Sprite. sprite_ = sprite.Sprite('HSCard.png') sprite_.position = 320, 240 # [NOTE] The sprite will 3 times bigger. sprite_.scale = 0.58 # [NOTE] z is the precedence of the sprite. This sprite will on the top of the label. self.add(sprite_, z=1) # [LEARN] We create a ScaleBy action. It will scale 3 times the object in 2 seconds: scale = actions.ScaleBy(3, duration=2) # [LEARN] '+' is sequence action here. # 'Reverse' reverse the action. label.do(actions.Repeat(scale + actions.Reverse(scale))) sprite_.do(actions.Repeat(actions.Reverse(scale) + scale))