Exemple #1
0
 def __init__(self):
     Layer.__init__(self)
     self.config = Config()
     self.gallery = Gallery()
     self.schedule_interval(self.music_start, interval=7)
     self.intro_sound = load("music/sound_start.wav", streaming=False)
     self.intro_sound.play()
     self.is_event_handler = True
     background = Sprite(self.gallery.content["display"]["title"])
     self.optimal_scale = (
         self.config.window_width *
         self.display_pos_size["display_title"]["W"]) / background.width
     background.image_anchor = 0, 0
     background.scale = self.optimal_scale
     background.x = self.config.window_width * self.display_pos_size[
         "display_title"]["X"]
     background.y = self.config.window_height * self.display_pos_size[
         "display_title"]["Y"]
     self.left_margin = background.x
     self.bottom_margin = background.y
     self.optimal_width = background.width
     self.optimal_height = background.height
     self.add(background)
     place_holder_image = Sprite(self.gallery.content["screen"]["title"])
     place_holder_image.position = director.window.width / 2, director.window.height / 2
     place_holder_image.scale = self.optimal_scale
     place_holder_image.do(ScaleBy(5.2, duration=25))
     self.add(place_holder_image)
 def bring(self, minion):
     if minion == "gatherer":
         if self.gathval:
             mini = Sprite(load_animation("resources/gatherer_coming.gif"),
                           position = (spawn_place[minion][0] + minion_move_to[minion][0],
                                       spawn_place[minion][1] + minion_move_to[minion][1]))
             mini.scale = minion_scale
             self.add(mini)               
             mini.do(MoveTo(spawn_place[minion], minion_move_time) + CallFunc(mini.kill))
             self.gathval = False
         else:
             mini1 = Sprite(load_animation("resources/gatherer.gif"), position = spawn_place[minion])
             mini1.scale = minion_scale
             self.add(mini1)               
             mini1.do(MoveBy(minion_move_to[minion], minion_move_time) + CallFunc(mini1.kill))
             self.gathval = True
     elif minion == "miner":
         if self.minval:
             mini = Sprite(load_animation("resources/miner.gif"), 
                         position = (spawn_place[minion ][0] + minion_move_to[minion][0],
                         spawn_place[minion][1] + minion_move_to[minion][1]))
             mini.scale = minion_scale
             mini.scale_x = -minion_scale
             self.add(mini)               
             mini.do(MoveTo( (spawn_place[minion]), minion_move_time) + CallFunc(mini.kill) )
             self.minval = False
         else:
             mini1 = Sprite(load_animation("resources/miner.gif"), position = spawn_place[minion])
             mini1.scale = minion_scale
             self.add(mini1)               
             mini1.do(MoveBy(minion_move_to[minion], minion_move_time) + CallFunc(mini1.kill))
             self.minval = True
Exemple #3
0
 def __init__(self):
     super(Snake, self).__init__()
     self.score = 30
     self.head = Sprite('img/circle.png', color=random.choice(rand_color))
     self.head.scale = 1.5
     self.head.set_position(director.get_window_size()[0] / 2,
                            director.get_window_size()[1] / 2)
     eyeball = Sprite('img/circle.png', color=(253, 55, 80))
     eyeball.scale = 0.5
     eye_left = Sprite('img/circle.png')
     eye_left.y = 5
     eye_left.scale = 0.5
     eye_left.add(eyeball)
     eye_right = Sprite('img/circle.png')
     eye_right.y = -5
     eye_right.scale = 0.5
     eye_right.add(eyeball)
     mouth = Sprite('img/circle.png', color=(0, 0, 0))
     mouth.x = +5
     mouth.scale = 0.3
     self.head.add(mouth)
     self.head.add(eye_left)
     self.head.add(eye_right)
     self.add(self.head)
     self.schedule_interval(self.update, random.random() * 0.2 + 0.1)
    def __init__(self):
        super( TestLayer, self ).__init__()

        x,y = director.get_window_size()

        sprite1 = Sprite('grossini.png')
        sprite1.position = x//4, y//2
        self.add( sprite1 )

        sprite2 = Sprite('grossini.png')
        sprite2.position = x//4, y//2
        self.add( sprite2, z=2  )
        sprite2.scale = 0.3

        sprite2.do( RotateBy(duration=2, angle=360) )
        sprite1.do( RotateBy(duration=2, angle=-360) )

        sprite1.transform_anchor = 0, 0

        sprite3 = Sprite('grossini.png')
        sprite3.position = 3*x//4, y//2
        self.add( sprite3  )

        sprite4 = Sprite('grossini.png')
        sprite4.position = 3*x//4, y//2
        self.add( sprite4, z=2  )
        sprite4.scale = 0.3

        sprite3.do( RotateBy(duration=2, angle=360) )
        sprite4.do( RotateBy(duration=2, angle=-360) )

        sprite3.transform_anchor = sprite3.image.width//2, sprite3.image.height//2
 def _load_background(self):
     background = Sprite(self.gallery.content["display"]["city_" +
                                                         self.market])
     self.optimal_scale = (self.config.window_width *
                           self.display_pos_size["display_city_commerce"]
                           ["W"]) / background.width
     background.image_anchor = 0, 0
     background.scale = self.optimal_scale
     background.x = self.config.window_width * self.display_pos_size[
         "display_city_commerce"]["X"]
     background.y = self.config.window_height * self.display_pos_size[
         "display_city_commerce"]["Y"]
     self.left_margin = background.x
     self.bottom_margin = background.y
     self.optimal_width = background.width
     self.optimal_height = background.height
     self.add(background)
     if self.market == "commerce":
         overlay = Sprite(self.gallery.content["display"]["city_commerce_" +
                                                          self.supply])
         overlay.image_anchor = 0, 0
         overlay.x = self.left_margin
         overlay.y = self.bottom_margin
         overlay.scale = self.optimal_scale
         self.add(overlay)
Exemple #6
0
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        sprite1 = Sprite('grossini.png')
        sprite1.position = x // 4, y // 2
        self.add(sprite1)

        sprite2 = Sprite('grossini.png')
        sprite2.position = x // 4, y // 2
        self.add(sprite2, z=2)
        sprite2.scale = 0.3

        sprite2.do(RotateBy(duration=2, angle=360))
        sprite1.do(RotateBy(duration=2, angle=-360))

        sprite1.transform_anchor = 0, 0

        sprite3 = Sprite('grossini.png')
        sprite3.position = 3 * x // 4, y // 2
        self.add(sprite3)

        sprite4 = Sprite('grossini.png')
        sprite4.position = 3 * x // 4, y // 2
        self.add(sprite4, z=2)
        sprite4.scale = 0.3

        sprite3.do(RotateBy(duration=2, angle=360))
        sprite4.do(RotateBy(duration=2, angle=-360))

        sprite3.transform_anchor = sprite3.image.width // 2, sprite3.image.height // 2
Exemple #7
0
    def __init__(self, game, interface, meta):
        super().__init__(242, 242, 242, 255)

        background_sprite = Sprite('fondo_final.svg', anchor=(0, 0))
        background_sprite.position = (0, 0)
        background_sprite.scale = 0.1
        self.add(background_sprite, z=0)

        self.game = game
        self.toaster = None
        self.meta = meta

        self.meta["current_world"] = 0
        self.current_screen = 0
        self.space_used = 1
        self.interface = interface
        self.main_character = CollidableSprite('ppepotato.svg', anchor=(0, 0))
        self.collision_manager = CollisionManagerBruteForce()
        self.collision_manager.add(self.main_character)
        self.add(self.main_character)
        self.sprites_by_id = {}
        self.explosions = []

        self.do_draw()

        self.schedule_interval(self.check_collisions, 0.1)
        self.schedule_interval(self.check_finished, 0.1)
Exemple #8
0
 def _load_background(self):
     background = Sprite(
         self.gallery.content["display"]["worldmap_minitrain"])
     self.optimal_scale = (self.config.window_width * self.display_pos_size[
         "display_worldmap_minitrain"]["W"]) / background.width
     background.image_anchor = 0, 0
     background.scale = self.optimal_scale
     background.x = self.config.window_width * self.display_pos_size[
         "display_worldmap_minitrain"]["X"]
     background.y = self.config.window_height * self.display_pos_size[
         "display_worldmap_minitrain"]["Y"]
     self.left_margin = background.x
     self.bottom_margin = background.y
     self.optimal_width = background.width
     self.optimal_height = background.height
     #self.add(background)
     white_base = ColorLayer(255,
                             255,
                             255,
                             255,
                             width=background.width * 6,
                             height=background.height + 10)
     white_base.x = background.x - (background.width * 3)
     white_base.y = background.y + self.bottom_margin
     self.add(white_base)
Exemple #9
0
    def _create_sprites(self):
        SPEED = 0.4

        logo_image = common.load_image('scene/intro/ceferino.png')
        logo = Sprite(logo_image)
        logo.scale = 4
        logo.rotation = 180
        logo.opacity = 0
        logo.do(Place((100, 230)))
        logo.do(Delay(SPEED / 2) + 
                (FadeIn(SPEED * 2) | RotateBy(180, SPEED) | ScaleTo(1, SPEED)))

        losers_image = common.load_image('scene/intro/losers.png')
        losers = Sprite(losers_image)
        losers.position = 300, 500
        losers.rotation = 180
        losers.opacity = 0
        losers.do(Delay(SPEED) + 
                (MoveTo((300, 250), SPEED) | FadeIn(SPEED) | RotateBy(180, SPEED)))

        juegos_image = common.load_image('scene/intro/juegos.png')
        juegos = Sprite(juegos_image)
        juegos.position = 500, 0
        juegos.rotation = -180
        juegos.opacity = 0
        juegos.do(Delay(SPEED/2 * 3) +
                (MoveTo((520, 250), SPEED) | FadeIn(SPEED) | RotateBy(180, SPEED))
                + Delay(2) + CallFunc(self.skip_scene))

        self.add(logo)
        self.add(losers)
        self.add(juegos)
        self.juegos = juegos
    def challenge(self, type, pos):
         hunter = Sprite(load_animation("resources/" + type + ".gif"), position = (random.randint(483, 826), 105))
         hunter.scale = minion_scale
         self.add(hunter)               
         hunter.do(MoveTo(pos, minion_move_time)) 

         return hunter
    def _load_background(self):
        background = Sprite(
            self.gallery.content["display"]["worldmap_quarters"])
        self.optimal_scale = (self.config.window_width * self.display_pos_size[
            "display_worldmap_quarters"]["W"]) / background.width
        background.image_anchor = 0, 0
        background.scale = self.optimal_scale
        background.x = self.config.window_width * self.display_pos_size[
            "display_worldmap_quarters"]["X"]
        background.y = self.config.window_height * self.display_pos_size[
            "display_worldmap_quarters"]["Y"]
        self.left_margin = background.x
        self.bottom_margin = background.y
        self.optimal_width = background.width
        self.optimal_height = background.height
        self.add(background)

        self.ps_alarm = Sun()
        self.ps_alarm.total_particles = 20
        self.ps_alarm.speed = 0.0
        self.ps_alarm.speed_var = 0.0
        self.ps_alarm.life_var = 0.0
        self.ps_alarm.blend_additive = True
        self.ps_alarm.position = (
            self.optimal_width * self.button_positions["ps_alarm"]["X"] +
            self.left_margin), (
                self.optimal_height * self.button_positions["ps_alarm"]["Y"] +
                self.bottom_margin)
        self.ps_alarm.start_color = Color(1, 0.40, 0.40, 0.40)
        self.ps_alarm.size = 50.0
Exemple #12
0
 def _load_trade_boxes(self):
     self.remove_trade_boxes()
     if self.trade_display:
         self._load_button_gen("button", "drop", events.emit_commerce_switch_trade_dump, "button_switch", 0, 1, 0.95)
         for wagon in self.wagons_for_trade:
             self._load_button_gen("wagon", self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].display_image+"_t", events.emit_wagon_select, "trade_bracket"+str(wagon), wagon, 1, 0.99 )
             label_wagon_name = Label(self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].wagon_name + " ("+self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].storage+")", (self.optimal_width * (self.button_positions["sprite_trade_bracket"+str(wagon)]["X"]+0.112), self.optimal_height*(self.button_positions["sprite_trade_bracket"+str(wagon)]["Y"]+0.152)), color=(0,0,0,255), font_name="Arial", bold=True, font_size=16*self.optimal_scale, anchor_x="center", anchor_y="center")
             self.add(label_wagon_name, name="trade_bracket_wagon_name"+str(wagon))
             label_wagon_name = Label(" ", (self.optimal_width * (self.button_positions["sprite_trade_bracket"+str(wagon)]["X"]+0.112), self.optimal_height*(self.button_positions["sprite_trade_bracket"+str(wagon)]["Y"]+0.026)), color=(0,0,0,255), font_name="Arial", bold=True, font_size=14*self.optimal_scale, anchor_x="center", anchor_y="center")
             self.add(label_wagon_name, name="trade_bracket_wagon_hold"+str(wagon))
             self._load_button_gen("button", "plus", events.emit_item_buy, "button_buy"+str(wagon), wagon, 0.72, 0.95 )
             self._load_button_gen("button", "minus", events.emit_item_sell, "button_sell"+str(wagon), wagon, 0.72, 0.95 )
     else:
         self._load_button_gen("button", "trade", events.emit_commerce_switch_trade_dump, "button_switch", 0, 1, 0.95)
         for wagon in self.wagons_for_dump:
             trade_bracket = Sprite(self.gallery.content["wagon"][self.config.conf_wagons[self.wagons_for_dump[wagon]["wagon_id"]].display_image+"_t"])
             trade_bracket.image_anchor = 0, 0
             trade_bracket.scale = self.optimal_scale
             trade_bracket.x = self.optimal_width * self.button_positions["sprite_trade_bracket"+str(wagon)]["X"]
             trade_bracket.y = self.optimal_height * self.button_positions["sprite_trade_bracket"+str(wagon)]["Y"]
             self.add(trade_bracket, name="trade_bracket"+str(wagon))
             label_wagon_name = Label(self.config.conf_wagons[self.wagons_for_dump[wagon]["wagon_id"]].wagon_name + " ("+self.config.conf_wagons[self.wagons_for_dump[wagon]["wagon_id"]].storage+")", (self.optimal_width * (self.button_positions["sprite_trade_bracket"+str(wagon)]["X"]+0.112), self.optimal_height*(self.button_positions["sprite_trade_bracket"+str(wagon)]["Y"]+0.152)), color=(0,0,0,255), font_name="Arial", bold=True, font_size=16*self.optimal_scale, anchor_x="center", anchor_y="center")
             self.add(label_wagon_name, name="trade_bracket_wagon_name"+str(wagon))
             label_wagon_name = Label(" ", (self.optimal_width * (self.button_positions["sprite_trade_bracket"+str(wagon)]["X"]+0.112), self.optimal_height*(self.button_positions["sprite_trade_bracket"+str(wagon)]["Y"]+0.026)), color=(0,0,0,255), font_name="Arial", bold=True, font_size=14*self.optimal_scale, anchor_x="center", anchor_y="center")
             self.add(label_wagon_name, name="trade_bracket_wagon_hold"+str(wagon))
             self._load_button_gen("button", "minus", events.emit_item_sell, "button_sell"+str(wagon), wagon, 0.72, 0.95 )
     self.update_desc()
Exemple #13
0
    def __init__(self, piece, width, height):
        super(PieceLayer, self).__init__()
        
        self._width = width
        self._height = height
        self._piece = piece
        #logging.debug('New piece layer %d x %d, image name %s' % (width, height, piece.imageName()))

        # Pieces with the 'color' property get a background.
        if hasattr(piece, 'color'):
            #logging.debug('color ' + str(piece.color))
            c = colors[piece.color]
            bg = ColorLayer(c[0], c[1], c[2], 192, width=width, height=height)
            self.add(bg)
            self._background = bg

        pieceSprite = Sprite(piece.imageName())
        pieceSprite.image_anchor_x = 0
        pieceSprite.image_anchor_y = 0

        # Scale the sprite to the correct size.
        rect = pieceSprite.get_rect()
        scale = min(float(width) / rect.width,
                    float(height) / rect.height)
        pieceSprite.scale = scale
        self._pieceSprite = pieceSprite

        self.add(pieceSprite)
        self._opacity = 255

        self._turnIndicator = None
        self._updateTurnIndicator()
        self._chargeIndicator = None
        self._updateChargeIndicator()
Exemple #14
0
    def __init__(self, life=100, bullets=100):
        super(HudLayer, self).__init__()

        x, y = director.get_window_size()

        self.bullets_ico = face = Sprite('hud/bullets.png')
        self.bullets_ico.position = (
            self.bullets_ico.image.width/2,
            self.bullets_ico.image.height/2
        )

        self.bullets_label = cocos.text.Label(str(bullets),
            font_name='Times New Roman',
            font_size=32,
            x=self.bullets_ico.image.width+10,
            y=self.bullets_ico.image.height/2,
            anchor_x='left', anchor_y='center')
        self.add(self.bullets_ico)
        self.add(self.bullets_label)

        self.faces = {}
        self.deads = []
        space = 0
        self.face_scale = scale = 0.7
        for who in ["Dad", "Mom", "Zack", "Bee"]:
            sprite = Sprite('faces/%s.png'%who)
            self.faces[who] = sprite
            sprite.scale = scale
            sprite.position = (
                x-space-sprite.image.width*scale/2,
                sprite.image.height*scale/2
            )
            space += sprite.image.width*scale + 10

            self.add(sprite)
Exemple #15
0
    def check_queue(self, dt=0):
        width, height = cocos.director.director.get_window_size()

        image = fetch_image()
        sprite = Sprite(image)

        sprite.rotation = random.randint(-25, 25)

        end_scale = 1024.0 / image.width

        sw = int((image.width * end_scale) / 2)
        sh = int((image.height * end_scale) / 2)

        sprite.x = random.randint(sw, width - sw)
        sprite.y = random.randint(sh, height - sh)

        sprite.opacity = 0
        sprite.scale = end_scale * 1.5

        sprite.do(
            spawn(
                FadeIn(.2),
                AccelDeccel(ScaleTo(end_scale, duration=.4))) +
            Delay(15) +
            FadeOut(.5) +
            CallFunc(sprite.kill))

        self.z += 1
        self.add(sprite, z=self.z)
Exemple #16
0
    def draw_info_army(self, cell):
        """Прорисовка окна информации армии"""
        bg = Sprite("light95.png")
        bg.scale_x = 0.5
        bg.scale_y = 0.115
        bg.position = [self.X_POS_ARMY, self.Y_POS]

        self.mas_sprite.append(bg)
        mas_shift = [-3, -1, 1, 3]
        mas_count = [0]*4
        for unit in cell.army.army:
            for i in range(len(mas_count)):
                if unit.type_unit == i+1:

                    mas_count[i] += unit.count

        for i, g in enumerate(mas_shift):
            unit = Sprite(self.IMAGE_NAME[i] + str(cell.army.player) + ".png")
            unit.scale = 1.5
            unit.position = [self.X_POS_ARMY + self.SHIFT*g - 20, self.Y_POS]
            count = cocos.text.Label(str(mas_count[i]),
                                          font_name='Times New Roman',
                                          font_size=32,
                                          anchor_x='left', anchor_y='center')
            count.position = [self.X_POS_ARMY + self.SHIFT*g - 5, self.Y_POS]
            self.mas_sprite.append(count)
            self.mas_sprite.append(unit)

        for object in self.mas_sprite:
            chart.Chart().add(object)
Exemple #17
0
 def draw(self, flag):
     if flag == 1:
         '''Рисует окно'''
         N = 3
         window = Sprite("game_rule.png")
         window.position = [self.X_WINDOW, self.Y_WINDOW]
         window.scale = 0.8
         self.mas_sprite = [window]
         exit = Sprite("exit.png")
         exit.position = [self.X_BTN, self.Y_BTN]
         self.mas_sprite.append(exit)
         self.mas_text = []
         self.mas_test_pos = []
         d = os.path.dirname(__file__)
         interface = os.path.join(d, '../resources')
         interface += '/' + 'rules.txt'
         f = open(interface, 'r', encoding='utf-8')
         x = 130
         y = 650
         for line in f:
             label = cocos.text.Label(line,
                                      font_name='Arial',
                                      font_size=14,
                                      anchor_x='left', anchor_y='center')
             label.position = x, y
             y -= 13
             self.mas_sprite.append(label)
         for object in self.mas_sprite:
             chart.Chart().add(object)
 def __init__(self):
     super(SpriteMenuDocks, self).__init__()
     sprite_menu_1 = Sprite('src/arts/in_game_menu_docks.png')
     sprite_menu_1.scale = 2 / 3
     size = cocos.director.director.get_window_size()
     self.add(sprite_menu_1)
     sprite_menu_1.position = size[0]*17/20, size[1]/2
Exemple #19
0
    def __init__(self):

        super(MainLayer, self).__init__()

        player = Sprite('sprites/Idle__000.png')
        player.scale = 0.2
        player.position = 120, 250

        # player.do(MoveBy((450, 0), 3))

        # player.do(Place((120, 400)))
        # player.do(RotateBy(120,0))
        # player.do(ScaleTo(1, 3))

        # player.do(Blink(10, 3))
        # player.do(Repeat(RotateBy(360, 1)))

        # caminarDerecha = MoveBy((450, 0), 2)
        # reiniciarPosicion = Place((120, 250))
        # player.do(caminarDerecha + reiniciarPosicion)

        # caminarDerecha = MoveBy((450, 0), 2)
        # rotar = RotateBy(360, 1) * 2
        # player.do(caminarDerecha | rotar)

        # player.do(Blink(10, 3) + Show())

        rotar = Repeat(RotateBy(360, 1))
        achicar = ScaleTo(0, 2.5)
        player.do(rotar | achicar)

        self.add(player)
Exemple #20
0
 def bring(self, minion):
     if minion == "gatherer":
         if self.gathval:
             mini = Sprite(load_animation("resources/gatherer_coming.gif"),
                           position=(spawn_place[minion][0] +
                                     minion_move_to[minion][0],
                                     spawn_place[minion][1] +
                                     minion_move_to[minion][1]))
             mini.scale = minion_scale
             self.add(mini)
             mini.do(
                 MoveTo(spawn_place[minion], minion_move_time) +
                 CallFunc(mini.kill))
             self.gathval = False
         else:
             mini1 = Sprite(load_animation("resources/gatherer.gif"),
                            position=spawn_place[minion])
             mini1.scale = minion_scale
             self.add(mini1)
             mini1.do(
                 MoveBy(minion_move_to[minion], minion_move_time) +
                 CallFunc(mini1.kill))
             self.gathval = True
     elif minion == "miner":
         if self.minval:
             mini = Sprite(load_animation("resources/miner.gif"),
                           position=(spawn_place[minion][0] +
                                     minion_move_to[minion][0],
                                     spawn_place[minion][1] +
                                     minion_move_to[minion][1]))
             mini.scale = minion_scale
             mini.scale_x = -minion_scale
             self.add(mini)
             mini.do(
                 MoveTo((spawn_place[minion]), minion_move_time) +
                 CallFunc(mini.kill))
             self.minval = False
         else:
             mini1 = Sprite(load_animation("resources/miner.gif"),
                            position=spawn_place[minion])
             mini1.scale = minion_scale
             self.add(mini1)
             mini1.do(
                 MoveBy(minion_move_to[minion], minion_move_time) +
                 CallFunc(mini1.kill))
             self.minval = True
Exemple #21
0
 def add_body(self):
     b = Sprite('circle.png', color=self.color)
     b.scale = 1.5
     self.body.append(b)
     if self.x == 0:
         print self.position
     b.position = self.position
     self.parent.batch.add(b, 9999 - len(self.body))
Exemple #22
0
 def add_body(self):
     b = Sprite('circle.png', color=self.color)
     b.scale = 1.5
     self.body.append(b)
     if self.x == 0:
         print self.position
     b.position = self.position
     self.parent.batch.add(b, 9999 - len(self.body))
Exemple #23
0
    def challenge(self, type, pos):
        hunter = Sprite(load_animation("resources/" + type + ".gif"),
                        position=(random.randint(483, 826), 105))
        hunter.scale = minion_scale
        self.add(hunter)
        hunter.do(MoveTo(pos, minion_move_time))

        return hunter
 def add_named_node(self,name,p0,color=(255,255,255)):
     x,y = p0
     b = Sprite('data/npoint.png',color=color)
     b.x = x*scale+offset
     b.y = y*scale+offset
     b.scale = 1.0/8.0
     self.add(b)
     self.add_named(name,[b])
Exemple #25
0
    def __init__(self):

        super(MainLayer, self).__init__()

        player = Sprite('sprites/Idle__000.png')
        player.scale = 0.2
        player.position = 120, 250

        self.add(player)
Exemple #26
0
    def invoke(self, minion):
        mini = Sprite(load_animation("resources/" + minion + ".gif"),
                      position=spawn_place[minion])
        mini.scale = minion_scale
        self.add(mini)

        mini.do(
            MoveBy(minion_move_to[minion], minion_move_time) +
            CallFunc(mini.kill))
Exemple #27
0
 def tile_sprite(self, tile_type, pos):
     """
     :param tile_type: numeric id, must be in the range of available images
     :param pos: sprite position
     :return: sprite built form tile_type
     """
     sprite = Sprite(tile_type)
     sprite.position = pos
     sprite.scale = 1
     return sprite
Exemple #28
0
 def tile_sprite(self, tile_type, pos):
     """
     :param tile_type: 数字ID必须在可用图像的范围内
     :param pos:精灵的位置
     :return: 根据tile_type编译精灵
     """
     sprite = Sprite(tile_type)
     sprite.position = pos
     sprite.scale = 1
     return sprite
Exemple #29
0
 def tile_sprite(self, tile_type, pos):
     """
     :param tile_type: numeric id, must be in the range of available images
     :param pos: sprite position
     :return: sprite built form tile_type
     """
     sprite = Sprite(tile_type)
     sprite.position = pos
     sprite.scale = 1
     return sprite
    def __init__(self, is_enemy=False):  # 初始化并设置状态为玩家
        super(Snake, self).__init__()  # 初始化
        self.is_dead = False  # 初始化状态为存活
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)  # 随机颜色
        if is_enemy:  # 随机怪物位置
            self.position = random.randrange(150,
                                             650), random.randrange(100, 300)
            if 300 < self.x < 500:
                self.x += 200
        else:  # 随机玩家位置
            self.position = random.randrange(350,
                                             450), random.randrange(180, 230)
        self.is_enemy = is_enemy  # 传入状态
        self.head = Sprite('circle.png', color=self.color)  # 设置头的颜色
        self.scale = 1.5  # 设置头的尺寸
        eye = Sprite('circle.png')  # 设置眼睛
        eye.y = 5  # 设置眼睛的Y轴
        eye.scale = 0.5  # 设置眼睛的尺寸
        eyeball = Sprite('circle.png', color=define.BLACK)  # 设置眼球的颜色
        eyeball.scale = 0.5  # 设置眼球的尺寸
        eye.add(eyeball)  # 在眼睛中添加眼球
        self.head.add(eye)  # 在头中添加眼睛
        eye = Sprite('circle.png')  # 设置眼睛
        eye.y = -5  # 设置眼睛的Y轴
        eye.scale = 0.5  # 设置眼睛的尺寸
        eyeball = Sprite('circle.png', color=define.BLACK)  # 设置眼球的颜色
        eyeball.scale = 0.5  # 设置眼球的尺寸
        eye.add(eyeball)  # 在眼睛中添加眼球
        self.head.add(eye)  # 设置眼睛

        self.add(self.head)  # 把头添加进身体

        self.speed = 200  # 设置怪物速度
        if not is_enemy:  # 设置玩家速度
            self.speed = 150
        self.path = [self.position] * 100  # 用一个列表记录蛇头经过的位置,身子则根据路径中对应数据更新位置

        self.schedule(self.update)  # 在时间安排表中加入snake的更新
        if self.is_enemy:  # 更新怪物
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)
Exemple #31
0
    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300,
                                             1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
        else:
            self.position = random.randrange(700,
                                             900), random.randrange(350, 450)
        self.is_enemy = is_enemy
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 150
        if not is_enemy:
            self.speed = 180
        self.path = [self.position] * 100

        self.schedule(self.update)
        if self.is_enemy:
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)
 def add_circle(self,center,radius):
     cx , cy = center
     sprites = []
     for a in xrange(0, 360, 8):
         b = Sprite('data/npoint.png')#,color=(140,140,140))
         b.x = (cx + radius*cos(radians(a)))*scale+offset
         b.y = (cy + radius*sin(radians(a)))*scale+offset
         b.scale = 1.0/16.0
         self.add(b)
         sprites.append(b)
     return sprites
 def add_wpts(self,wpts):
     sprites = []
     for x,y in wps:
         b = Sprite('data/npoint.png')#,color=(140,140,140))
         b.x = x*scale+offset
         b.y = y*scale+offset
         b.scale = 1.0/8.0
         self.add(b)
         self.add_named('P%s %s'%(x,y),[b])
         sprites.append(b)
     return sprites
    def __init__(self):
        super( TestLayer, self ).__init__()

        go_through = [(100,300), (370,330), (430,270), (750,550)]

        # visually spot through where it should go
        for pos in go_through:
            sprite = Sprite('fire.png')
            sprite.position = pos
            sprite.scale = .3
            self.add(sprite)

        # calculate the points
        bezier_path = direct_bezier(*go_through)

        sprite = Sprite('fire.png')
        sprite.scale = .3
        sprite.color = (0, 0, 255)
        self.add(sprite, z=5)
        sprite.do(Bezier(bezier_path, 5))
 def _load_background(self, bubble_type, px, py, pscale):
     background = Sprite(self.gallery.content["text"]["bubble_" +
                                                      bubble_type])
     background.scale = pscale
     background.image_anchor = 0, 0
     background.x = px
     background.y = py
     self.left_margin = background.x
     self.bottom_margin = background.y
     self.optimal_width = background.width
     self.optimal_height = background.height
Exemple #36
0
    def __init__(self):
        super(TestLayer, self).__init__()

        go_through = [(100, 300), (370, 330), (430, 270), (750, 550)]

        # visually spot through where it should go
        for pos in go_through:
            sprite = Sprite('fire.png')
            sprite.position = pos
            sprite.scale = .3
            self.add(sprite)

        # calculate the points
        bezier_path = direct_bezier(*go_through)

        sprite = Sprite('fire.png')
        sprite.scale = .3
        sprite.color = (0, 0, 255)
        self.add(sprite, z=5)
        sprite.do(Bezier(bezier_path, 5))
Exemple #37
0
 def __init__(self, game, interface, meta):
     self.meta = meta
     self.game = game
     super().__init__(203, 207, 243, 255)
     toaster_sprite = Sprite('moneda.svg')
     toaster_sprite.scale = 0.5
     toaster_sprite.position = (director.get_window_size()[0] / 2,
                                director.get_window_size()[1] / 2)
     self.add(toaster_sprite)
     self.has_ran = False
     self.schedule_interval(self.run, 4)
 def _load_background(self):
     background = Sprite(self.gallery.content["display"]["city_hud"])
     self.optimal_scale=(self.config.window_width * self.display_pos_size["display_city_hud"]["W"]) / background.width
     background.image_anchor = 0, 0
     background.scale = self.optimal_scale
     background.x = self.config.window_width * self.display_pos_size["display_city_hud"]["X"]
     background.y = self.config.window_height * self.display_pos_size["display_city_hud"]["Y"]
     self.left_margin = background.x
     self.bottom_margin = background.y
     self.optimal_width = background.width
     self.optimal_height = background.height
     self.add(background)
Exemple #39
0
    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300, 1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
        else:
            self.position = random.randrange(700, 900), random.randrange(350, 450)
        self.is_enemy = is_enemy
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 150
        if not is_enemy:
            self.speed = 180
        self.path = [self.position] * 100

        self.schedule(self.update)
        if self.is_enemy:
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)
    def eat_apple(self):
        # create a new body and set the position to the previous last body partition
        new_snake_body = Sprite('resources\\resized_body.png')
        new_snake_body.position = self.body[-1].position
        new_snake_body.scale = 0.05
        # now, we can update the positions accordingly
        self.add(new_snake_body)
        self.body.append(new_snake_body)

        self.problem.new_problem()

        self.generate_apples()
        self.score += 10
Exemple #41
0
    def menu_xo(self):
        if not self.interact:
            background = Sprite(
                self.gallery.content["display"]["worldmap_hud_interact2"])
            background.image_anchor = 0, 0
            background.scale = self.optimal_scale
            background.x = 0
            background.y = 0
            self.add(background, name="display_worldmap_hud_interact")
            self.interact = True
            opt = {
                "0": {
                    "text": "Prospect for coal",
                    "param": "prospect"
                },
                "1": {
                    "text": "Deploy explosives",
                    "param": "mine"
                },
                "2": {
                    "text": "Discuss",
                    "param": "discuss_xo"
                },
                "3": {
                    "text": "That is all",
                    "param": "end"
                }
            }

            display_interact_box_self = DisplayInteractBox(
                opt, "1", self.optimal_width *
                self.button_positions["display_interact_box_self"]["X"],
                self.optimal_width *
                self.button_positions["display_interact_box_self"]["Y"],
                self.optimal_scale)
            self.add(display_interact_box_self,
                     name="display_interact_box_self")
            label_line_1 = self._load_label_gen("label_line_1")
            self.add(label_line_1, name="label_line_1")
            label_line_2 = self._load_label_gen("label_line_2")
            self.add(label_line_2, name="label_line_2")
            label_line_3 = self._load_label_gen("label_line_3")
            self.add(label_line_3, name="label_line_3")
            label_line_4 = self._load_label_gen("label_line_4")
            self.add(label_line_4, name="label_line_4")
            label_line_5 = self._load_label_gen("label_line_5")
            self.add(label_line_5, name="label_line_5")
            self.clear_text()
            self.get("label_line_1"
                     ).element.text = "Yes Conductor, how can I assist? "
Exemple #42
0
 def __init__(self, layer):
     super(Light, self).__init__()
     for c in layer.get_children():
         sp = Sprite(c.image)
         sp.source_position = c.position
         sp.position = c.position
         sp.scale = c.scale
         sp.source_scale = c.scale
         sp.rotation = c.rotation
         sp.opacity = c.opacity
         sp.dx = 0
         sp.dy = 0
         sp.dt = random.random()*3.15
         self.add( sp )
Exemple #43
0
 def display_wagon_info(self, wagon):
     try:
         self.remove("sprite_wagon_selected")
     except:
         A=1
     wagon_selected = Sprite(self.gallery.content["wagon"][self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].display_image+"_c"])
     wagon_selected.image_anchor = 0, 0
     wagon_selected.scale = self.optimal_scale*1.66
     wagon_selected.x = self.optimal_width * self.button_positions["sprite_wagon_selected"]["X"]
     wagon_selected.y = self.optimal_height * self.button_positions["sprite_wagon_selected"]["Y"]
     self.add(wagon_selected, name="sprite_wagon_selected")
     self.get("label_stores_1").element.text=self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].screen_name
     self.get("label_stores_2").element.text="Net weight: "+self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].net_weight+", Capacity: "+self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].capacity+str(self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].units)+self.config.conf_wagons[self.wagons_for_trade[wagon]["wagon_id"]].storage
     self.update_desc()
Exemple #44
0
    def __init__(self):
        super(SpriteLayer, self).__init__()

        sprite0 = Sprite('eleph2.png')
        sprite1 = Sprite('eleph1.png')
        sprite2 = Sprite('eleph0.png')

        sprite0.position = (600, 360)
        sprite1.position = (1180, 100)
        sprite2.position = (20, 100)

        sprite0.scale = .5
        sprite1.scale = .5
        sprite2.scale = .5

        self.add(sprite0)
        self.add(sprite1)
        self.add(sprite2)

        ju_right = JumpBy((600, 0), height=100, jumps=8, duration=5)
        ju_left = JumpBy((-600, 0), height=100, jumps=8, duration=5)
        rot1 = Rotate(180 * 4, duration=5)

        sprite0.opacity = 128

        sc = ScaleBy(9, 5)
        rot = Rotate(180, 5)

        sprite0.do(Repeat(sc + Reverse(sc)))
        sprite0.do(Repeat(rot + Reverse(rot)))
        sprite1.do(
            Repeat(ju_left + ju_left + Reverse(ju_left) + Reverse(ju_left)))
        sprite1.do(Repeat(Reverse(rot1) + Reverse(rot1) + rot1 + rot1))
        sprite2.do(
            Repeat(ju_right + ju_right + Reverse(ju_right) +
                   Reverse(ju_right)))
        sprite2.do(Repeat(rot1 + rot1 + Reverse(rot1) + Reverse(rot1)))
 def shootBullet(self):
     if gVariables.g_IS_FX:
         SFX(self.R._SFX[0])
     bullet = Sprite(self.R._BULLET[gVariables.g_PlayerIndex])
     bullet.position = (self.PLAYER.position[0] + bullet.width / 2,
                        self.PLAYER.position[1])
     bullet.cshape = CollisionModel.AARectShape(bullet.position,
                                                bullet.width / 2,
                                                bullet.height / 2)
     bullet.scale = 0.8
     bullet.velocity = (self.bullet_speed, 0)
     bullet.do(Move())
     self.bullet_Lists.add(bullet)
     self.collisionManager.add(bullet)
     self.batch.add(bullet, self.bulletZ)
 def add_line(self,p0,p1,color=(255,255,255)):
     step = int(fstep*scale)
     x0 , y0 = p0
     x1 , y1 = p1
     d = float(geom.dist(p0,p1))
     a = fstep
     sprites = []
     while a<d:
         b = Sprite('data/npoint.png', color=color)
         b.x = (a*x0 + (d-a)*x1)*scale/d + offset
         b.y = (a*y0 + (d-a)*y1)*scale/d + offset
         b.scale = 1.0/16.0
         self.add(b)
         sprites.append(b)
         a += fstep
     return sprites
    def _create_out_screenshot(self):
        # TODO: try to use `pyglet.image.get_buffer_manager().get_color_buffer()`
        #       instead of create a new BufferManager... note that pyglet uses
        #       a BufferManager singleton that fail when you change the window
        #       size.
        buffer = pyglet.image.BufferManager()
        image = buffer.get_color_buffer()

        width, height = director.window.width, director.window.height
        actual_width, actual_height = director.get_window_size()

        out = Sprite(image)
        out.position = actual_width // 2, actual_height // 2
        out.scale = max(actual_width / width, actual_height / height)

        return out
Exemple #48
0
    def check_queue(self, dt=0):
        width, height = cocos.director.director.get_window_size()

        if self.bkg:
            self.bkg.do(
                CallFunc(self.bkg.kill)
            )

        image = fetch_image()
        sprite = Sprite(image)

        end_scale = 1024.0 / image.width * self.scale

        sw = int((image.width * end_scale) / 2)
        sh = int((image.height * end_scale) / 2)

        if random.randint(0, 1):
            sprite.x = 0
        else:
            sprite.x = width

        sprite.y = random.randint(height * .25, height * .75)

        #dst = random.randint(width*.25, width*.75), height / 2
        dst = width / 2, height / 2

        sprite.scale = end_scale * 5
        sprite.opacity = 0
        sprite.do(
            spawn(
                FadeIn(1),
                AccelDeccel(
                    spawn(
                        ScaleTo(end_scale, duration=2),
                        MoveTo(dst, duration=2)))) +
            Delay(self.interval) +
            FadeOut(.5) +
            CallFunc(sprite.kill))

        self._z += 1
        self.add(sprite, z=self._z)
Exemple #49
0
 def on_shoot(self, tower):
     """
     when the tower shoots, add a shot sprite
     """
     shot_sprite = Sprite('shot.png')
     shot_sprite.scale = 0.5
     self.shots_layer.add(shot_sprite, z=30)
     
     ang_radians = math.radians(tower.angle)
     x = math.sin(ang_radians)
     y = math.cos(ang_radians)
     shot_sprite.position = (self.x + self.shot_position * x,
                              self.y + self.shot_position * y)
     
     shot_distance = tower.target_distance - self.shot_position
     dx = (shot_distance) * x
     dy = (shot_distance) * y
     
     def remove_shot(shot):
         self.shots_layer.remove(shot)
     
     t = shot_distance / self.shot_speed_px
     shot_sprite.do(MoveBy((dx, dy), t) +
                     CallFunc(remove_shot, shot_sprite))
Exemple #50
0
    def __init__(self):
        super( TestLayer, self ).__init__()

        x,y = director.get_window_size()

        sprite = Sprite('grossini.png')
        sprite.position = x//5, y//2
        self.add(sprite)

        sprite = Sprite('grossini.png')
        sprite.position = x*2//5, y//2
        sprite.scale_x = 0.5
        self.add(sprite)

        sprite = Sprite('grossini.png')
        sprite.position = x*3//5, y//2
        sprite.scale_y = 0.5
        self.add(sprite)

        sprite = Sprite('grossini.png')
        sprite.position = x*4//5, y//2
        sprite.scale_y = 0.5
        sprite.scale = 2.0
        self.add(sprite)
Exemple #51
0
    def __init__(self, battle_unit, is_friendly=True, reverse=False, mask_image=True, menu_selected=False):
        super(UnitCard, self).__init__()
        from board import Board

        self.battle_unit = battle_unit
        self.reverse = reverse
        self.width = 0
        self.height = 0

        self.unit_display = BatchNode()
        self.unit_display.position = 0, 0

        mech_img_grid = pyglet.image.ImageGrid(pyglet.resource.image(battle_unit.getImagePath()), 1, 6)
        mech_img_static = mech_img_grid[0]
        pitch = -(mech_img_static.width * len('RGBA'))
        img_data = mech_img_static.get_image_data()

        pyg_img = mech_img_static
        if mask_image:
            # masking only a portion of the image based on damage
            damage_height = int(mech_img_static.height)
            data = img_data.get_region(0, 0, mech_img_static.width, damage_height).get_data('RGBA', pitch)

            mask = Image.frombytes('RGBA', (mech_img_static.width, damage_height), data)
            # the first image is the color that the stamp will be
            img1 = Image.new('RGBA', mask.size, color=(0, 0, 0, 255))
            # second image is the background
            bg_color = (200, 75, 75, 200)
            if is_friendly:
                bg_color = (225, 225, 225, 200)
            img2 = Image.new('RGBA', mask.size, color=bg_color)
            img1 = img1.convert('RGBA')

            # apply mask to background image
            img = Image.composite(img1, img2, mask)

            raw_image = img.tobytes()
            img_x = mask.size[0]
            img_y = mask.size[1]
            pyg_img = pyglet.image.ImageData(img_x, img_y, 'RGBA', raw_image, pitch=-img_x * len('RGBA'))

        mech_sprite = Sprite(pyg_img)
        mech_sprite.position = mech_sprite.width // 2, Board.TILE_SIZE // 2 + mech_sprite.height // 2
        self.sprite = mech_sprite

        self.unit_display.add(mech_sprite)
        self.add(self.unit_display)

        # Show unit name above the image
        unit_name_str = "%it %s [%ipv]" % (battle_unit.getTonnage(), battle_unit.getName(), battle_unit.getPointValue())
        unit_name_font_size = Board.TILE_SIZE // 2
        if menu_selected:
            unit_name_font_size = int(unit_name_font_size * 1.5)

        if reverse:
            self.unit_name = floaters.TextFloater(unit_name_str, font_name='TranscendsGames',
                                                  font_size=unit_name_font_size, anchor_x='right', anchor_y='bottom')
            name_rect = mech_sprite.get_rect().topright
            self.unit_name.position = name_rect[0], name_rect[1]
        else:
            self.unit_name = floaters.TextFloater(unit_name_str, font_name='TranscendsGames',
                                                  font_size=unit_name_font_size, anchor_x='left', anchor_y='bottom')
            name_rect = mech_sprite.get_rect().topleft
            self.unit_name.position = name_rect[0], name_rect[1]

        self.add(self.unit_name)

        # Show unit variant below the image
        unit_variant_str = battle_unit.getVariant().upper()
        unit_variant_font_size = Board.TILE_SIZE // 3
        if menu_selected:
            unit_variant_font_size = int(unit_variant_font_size * 1.5)

        if reverse:
            self.unit_variant = floaters.TextFloater(unit_variant_str, font_name='TranscendsGames',
                                                     font_size=unit_variant_font_size, anchor_x='right', anchor_y='top')
            variant_rect = mech_sprite.get_rect().bottomright
            self.unit_variant.position = variant_rect[0], variant_rect[1] - 4
        else:
            self.unit_variant = floaters.TextFloater(unit_variant_str, font_name='TranscendsGames',
                                                     font_size=unit_variant_font_size, anchor_x='left', anchor_y='top')
            variant_rect = mech_sprite.get_rect().bottomleft
            self.unit_variant.position = variant_rect[0], variant_rect[1] - 4

        if menu_selected:
            # when selected in a menu the fonts are larger and needs more space away from the image stamp
            self.unit_variant.y -= unit_variant_font_size

        self.add(self.unit_variant)

        # Show armor, structure, heat stats next to the image (top)
        unit_stats = cocos.layer.Layer()
        stats_width = 0
        stats_height = 0

        # Show move and attack numbers next to the image (bottom)
        # values = "MV %i  ATK %i/%i/%i" % (battle_unit.getTurnMove(),
        #                                   battle_unit.short, battle_unit.medium, battle_unit.long)
        # self.unit_values = floaters.TextFloater(values, font_name='TranscendsGames',
        #                                         font_size=Board.TILE_SIZE // 4, anchor_x='left', anchor_y='bottom')
        # values_pos = mech_sprite.get_rect().bottomright
        # self.unit_values.position = 4 + values_pos[0], values_pos[1] - 2
        # self.add(self.unit_values)

        # create move icon and label of values
        move_icon = Sprite(Resources.move_icon_img)
        move_str = str(battle_unit.getTurnMove())

        unit_values_font_size = Board.TILE_SIZE // 3
        if menu_selected:
            unit_values_font_size = int(unit_values_font_size * 1.25)

        if reverse:
            move_icon.position = -move_icon.width // 2, stats_height + move_icon.height // 2

            move_label = floaters.TextFloater(move_str, font_name='TranscendsGames',
                                              font_size=unit_values_font_size, anchor_x='right', anchor_y='bottom')
            move_label.position = move_icon.get_rect().bottomleft
            unit_stats.add(move_label, z=2)
        else:
            move_icon.position = move_icon.width // 2, stats_height + move_icon.height // 2

            move_label = floaters.TextFloater(move_str, font_name='TranscendsGames',
                                              font_size=unit_values_font_size, anchor_x='left', anchor_y='bottom')
            move_label.position = move_icon.get_rect().bottomright
            unit_stats.add(move_label, z=2)

        unit_stats.add(move_icon, z=2)

        stats_height += move_icon.height

        # create attack icon and label of values
        attack_icon = Sprite(Resources.weapon_icon_img)
        attack_short = battle_unit.getDamageForRange('short')
        attack_medium = battle_unit.getDamageForRange('medium')
        attack_long = battle_unit.getDamageForRange('long')
        attack_str = "%i/%i/%i" % (attack_short, attack_medium, attack_long)

        if reverse:
            attack_icon.position = -attack_icon.width // 2, stats_height + attack_icon.height // 2

            attack_label = floaters.TextFloater(attack_str, font_name='TranscendsGames',
                                                font_size=unit_values_font_size, anchor_x='right', anchor_y='bottom')
            attack_label.position = attack_icon.get_rect().bottomleft
            unit_stats.add(attack_label, z=2)
        else:
            attack_icon.position = attack_icon.width // 2, stats_height + attack_icon.height // 2

            attack_label = floaters.TextFloater(attack_str, font_name='TranscendsGames',
                                                font_size=unit_values_font_size, anchor_x='left', anchor_y='bottom')
            attack_label.position = attack_icon.get_rect().bottomright
            unit_stats.add(attack_label, z=2)

        unit_stats.add(attack_icon, z=2)

        stats_height += attack_icon.height

        # create heat icon and bars
        heat_icon = Sprite(Resources.heat_icon_img)
        if reverse:
            heat_icon.position = -heat_icon.width // 2, stats_height + heat_icon.height // 2
        else:
            heat_icon.position = heat_icon.width // 2, stats_height + heat_icon.height // 2

        unit_stats.add(heat_icon, z=2)

        for i in range(battle_unit.heat):
            pip = Sprite(Resources.heat_pip_img)
            pip.scale = 2.0
            if reverse:
                pip.position = -heat_icon.width - (i * pip.width) - pip.width, stats_height + pip.height // 2
            else:
                pip.position = heat_icon.width + (i * pip.width) + pip.width // 2, stats_height + pip.height // 2

            unit_stats.add(pip, z=1)

            if pip.x + pip.width > stats_width:
                stats_width = pip.x + pip.width

        stats_height += heat_icon.height

        # create structure icon and bars
        structure_icon = Sprite(Resources.structure_icon_img)
        if reverse:
            structure_icon.position = -structure_icon.width // 2, stats_height + structure_icon.height // 2
        else:
            structure_icon.position = structure_icon.width // 2, stats_height + structure_icon.height // 2

        unit_stats.add(structure_icon, z=2)

        orig_structure = battle_unit.mech.structure
        for i in range(orig_structure):
            pip_img = Resources.structure_pip_img
            if i >= battle_unit.structure:
                pip_img = Resources.empty_pip_img

            pip = Sprite(pip_img)
            pip.scale = 2.0
            if reverse:
                pip.position = -structure_icon.width - (i * pip.width) - pip.width, stats_height + pip.height // 2
            else:
                pip.position = structure_icon.width + (i * pip.width) + pip.width // 2, stats_height + pip.height // 2

            unit_stats.add(pip, z=1)

            if pip.x + pip.width > stats_width:
                stats_width = pip.x + pip.width

        stats_height += structure_icon.height

        # create armor icon and bars
        armor_icon = Sprite(Resources.armor_icon_img)
        if reverse:
            armor_icon.position = -armor_icon.width // 2, stats_height + armor_icon.height // 2
        else:
            armor_icon.position = armor_icon.width // 2, stats_height + armor_icon.height // 2

        unit_stats.add(armor_icon, z=2)

        orig_armor = battle_unit.mech.armor
        for i in range(orig_armor):
            pip_img = Resources.armor_pip_img
            if i >= battle_unit.armor:
                pip_img = Resources.empty_pip_img

            pip = Sprite(pip_img)
            pip.scale = 2.0
            if reverse:
                pip.position = -armor_icon.width - (i * pip.width) - pip.width, stats_height + pip.height // 2
            else:
                pip.position = armor_icon.width + (i * pip.width) + pip.width // 2, stats_height + pip.height // 2

            unit_stats.add(pip, z=1)

            if pip.x + pip.width > stats_width:
                stats_width = pip.x + pip.width

        stats_height += armor_icon.height

        if reverse:
            stats_pos = mech_sprite.get_rect().topleft
            unit_stats.position = stats_pos[0] - 4, stats_pos[1] - stats_height

        else:
            stats_pos = mech_sprite.get_rect().topright
            unit_stats.position = 4 + stats_pos[0], stats_pos[1] - stats_height

        self.add(unit_stats)

        # calculate actual width and height of this element
        self.width = mech_sprite.width + stats_width
        self.height = mech_sprite.height + (3 * Board.TILE_SIZE // 2)
	def add_image_sprite(self):

		print("ImageLayer.add_image_layer()")

		pil = PIL.Image.open(self.image_file)
		pyglet_img = pyglet.image.load(self.image_file)
		target_w = self.window_width
		target_h = self.window_height
		orig_w = pil.size[0]
		orig_h = pil.size[1]

		id = self.next_id
		print(pil)

		( xscale, yscale,
		  result_w, result_h, dx, dy ) = SizeFitting.scaleToSize(
										 orig_w, orig_h,
				                         target_w, target_h,
		                                 FitType.ScaleFitAspectFit)
		imgsprite = Sprite(pyglet_img)
		imgsprite.anchor = (0, 0)
		imgsprite.transform_anchor = (result_w/2, result_h/2)

		bg_w = int(float(target_w) / xscale)
		bg_h = int(float(target_h) / yscale)

		background = SolidColorImagePattern(
			color=self.color_black
		).create_image(width=bg_w, height=bg_h)

		bgsprite = Sprite(background)
		bgsprite.add(imgsprite, z=id, name="image%d" % id)
		bgsprite.anchor = (0, 0)
		bgsprite.scale = xscale


		self.add(bgsprite, z=id, name="spritelayer%d" % id)


		self.animate(bgsprite, imgsprite)


		## !!! CENTERING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		self.position = (target_w/2, target_h/2)
		## Remove the lign below to center on display (as oppposed to anchoing at (0,0)
#		imgsprite.position = (-(target_w-result_w)/2/xscale, -(target_h-result_h)/2/yscale )

		## !!!!!!!!!!!!!!
		##############

		########## DEBUG
		bg = bgsprite
		lists = [ "orig_w result_w bg_w target_w xscale".split(" "),
		          "orig_h result_h bg_h target_h yscale".split(" "),
		          "bg.width bg.height bg.anchor bg.transform_anchor".split(" "),
		          "self.position self.get_local_transform() self.get_world_transform()".split(" ")
				]
		debug = "id: %2d " %id
		for list in lists:
			debug += "\n"
			for  key in list:
				debug += "{k:>5}: {v:>4}  ".format(k=key, v=eval(key))
		print debug
    def invoke(self, minion):
        mini = Sprite(load_animation("resources/" + minion + ".gif"), position = spawn_place[minion])
        mini.scale = minion_scale
        self.add(mini) 

        mini.do(MoveBy(minion_move_to[minion], minion_move_time) + CallFunc(mini.kill))
Exemple #54
0
def performAttackOnUnit(board, target_unit, overheat=0):
    # perform an attack on the given target BattleUnit
    battle = board.battle

    turn_unit = battle.getTurnUnit()
    if turn_unit is None or target_unit is None\
            or turn_unit.isDestroyed() or target_unit.isDestroyed():
        # TODO: make sure it is a player unit's turn
        return 0

    src_cell = turn_unit.col, turn_unit.row
    dest_cell = target_unit.col, target_unit.row

    # minimum travel time to target used to determine when to show the damage floater
    min_travel_time = 0
    # maximum travel time to target used to determine when all animations are finished
    max_travel_time = 0

    # cell distance used to determine which range of weapons will fire
    cell_distance = Battle.getCellDistance(src_cell, dest_cell)
    target_range = Battle.getDistanceRange(cell_distance)
    print(target_range + ": " + str(src_cell) + " -> " + str(dest_cell) + " = " + str(cell_distance))

    # perform the attack and show the results
    attack_results = battle.performAttack(turn_unit, target_unit, overheat=overheat)
    attack_damage = attack_results.attack_damage
    critical_type = attack_results.critical_type

    # determine actual target point based on the target unit sprite size
    target_sprite = target_unit.getSprite()
    real_x = (dest_cell[0] * Board.TILE_SIZE) + Board.TILE_SIZE // 2
    real_y = (dest_cell[1] * Board.TILE_SIZE) + (2 * target_sprite.get_height() // 3)

    # if missed, show a visible weapon miss
    if attack_damage == 0:
        real_x += random.choice([-1, 1]) * Board.TILE_SIZE
        real_y += random.choice([-1, 0, 1]) * Board.TILE_SIZE

    for weaponMap in turn_unit.mech.weapons:
        for weapon in weaponMap.iterkeys():

            if not weapon.inRange(cell_distance):
                continue

            weapon_data = weaponMap[weapon]

            # get sound channel to use just for this weapon
            weapon_channel = pygame.mixer.find_channel()
            if weapon_channel is None:
                weapon_channel = pygame.mixer.Channel(0)
            weapon_channel.set_volume(Settings.get_volume_fx())

            weapon_offset = weapon_data.get('offset', [0, 0])
            weapon_x = turn_unit.sprite.x + weapon_offset[0]
            weapon_y = turn_unit.sprite.y - (Board.TILE_SIZE // 2) + weapon_offset[1]

            weapon_color = weapon.get_color()

            if weapon.isPPC():
                # fire test ppcs
                ppc = Meteor()
                ppc.size = 10
                ppc.speed = 20
                ppc.gravity = Point2(0, 0)
                # TODO: offer decreased particle emission rate to improve performance
                ppc.emission_rate = 100
                ppc.life = 0.5
                ppc.life_var = 0.1

                ppc.position = weapon_x, weapon_y
                board.add(ppc, z=1000)

                target_x = real_x + random_offset()
                target_y = real_y + random_offset()
                target_pos = target_x, target_y

                # figure out the duration based on speed and distance
                ppc_speed = weapon.get_speed()  # pixels per second
                distance = Point2(ppc.x, ppc.y).distance(Point2(target_x, target_y))
                ppc_t = distance / ppc_speed

                ppc_sound = Resources.ppc_sound
                weapon_channel.play(ppc_sound)

                action = Delay(0.5) + MoveTo((target_x, target_y), duration=ppc_t) \
                         + CallFunc(impact_ppc, ppc) \
                         + Delay(0.5) + CallFunc(ppc.kill) \
                         + Delay(ppc_sound.get_length()) \
                         + CallFunc(weapon_channel.stop)

                ppc.do(action)

                travel_time = 0.5 + ppc_t
                if min_travel_time == 0 or min_travel_time > travel_time:
                    min_travel_time = travel_time

                if travel_time > max_travel_time:
                    max_travel_time = travel_time

            elif weapon.isFlamer():
                # fire test flamer
                flamer = Fire()

                flamer.size = 25
                flamer.speed = 300
                flamer.gravity = Point2(0, 0)
                # TODO: offer decreased particle emission rate to improve performance
                flamer.emission_rate = 100

                dx = real_x - weapon_x
                dy = real_y - weapon_y
                rads = atan2(-dy, dx)
                rads %= 2 * pi
                angle = degrees(rads) + 90

                flamer.rotation = angle
                flamer.angle_var = 5
                flamer.pos_var = Point2(5, 5)

                flamer.position = weapon_x, weapon_y
                board.add(flamer, z=1000)

                target_x = real_x + random_offset()
                target_y = real_y + random_offset()
                target_pos = target_x, target_y

                # figure out the duration based on speed and distance
                flamer_speed = weapon.get_speed()  # pixels per second
                distance = Point2(flamer.x, flamer.y).distance(Point2(target_x, target_y))
                flamer_t = 1

                flamer.life = distance / flamer_speed
                flamer.life_var = 0

                flamer_sound = Resources.flamer_sound
                weapon_channel.play(flamer_sound)

                action = Delay(flamer_t) \
                         + CallFunc(impact_flamer, flamer) \
                         + CallFunc(weapon_channel.fadeout, 750) \
                         + Delay(flamer_t) + CallFunc(flamer.kill) \
                         + CallFunc(weapon_channel.stop)

                flamer.do(action)

                travel_time = flamer_t
                if min_travel_time == 0 or min_travel_time > travel_time:
                    min_travel_time = travel_time

                if travel_time > max_travel_time:
                    max_travel_time = travel_time

            elif weapon.isLaser():
                # fire test laser
                las_life = 1.0
                las_size = (1, 1, 1)
                if weapon.isShort():
                    las_size = (2, 1, 0.5)
                    las_life = 0.5
                elif weapon.isMedium():
                    las_size = (3, 2, 1)
                    las_life = 0.75
                elif weapon.isLong():
                    las_size = (6, 4, 2)
                    las_life = 1.0

                target_x = real_x + random_offset()
                target_y = real_y + random_offset()
                target_pos = target_x, target_y

                las_outer = gl.SingleLine((weapon_x, weapon_y), (target_x, target_y),
                                          width=las_size[0],
                                          color=(weapon_color[0], weapon_color[1], weapon_color[2], 50))
                las_middle = gl.SingleLine((weapon_x, weapon_y), (target_x, target_y),
                                           width=las_size[1],
                                           color=(weapon_color[0], weapon_color[1], weapon_color[2], 125))
                las_inner = gl.SingleLine((weapon_x, weapon_y), (target_x, target_y),
                                          width=las_size[2],
                                          color=(weapon_color[0], weapon_color[1], weapon_color[2], 200))

                las_outer.visible = False
                las_middle.visible = False
                las_inner.visible = False

                node = cocos.layer.Layer()
                node.add(las_outer, z=1)
                node.add(las_middle, z=2)
                node.add(las_inner, z=3)
                board.add(node, z=1000)

                # give lasers a small particle pre-fire effect
                laser_charge = Galaxy()
                laser_charge.angle = 270
                laser_charge.angle_var = 180
                laser_charge.position = weapon_x, weapon_y
                laser_charge.size = 10
                laser_charge.size_var = 5
                laser_charge.emission_rate = 15
                laser_charge.life = 0.5
                laser_charge.speed = 0
                laser_charge.speed_var = 0
                laser_charge.start_color = Color(weapon_color[0] / 255, weapon_color[1] / 255, weapon_color[2] / 255,
                                                 1.0)
                laser_charge.end_color = Color(weapon_color[0] / 255, weapon_color[1] / 255, weapon_color[2] / 255, 1.0)
                node.add(laser_charge, z=0)

                laser_drift = random.uniform(-15.0, 15.0), random.uniform(-15.0, 15.0)

                las_action = Delay(0.5) + ToggleVisibility() \
                             + CallFunc(create_laser_impact, board, target_pos, laser_drift, las_life) \
                             + gl.LineDriftBy(laser_drift, las_life) \
                             + CallFunc(laser_charge.stop_system) + CallFunc(node.kill)
                las_outer.do(las_action)
                las_middle.do(las_action)
                las_inner.do(las_action)

                las_sound = Resources.las_sound
                weapon_channel.play(las_sound)
                las_duration_ms = int(las_action.duration * 1000)
                weapon_channel.fadeout(las_duration_ms)

                travel_time = 0.5
                if min_travel_time == 0 or min_travel_time > travel_time:
                    min_travel_time = travel_time

                if travel_time > max_travel_time:
                    max_travel_time = travel_time

            elif weapon.isBallistic():
                # fire test ballistic projectile
                num_ballistic = weapon.get_projectiles()

                if weapon.isGauss():
                    ballistic_img = Resources.gauss_img
                elif weapon.isLBX():
                    # LBX fires only one projectile, but will appear to have multiple random impacts
                    num_ballistic = 1
                    ballistic_img = Resources.buckshot_img
                else:
                    ballistic_img = Resources.ballistic_img

                # machine gun sound only plays once instead of per projectile
                cannon_sound = None
                if weapon.isMG():
                    cannon_sound = Resources.machinegun_sound
                elif weapon.isGauss():
                    cannon_sound = Resources.gauss_sound

                for i in range(num_ballistic):
                    ballistic = Sprite(ballistic_img)
                    ballistic.visible = False
                    ballistic.position = weapon_x, weapon_y
                    ballistic.scale = weapon.get_scale()
                    ballistic.anchor = 0, 0

                    dx = real_x - weapon_x
                    dy = real_y - weapon_y
                    rads = atan2(-dy, dx)
                    rads %= 2 * pi
                    angle = degrees(rads)

                    ballistic.rotation = angle

                    target_x = real_x + random_offset()
                    target_y = real_y + random_offset()
                    target_pos = target_x, target_y

                    # figure out the duration based on speed and distance
                    ballistic_speed = weapon.get_speed()  # pixels per second
                    distance = Point2(weapon_x, weapon_y).distance(Point2(target_x, target_y))
                    ballistic_t = distance / ballistic_speed

                    # setup the firing sound
                    if cannon_sound is None:
                        cannon_sound = Resources.cannon_sound

                    impact_func = create_ballistic_impact
                    if weapon.isLBX():
                        impact_func = create_lbx_impact

                    action = Delay(i * 0.1) + ToggleVisibility() \
                             + CallFunc(weapon_channel.play, cannon_sound) \
                             + MoveTo((target_x, target_y), ballistic_t) \
                             + CallFunc(impact_func, weapon, board, target_pos) \
                             + CallFunc(ballistic.kill)

                    if weapon.isGauss():
                        # give gauss sound a bit more time to stop
                        action += Delay(cannon_sound.get_length())

                    if i == num_ballistic - 1:
                        # stop the sound channel after the last projectile only
                        action += CallFunc(weapon_channel.stop)

                    ballistic.do(action)

                    board.add(ballistic, z=1000 + i)

                    travel_time = (i * 0.1) + ballistic_t
                    if min_travel_time == 0 or min_travel_time > travel_time:
                        min_travel_time = travel_time

                    if travel_time > max_travel_time:
                        max_travel_time = travel_time

            elif weapon.isMissile():
                # get another sound channel to use just for the explosions
                explosion_channel = pygame.mixer.find_channel()
                if explosion_channel is None:
                    explosion_channel = pygame.mixer.Channel(1)
                explosion_channel.set_volume(Settings.get_volume_fx())

                # fire test missile projectile
                missile_img = Resources.missile_img

                num_missile = weapon_data.get('count', 1)

                num_per_row = 1
                if weapon.isLRM():
                    num_per_row = 5
                elif weapon.isSRM():
                    num_per_row = 2

                for i in range(num_missile):

                    tube_x = i % num_per_row
                    tube_y = i // num_per_row

                    missile = Sprite(missile_img)
                    missile.visible = False
                    missile.position = weapon_x + tube_x, weapon_y + tube_y
                    missile.scale = weapon.get_scale()
                    missile.anchor = 0, 0

                    dx = real_x - weapon_x
                    dy = real_y - weapon_y
                    rads = atan2(-dy, dx)
                    rads %= 2 * pi
                    angle = degrees(rads)

                    missile.rotation = angle

                    target_x = real_x + random_offset()
                    target_y = real_y + random_offset()
                    target_pos = target_x, target_y

                    # figure out the duration based on speed and distance
                    missile_speed = weapon.get_speed()  # pixels per second
                    distance = Point2(weapon_x, weapon_y).distance(Point2(target_x, target_y))
                    missile_t = distance / missile_speed

                    rand_missile_sound = random.randint(0, 7)
                    missile_sound = Resources.missile_sounds[rand_missile_sound]

                    explosion_sound = Resources.impact_sound

                    action = Delay(i * 0.05) + ToggleVisibility() \
                             + CallFunc(weapon_channel.play, missile_sound) \
                             + MoveTo((target_x, target_y), missile_t) \
                             + CallFunc(create_missile_impact, board, target_pos) \
                             + CallFunc(missile.kill) \
                             + CallFunc(explosion_channel.play, explosion_sound) \
                             + Delay(0.5)

                    if i == num_missile - 1:
                        # stop the sound channels after the last missile only
                        action += CallFunc(weapon_channel.stop) + CallFunc(explosion_channel.stop)

                    missile.do(action)

                    board.add(missile, z=1000 + i)

                    travel_time = (i * 0.05) + missile_t
                    if min_travel_time == 0 or min_travel_time > travel_time:
                        min_travel_time = travel_time

                    if travel_time > max_travel_time:
                        max_travel_time = travel_time

    # scroll focus over to the target area halfway through the travel time
    target_area = Board.board_to_layer(target_unit.col, target_unit.row)

    # show damage floater after the travel time of the first projectile to hit
    floater_text = "%i" % attack_damage
    if attack_damage == 0:
        floater_text = "MISS"

    floater = floaters.TextFloater(floater_text)
    floater.visible = False
    floater.position = real_x, real_y + target_sprite.get_height() // 3
    board.add(floater, z=2000)

    action = Delay(min_travel_time / 2) + CallFunc(board.scroller.set_focus, *target_area) \
        + Delay(min_travel_time / 2) + ToggleVisibility() \
        + Delay(0.25) + MoveBy((0, Board.TILE_SIZE), 1.0) \
        + FadeOut(1.0) + CallFunc(floater.kill)
    floater.do(action)

    if critical_type is not None:
        crit_floater = floaters.TextFloater(critical_type)
        crit_floater.visible = False

        crit_floater.position = real_x, real_y + target_sprite.get_height() // 3
        board.add(crit_floater, z=2000)

        action = Delay(min_travel_time) + Delay(1.0) + ToggleVisibility() \
                 + Delay(0.25) + MoveBy((0, Board.TILE_SIZE), 1.5) \
                 + FadeOut(1.5) + CallFunc(crit_floater.kill)
        crit_floater.do(action)

    if action.duration > max_travel_time:
        max_travel_time = action.duration

    stats_action = Delay(min_travel_time) + CallFunc(target_sprite.updateStatsIndicators) \
                   + CallFunc(Interface.UI.updateTargetUnitStats, target_unit)
    target_sprite.do(stats_action)

    if target_unit.structure > 0:
        print("Remaining %i/%i" % (target_unit.armor, target_unit.structure))

    else:
        print("Target destroyed!")
        # show destroyed floater after the travel time of the first projectile to hit
        destroyed = floaters.TextFloater("DESTROYED")
        destroyed.visible = False
        destroyed.position = real_x, real_y + target_sprite.get_height() // 3
        board.add(destroyed, z=5000)

        action = Delay(max_travel_time) + ToggleVisibility() \
            + (MoveBy((0, Board.TILE_SIZE), 1.0) | CallFunc(create_destruction_explosions, board, target_unit)) \
            + Delay(0.5) + CallFunc(target_sprite.destroy) + FadeOut(2.0) + CallFunc(destroyed.kill)
        destroyed.do(action)

        # give a bit of extra time to explode
        max_travel_time = action.duration

    return max_travel_time