Пример #1
0
    def levy(self):
        char = Char(self.char_id).mc

        if self.counter.remained_value <= 0:
            if char.vip < VIP_MAX_LEVEL:
                raise SanguoException(
                    errormsg.LEVY_NO_TIMES, self.char_id, "Levy",
                    "no times. but can get additional times by increase vip level. current: {0}, max: {1}"
                    .format(char.vip, VIP_MAX_LEVEL))
            raise SanguoException(
                errormsg.LEVY_NO_TIMES_FINAL, self.char_id, "Levy",
                "no times. vip reach the max level {0}".format(VIP_MAX_LEVEL))

        resource = Resource(self.char_id, "Levy")
        cost_cyess = self.get_cost_sycee()

        with resource.check(sycee=-cost_cyess):
            drop = self.get_levy_drop()

            self.counter.incr()
            standard_drop = resource.add(**drop)

        t = Task(self.char_id)
        t.trig(4)

        self.send_notify()
        return standard_drop
Пример #2
0
    def equip_embed(self, _id, slot_id, gem_id):
        # gem_id = 0 表示取下slot_id对应的宝石
        if not self.has_equip(_id):
            raise SanguoException(errormsg.EQUIPMENT_NOT_EXIST, self.char_id,
                                  "Equipment Embed Gem",
                                  "Equipment {0} NOT exist".format(_id))

        if gem_id and not self.has_gem(gem_id):
            raise SanguoException(errormsg.GEM_NOT_EXIST, self.char_id,
                                  "Equipment Embed Gem",
                                  "Gem {0} NOT exist".format(gem_id))

        slot_index = slot_id - 1

        e = Equipment(self.char_id, _id, self.item)
        if gem_id:
            off_gem = e.add_gem(slot_index, gem_id)
            self.gem_remove(gem_id, 1)
            if off_gem:
                self.gem_add([(off_gem, 1)])
        else:
            off_gem = e.rem_gem(slot_index)
            self.gem_add([(off_gem, 1)])

        self.item.save()
Пример #3
0
    def apply_union(self, union_id):
        # 申请加入工会
        from core.union.union import Union, UnionList

        doc = MongoUnion._get_collection().find_one({'_id': union_id},
                                                    {'owner': 1})

        if not doc:
            raise SanguoException(errormsg.UNION_NOT_EXIST, self.char_id,
                                  "Member Apply Union",
                                  "union {0} not exist".format(union_id))

        if self.mongo_union_member.joined:
            raise SanguoException(
                errormsg.UNION_CANNOT_APPLY_ALREADY_IN, self.char_id,
                "Member Apply Union",
                "already in {0}".format(self.mongo_union_member.joined))

        if len(self.mongo_union_member.applied) >= 10:
            raise SanguoException(errormsg.UNION_CANNOT_APPLY_FULL,
                                  self.char_id, "Member Apply Union",
                                  "apply list too long")

        if union_id not in self.mongo_union_member.applied:
            self.mongo_union_member.applied.append(union_id)
            self.mongo_union_member.save()

            Union(doc['owner']).send_apply_list_notify()

        UnionList.send_list_notify(self.char_id)
Пример #4
0
    def evolution(self, horse_id, horse_soul_id):
        from core.item import Item

        try:
            h = self.mongo_horse.horses[str(horse_id)]
        except KeyError:
            raise SanguoException(errormsg.HORSE_NOT_EXIST, self.char_id,
                                  "Hero Evolution",
                                  "horse {0} not exist".format(horse_id))

        item = Item(self.char_id)
        if not item.has_stuff(horse_soul_id):
            raise SanguoException(
                errormsg.STUFF_NOT_EXIST, self.char_id, "Hero Evolution",
                "horse soul {0} not exist".format(horse_soul_id))

        stuff = STUFFS[horse_soul_id]
        if stuff.tp != 4:
            raise SanguoException(
                errormsg.INVALID_OPERATE, self.char_id, "Hero Evolution",
                "stuff {0} tp {1} != 4".format(horse_soul_id, stuff.tp))

        if stuff.value not in HORSE:
            raise SanguoException(
                errormsg.INVALID_OPERATE, self.char_id, "Hero Evolution",
                "stuff value not in HORSE".format(stuff.value))

        item.stuff_remove(horse_soul_id, 1)

        h.oid = stuff.value
        self.mongo_horse.save()
        self.send_update_notify(horse_id, h)
Пример #5
0
    def battle(self):
        need_sycee = 0

        counter = Counter(self.char_id, 'arena')
        if counter.remained_value <= 0:
            counter = Counter(self.char_id, 'arena_buy')
            if counter.remained_value <= 0:
                char = Char(self.char_id).mc
                if char.vip < VIP_MAX_LEVEL:
                    raise SanguoException(
                        errormsg.ARENA_NO_TIMES, self.char_id, "Arena Battle",
                        "arena no times. vip current: {0}, max {1}".format(
                            char.vip, VIP_MAX_LEVEL))
                raise SanguoException(
                    errormsg.ARENA_NO_TIMES_FINAL, self.char_id,
                    "Arena Battle",
                    "arena no times. vip reach max level {0}".format(
                        VIP_MAX_LEVEL))
            else:
                need_sycee = ARENA_COST_SYCEE

        rival_id = self.choose_rival()
        if not rival_id:
            raise SanguoException(errormsg.ARENA_NO_RIVAL, self.char_id,
                                  "Arena Battle", "no rival.")

        if need_sycee:
            resource = Resource(self.char_id, "Arena Battle",
                                "battle for no free times")
            resource.check_and_remove(sycee=-need_sycee)

        counter.incr()

        # set battle cd
        redis_client.setex(REDIS_ARENA_BATTLE_CD_KEY(rival_id), 1, ARENA_CD)

        msg = protomsg.Battle()
        b = PVP(self.char_id, rival_id, msg)
        b.start()

        if msg.self_win:
            achievement = Achievement(self.char_id)
            achievement.trig(11, 1)

        self_score = self.score
        rival_arena = Arena(rival_id)
        rival_score = rival_arena.score

        new_score = calculate_score(self_score, rival_score, msg.self_win)
        self.set_score(new_score)

        t = Task(self.char_id)
        t.trig(2)

        self.send_notify(score=new_score)

        rival_arena.be_beaten(rival_score, self_score, not msg.self_win,
                              self.char_id)

        return msg
Пример #6
0
    def plunder(self):
        if not self.mongo_plunder.char_id:
            raise SanguoException(errormsg.PLUNDER_NO_RIVAL, self.char_id,
                                  "Plunder Battle", "no rival target")

        if self.mongo_plunder.current_times <= 0:
            raise SanguoException(errormsg.PLUNDER_NO_TIMES, self.char_id,
                                  "Plunder Battle", "no times")

        self.change_current_plunder_times(change_value=-1)

        rival_battle_heros = dill.loads(
            base64.b64decode(self.mongo_plunder.battle_heros))

        msg = MsgBattle()
        pvp = PlunderBattle(
            self.char_id,
            self.mongo_plunder.char_id,
            msg,
            self.mongo_plunder.char_name,
            rival_battle_heros,
        )
        pvp.start()

        t = Task(self.char_id)
        t.trig(3)

        to_char_id = self.mongo_plunder.char_id
        target_server_url = self.mongo_plunder.server_url

        if msg.self_win:
            standard_drop = self._get_plunder_reward(
                self.mongo_plunder.char_city_id, self.mongo_plunder.char_gold,
                self.mongo_plunder.char_hero_original_ids)

            self.clean_plunder_target()

            achievement = Achievement(self.char_id)
            achievement.trig(12, 1)

            PlunderLeaderboardWeekly.incr(self.char_id)
            TimesLogPlunder(self.char_id).inc()
        else:
            standard_drop = make_standard_drop_from_template()

        self.mongo_plunder.plunder_times += 1
        self.mongo_plunder.save()
        self.send_notify()

        plunder_finished_signal.send(
            sender=None,
            from_char_id=self.char_id,
            from_char_name=Char(self.char_id).mc.name,
            to_char_id=to_char_id,
            from_win=msg.self_win,
            standard_drop=standard_drop,
            target_server_url=target_server_url,
        )

        return (msg, standard_drop)
Пример #7
0
    def get_reward(self, vip):
        if vip > self.mc.vip:
            raise SanguoException(
                errormsg.VIP_LEVEL_NOT_ENOUGH,
                self.char_id,
                "VIP GET REWARD",
                "vip not enough. {0} < {1}".format(self.mc.vip, vip)
            )

        vips = self.can_reward_vips()
        if vip not in vips:
            raise SanguoException(
                errormsg.VIP_HAS_GOT_REWARD,
                self.char_id,
                "VIP GET REWARD",
                "vip {0} has got reward".format(vip)
            )

        # send reward
        prepare_drop = get_drop([VIP_REWARD[vip].package])
        resource = Resource(self.char_id, "VIP GET REWARD", "vip {0}".format(vip))
        standard_drop = resource.add(**prepare_drop)

        self.mc.vip_has_reward.append(vip)
        self.mc.save()
        self.send_notify()

        return standard_drop_to_attachment_protomsg(standard_drop)
Пример #8
0
    def levy(self):
        char = Char(self.char_id).mc

        if self.counter.remained_value <= 0:
            if char.vip < VIP_MAX_LEVEL:
                raise SanguoException(
                    errormsg.LEVY_NO_TIMES, self.char_id, "Levy",
                    "no times. but can get additional times by increase vip level. current: {0}, max: {1}"
                    .format(char.vip, VIP_MAX_LEVEL))
            raise SanguoException(
                errormsg.LEVY_NO_TIMES_FINAL, self.char_id, "Levy",
                "no times. vip reach the max level {0}".format(VIP_MAX_LEVEL))

        resource = Resource(self.char_id, "Levy")
        cost_cyess = self.get_cost_sycee()

        with resource.check(sycee=-cost_cyess):
            got_gold = LEVY_GOT_GOLD_FUNCTION(char.level)
            prob = random.randint(1, 100)
            for k, v in LEVY_CRIT_PROB_TABLE:
                if prob <= k:
                    break

            got_gold *= v

            self.counter.incr()
            resource.add(gold=got_gold)

        self.send_notify()
Пример #9
0
        def _up():
            if self.level >= EQUIP_MAX_LEVEL:
                raise SanguoException(
                    errormsg.EQUIPMENT_REACH_MAX_LEVEL, self.char_id,
                    "Equipment Level Up",
                    "Equipment {0} has already touch max level {1}".format(
                        self.equip.id, EQUIP_MAX_LEVEL))

            if self.level >= char_level:
                raise SanguoException(
                    errormsg.EQUIPMENT_REACH_CHAR_LEVEL, self.char_id,
                    "Equipment Level Up",
                    "Equipment {0} level {1} >= char level {2}".format(
                        self.equip.id, self.level, char_level))

            gold_needs = self.level_up_need_gold()
            if cache_char.gold < gold_needs:
                raise SanguoException(errormsg.GOLD_NOT_ENOUGH, self.char_id,
                                      "Equipment Level Up", "Gold Not Enough")

            cache_char.gold -= gold_needs

            prob = random.randint(1, 100)
            for p, l in LEVEL_UP_PROBS:
                if prob <= p:
                    actual_level_up = l
                    break

            self.mongo_item.equipments[str(
                self.equip_id)].level += actual_level_up
            self.level += actual_level_up
            return gold_needs
Пример #10
0
    def equip_sell(self, ids):
        if not isinstance(ids, (set, list, tuple)):
            ids = [ids]

        f = Formation(self.char_id)
        ids = set(ids)
        for _id in ids:
            if not self.has_equip(_id):
                raise SanguoException(
                    errormsg.EQUIPMENT_NOT_EXIST,
                    self.char_id,
                    "Equipment Sell",
                    "Equipment {0} NOT exist".format(_id)
                )

            if f.find_socket_by_equip(_id):
                raise SanguoException(
                    errormsg.EQUIPMENT_CANNOT_SELL_FORMATION,
                    self.char_id,
                    "Equipment Sell",
                    "Equipment {0} in Formation, Can not sell".format(_id)
                )

        gold = 0
        for _id in ids:
            e = Equipment(self.char_id, _id, self.item)
            gold += e.sell_gold()

        resource = Resource(self.char_id, "Equipment Sell", "equipments {0}".format(ids))
        resource.check_and_remove(equipments=list(ids))
        resource.add(gold=gold)
Пример #11
0
    def get_plunder_times(self, sender_id):
        if sender_id not in self.mf.plunder_senders:
            raise SanguoException(
                errormsg.FRIEND_GET_PLUNDER_TIMES_NOT_EXIST, self.char_id,
                "Friend Get Plunder Times",
                "{0} try to get plunder times, buy {1} not give".format(
                    self.char_id, sender_id))

        if sender_id in self.mf.plunder_gots:
            raise SanguoException(
                errormsg.FRIEND_GET_PLUNDER_TIMES_ALREADY_GOT, self.char_id,
                "Friend Get Plunder Times",
                "{0} try to get plunder times, buy already got from {1}".
                format(self.char_id, sender_id))

        if len(self.mf.plunder_gots) >= self.max_amount:
            raise SanguoException(
                errormsg.PLUNDER_GET_TIMES_FULL, self.char_id,
                "Friend Get Plunder Times",
                "{0} try to get plunder times, buy already reach max friends amount"
                .format(self.char_id))

        self.mf.plunder_senders.remove(sender_id)
        self.mf.plunder_gots.append(sender_id)
        self.mf.save()

        p = Plunder(self.char_id)
        p.change_current_plunder_times(change_value=1, allow_overflow=True)

        self.send_update_friend_notify(sender_id)
Пример #12
0
    def start(self, boss_id):
        try:
            boss = UNION_BOSS[boss_id]
        except KeyError:
            raise SanguoException(
                errormsg.INVALID_OPERATE,
                self.char_id,
                "UnionBoss Start",
                "boss {0} not exist".format(boss_id)
            )

        if not self.union.belong_to_self:
            raise SanguoException(
                errormsg.INVALID_OPERATE,
                self.char_id,
                "UnionBoss Start",
                "{0} not union owner".format(self.char_id)
            )

        if self.union.mongo_union.level < boss.union_level:
            raise SanguoException(
                errormsg.UNION_BOSS_LEVEL_NOT_ENOUGH,
                self.char_id,
                "UnionBoss Start",
                "union level not enough. {0} < {1}".format(self.union.mongo_union.level, boss.union_level)
            )

        meb = MongoEmbeddedUnionBoss()
        meb.start_at = arrow.utcnow().timestamp
        meb.hp = boss.hp
        meb.killer = 0
        meb.logs = []

        self.mongo_boss.opened[str(boss_id)] = meb
        self.mongo_boss.save()
Пример #13
0
    def create(self,name):
        if len(name) > UNION_NAME_MAX_LENGTH:
            raise SanguoException(
                    errormsg.UNION_NAME_TOO_LONG,
                    self.char_id,
                    "Union Create",
                    "name too long: {0}".format(name.encode('utf-8'))
                    )


        if MongoUnion.objects.filter(name=name).count() > 0:
            raise SanguoException(
                    errormsg.UNION_NAME_ALREADY_EXIST,
                    self.char_id,
                    "Union Create",
                    "name already exist: {0}".format(name.encode('utf-8'))
                    )


        resource = Resource(self.char_id, "Union Create")

        with resource.check(sycee=-UNION_CREATE_NEEDS_SYCEE):
            new_id = id_generator('union')[0]
            mu = MongoUnion(id=new_id)
            mu.owner = self.char_id
            mu.name = name
            mu.bulletin = UNION_DEFAULT_DES
            mu.level = 1
            mu.contribute_points = 0
            mu.save()
            UnionMember(self.char_id).join_union(new_id)

        Union(self.char_id, new_id).send_notify()
        UnionBattle(self.char_id).send_notify()
Пример #14
0
    def get_reward(self, char_id, condition_id):
        key = self.make_key(condition_id)
        try:
            doc = MongoActivityEnabledCondition.objects.get(id=key)
        except DoesNotExist:
            raise SanguoException(
                errormsg.ACTIVITY_CAN_NOT_GET_REWARD,
                char_id,
                "Activity Get Reward",
                "condition {0} can not get".format(condition_id)
            )

        if doc.value == 1:
            raise SanguoException(
                errormsg.ACTIVITY_ALREADY_GOT_REWARD,
                char_id,
                "Activity Get Reward",
                "condition {0} already got".format(condition_id)
            )

        doc.value = 1
        doc.save()

        standard_drop = get_drop([ACTIVITY_STATIC_CONDITIONS[condition_id].package])
        resource = Resource(char_id, "Activity Get Reward", "get condition id {0}".format(condition_id))
        standard_drop = resource.add(**standard_drop)

        return standard_drop_to_attachment_protomsg(standard_drop)
Пример #15
0
    def start_battle(self):
        if not self.union.belong_to_self:
            raise SanguoException(
                errormsg.INVALID_OPERATE,
                self.char_id,
                "UnionBattle Start",
                "no permission"
            )


        rival_union = self.find_rival()
        if not rival_union:
            raise SanguoException(
                errormsg.UNION_BATTLE_NO_RIVAL,
                self.char_id,
                "UnionBattle Start",
                "no rival"
            )

        record = UnionBattleRecord(self.union.char_id, self.union.union_id, rival_union.owner, rival_union.id)
        record.start()
        msg = record.save()

        self.send_notify()

        if msg.win:
            self.after_battle_win()
        else:
            self.after_battle_lose()

        return msg
Пример #16
0
    def reset_one(self, _id):
        str_id = str(_id)
        if str_id not in self.stage.elites:
            raise SanguoException(
                errormsg.STAGE_ELITE_NOT_OPEN,
                self.char_id,
                "Elite Reset One",
                "reset a not opened stage {0}".format(_id)
            )

        reset_times = self.stage.elites_buy.get(str(_id), 0)
        char = Char(self.char_id).mc
        can_reset_times = VIP_FUNCTION[char.vip].stage_elite_buy
        if reset_times >= can_reset_times:
            raise SanguoException(
                errormsg.STAGE_ELITE_RESET_FULL,
                self.char_id,
                "Elite Reset One",
                "reset {0}".format(_id)
            )

        cost = self.get_reset_cost(_id)

        resource = Resource(self.char_id, "Elite Reset One", "reset {0}".format(_id))
        with resource.check(sycee=-cost):
            self.stage.elites[str(_id)] = 0
            self.stage.elites_buy[str(_id)] = reset_times + 1
            self.stage.save()

        self.send_update_notify(_id)
Пример #17
0
def activatecode_use(request):
    char_id = request._char_id
    code_id = request._proto.code_id

    data = {'char_id': char_id, 'code_id': code_id}

    try:
        res = api_activatecode_use(data)
    except APIFailure:
        raise SanguoException(errormsg.SERVER_FAULT, char_id,
                              "ActivateCode Use",
                              "APIFailure. api_activatecode_use")

    if res['ret'] != 0:
        raise SanguoException(
            res['ret'], char_id, "ActivateCode use",
            "api_activatecode_use ret = {0}".format(res['ret']))

    # DONE
    package = res['data']['package']
    drop = get_drop_from_raw_package(package)

    mail = Mail(char_id)
    mail.add(ACTIVATECODE_MAIL_TITLE,
             ACTIVATECODE_MAIL_CONTENT,
             arrow.utcnow().format('YYYY-MM-DD HH:mm:ss'),
             attachment=json.dumps(drop))

    return None
Пример #18
0
    def get_reward(self):
        counter = Counter(self.char_id, 'official_reward')
        if counter.remained_value <= 0:
            raise SanguoException(
                errormsg.OFFICAL_ALREADY_GET_REWARD,
                self.char_id,
                "OfficialDailyReward Get Reward",
                "already got"
            )


        char = Char(self.char_id)
        official_level = char.mc.official
        if official_level == 0:
            raise SanguoException(
                errormsg.OFFICAL_ZERO_GET_REWARD,
                self.char_id,
                "OfficialDailyReward Get Reward",
                "char official level = 0"
            )

        counter = Counter(self.char_id, 'official_reward')
        counter.incr()

        gold = OFFICIAL[official_level].gold

        resource = Resource(self.char_id, "Daily Official", 'official reward')
        standard_drop = resource.add(gold=gold)
        return standard_drop_to_attachment_protomsg(standard_drop)
Пример #19
0
def break_hero(char_id, _id):
    # 主动将武将转为卡魂
    try:
        h = char_heros_dict(char_id)[_id]
    except KeyError:
        raise SanguoException(errormsg.HERO_NOT_EXSIT, char_id, "Hero Break",
                              "hero {0} not exist".format(_id))

    formation = Formation(char_id)
    if _id in formation.in_formation_hero_ids():
        raise SanguoException(
            errormsg.HERO_CANNOT_BREAK_IN_FORMATION, char_id, "Hero Break",
            "hero {0} in formation, cannot break".format(_id))

    oid = h.oid
    quality = HEROS[oid].quality
    souls_amount = SAVE_HERO_TO_SOUL_TABLE[quality]

    MongoHero.objects.get(id=_id).delete()

    hero_del_signal.send(sender=None,
                         char_id=char_id,
                         hero_id=_id,
                         hero_oid=oid)

    HeroSoul(char_id).add_soul([(oid, souls_amount)])
Пример #20
0
    def start_hang(self, city_id, get_reward=True):
        if city_id not in BATTLES:
            raise SanguoException(
                errormsg.INVALID_OPERATE, self.char_id, "Start Hang",
                "hang at none exist city id {0}".format(city_id))

        if city_id not in self.mongo_affairs.opened:
            raise SanguoException(errormsg.INVALID_OPERATE, self.char_id,
                                  "Start Hang",
                                  "city id {0} not opened".format(city_id))

        if get_reward:
            if self.mongo_affairs.hang_city_id:
                # 上次有挂机,先结算
                drop_msg = self.get_hang_reward(auto_start=False)
            else:
                drop_msg = None
        else:
            drop_msg = None

        self.mongo_affairs.hang_city_id = city_id
        self.mongo_affairs.hang_start_at = arrow.utcnow().timestamp
        self.mongo_affairs.logs = []
        self.mongo_affairs.save()

        self.send_hang_notify()
        return drop_msg
Пример #21
0
    def up_horse(self, socket_id, horse_id):
        # 上马
        from core.horse import Horse

        try:
            this_socket = self.formation.sockets[str(socket_id)]
        except KeyError:
            raise SanguoException(errormsg.FORMATION_NONE_EXIST_SOCKET,
                                  self.char_id, "Formation Up Horse",
                                  "Socket {0} not exist".format(socket_id))

        horse = Horse(self.char_id)
        if not horse.has_horse(horse_id):
            raise SanguoException(
                errormsg.HORSE_NOT_EXIST, self.char_id, "formation Up Horse",
                "horse, {0} not belong to self".format(horse_id))

        changed_socket = []
        this_socket.horse = horse_id

        for k, v in self.formation.sockets.iteritems():
            if int(k) == socket_id:
                continue

            if v.horse == horse_id:
                v.horse = 0
                changed_socket.append((int(k), v))
                break

        changed_socket.append((socket_id, this_socket))
        self.formation.save()

        for k, v in changed_socket:
            self.send_socket_changed_notify(k, v)
Пример #22
0
    def battle(self, _id):
        try:
            self.this_stage = STAGE_ACTIVITY[_id]
        except KeyError:
            raise SanguoException(errormsg.STAGE_ACTIVITY_NOT_EXIST,
                                  self.char_id, "StageActivity Battle",
                                  "StageActivity {0} not exist".format(_id))

        if _id not in self.stage.activities:
            raise SanguoException(errormsg.STAGE_ACTIVITY_NOT_OPEN,
                                  self.char_id, "StageActivity Battle",
                                  "StageActivity {0} not open".format(_id))

        counter = ActivityStageCount(self.char_id)
        counter.make_func_name(self.this_stage.tp)

        if counter.remained_value <= 0:
            raise SanguoException(
                errormsg.STAGE_ACTIVITY_TOTAL_NO_TIMES, self.char_id,
                "StageActivity Battle",
                "StageActivity no total times. battle {0}".format(_id))

        battle_msg = protomsg.Battle()
        b = ActivityPVE(self.char_id, _id, battle_msg)
        b.start()

        if battle_msg.self_win:
            counter.incr()
            self.send_remained_times_notify()

            Task(self.char_id).trig(9)

        return battle_msg
Пример #23
0
    def plunder(self, _id):
        if str(_id) not in self.mongo_plunder.chars:
            raise SanguoException(
                errormsg.PLUNDER_NOT_IN_LIST, self.char_id, "Plunder Plunder",
                "Plunder, {0} not in plunder list".format(_id))

        counter = Counter(self.char_id, 'plunder')
        if counter.remained_value <= 0:
            char = Char(self.char_id).mc
            if char.vip < VIP_MAX_LEVEL:
                raise SanguoException(
                    errormsg.PLUNDER_NO_TIMES, self.char_id, "Plunder Battle",
                    "Plunder no times. vip current: {0}, max: {1}".format(
                        char.vip, VIP_MAX_LEVEL))
            raise SanguoException(
                errormsg.PLUNDER_NO_TIMES_FINAL, self.char_id,
                "Plunder Battle",
                "Plunder no times. vip reach max level {0}".format(
                    VIP_MAX_LEVEL))

        msg = MsgBattle()
        pvp = PVP(self.char_id, _id, msg)
        pvp.start()

        if not self.mongo_plunder.chars[str(_id)].is_robot:
            char = Char(self.char_id)
            h = Hang(_id)
            h.plundered(char.cacheobj.name, not msg.self_win)

        t = Task(self.char_id)
        t.trig(3)

        ground_win_times = 0
        if msg.first_ground.self_win:
            ground_win_times += 1
        if msg.second_ground.self_win:
            ground_win_times += 1
        if msg.third_ground.self_win:
            ground_win_times += 1

        got_point = PLUNDER_POINT.get(ground_win_times, 0)
        if got_point:
            self.mongo_plunder.points += got_point

        if msg.self_win:
            counter.incr()
            self.mongo_plunder.target_char = _id

            drop_official_exp = PLUNDER_GET_OFFICIAL_EXP_WHEN_WIN
            drop_gold = PLUNDER_DEFENSE_FAILURE_GOLD

            resource = Resource(self.char_id, "Plunder")
            resource.add(gold=drop_gold, official_exp=drop_official_exp)
        else:
            self.mongo_plunder.target_char = 0

        self.mongo_plunder.got_reward = []
        self.mongo_plunder.save()
        self.send_notify()
        return msg
Пример #24
0
    def get_attachment(self, mail_id):
        if str(mail_id) not in self.mail.mails:
            raise SanguoException(
                errormsg.MAIL_NOT_EXIST,
                self.char_id,
                "Mail Get Attachment",
                "mail {0} not exist".format(mail_id)
            )

        if not self.mail.mails[str(mail_id)].attachment:
            raise SanguoException(
                errormsg.MAIL_HAS_NO_ATTACHMENT,
                self.char_id,
                "Mail Get Attachment",
                "mail {0} has no attachment".format(mail_id)
            )

        resource = Resource(self.char_id, "Mail Attachment")
        attachment = json.loads(self.mail.mails[str(mail_id)].attachment)
        resource.add(**attachment)

        self.mail.mails[str(mail_id)].attachment = ''
        self.mail.mails[str(mail_id)].has_read = True
        self.mail.save()
        self.send_mail_notify()
Пример #25
0
def login(request):
    req = request._proto

    try:
        account_data = make_account_dict_from_message(req.login)
    except Exception as e:
        raise SanguoException(errormsg.BAD_MESSAGE, 0, 'Login', e.args[0])

    account_data['server_id'] = server.id

    try:
        res = api_account_login(data=account_data)
    except APIFailure:
        raise SanguoException(errormsg.SERVER_FAULT, 0, 'Login',
                              'APIFailure. api_account_login')

    if res['ret'] != 0:
        raise SanguoException(
            res['ret'], 0, 'Login',
            'login, api_account_login, ret = {0}'.format(res['ret']))

    account_id = res['data']['account_id']
    char_id = res['data']['char_id']
    new_token = res['data']['new_token']

    request._account_id = account_id
    request._server_id = server.id

    login_signal.send(
        sender=None,
        char_id=char_id,
        real_login=True,
    )

    if char_id:
        request._char_id = char_id
    else:
        request._char_id = None

    session = GameSession(request._account_id, request._server_id,
                          request._char_id)

    if char_id:
        Player(char_id).set_login_id(session.login_id)

    request._game_session = session
    session = crypto.encrypt(session_dumps(session))

    response = StartGameResponse()
    response.ret = 0

    response.login.MergeFrom(make_login_response_msg(req.login, new_token))
    response.need_create_new_char = char_id == 0

    sync = SyncResponse()
    sync.ret = 0
    sync.utc_timestamp = arrow.utcnow().timestamp

    return [pack_msg(response, session), pack_msg(sync)]
Пример #26
0
    def battle(self, _id):
        str_id = str(_id)

        try:
            self.this_stage = STAGE_ELITE[_id]
        except KeyError:
            raise SanguoException(errormsg.STAGE_ELITE_NOT_EXIST, self.char_id,
                                  "StageElite Battle",
                                  "StageElite {0} not exist".format(_id))

        try:
            times = self.stage.elites[str_id]
        except KeyError:
            raise SanguoException(errormsg.STAGE_ELITE_NOT_OPEN, self.char_id,
                                  "StageElite Battle",
                                  "StageElite {0} not open".format(_id))

        if str(self.this_stage.open_condition) not in self.stage.stages:
            if self.this_stage.previous and str(
                    self.this_stage.previous) not in self.stage.elites:
                raise SanguoException(
                    errormsg.STAGE_ELITE_NOT_OPEN, self.char_id,
                    "StageElite Battle",
                    "StageElite {0} not open. XXX check source core/stage/EliteStage Open"
                    .format(_id))

        if times >= self.this_stage.times:
            raise SanguoException(errormsg.STAGE_ELITE_NO_TIMES, self.char_id,
                                  "StageElite Battle",
                                  "StageElite {0} no times".format(_id))

        counter = Counter(self.char_id, 'stage_elite')
        if counter.remained_value <= 0:
            raise SanguoException(errormsg.STAGE_ELITE_TOTAL_NO_TIMES,
                                  self.char_id, "StageElite Battle",
                                  "stageElite no total times.")

        battle_msg = protomsg.Battle()
        b = ElitePVE(self.char_id, _id, battle_msg)
        b.start()

        if battle_msg.self_win:
            self.stage.elites[str_id] += 1
            if self.this_stage.next:

                if str(self.this_stage.next) not in self.stage.elites:
                    self.stage.elites[str(self.this_stage.next)] = 0
                    self.send_new_notify(self.this_stage.next)
            self.stage.save()

            self.send_update_notify(_id)

            counter.incr()
            self.send_remained_times_notify()
            self.enable_next_elite_stage(_id)

        return battle_msg
Пример #27
0
    def step_up(self):
        # 升阶
        if self.step >= HERO_MAX_STEP:
            raise SanguoException(
                errormsg.HERO_REACH_MAX_STEP, self.char_id, "Hero Step Up",
                "Hero {0} reach max step {1}".format(self.id, HERO_MAX_STEP))

        resource_needs = {}
        cost_gold = self.get_step_up_gold_needs()

        resource_needs['gold'] = -cost_gold
        soul_needs_amount = self.get_step_up_soul_needs()

        resource_needs['souls'] = [(self.oid, soul_needs_amount)]

        hs = HeroSoul(self.char_id)
        self_soul_amount = hs.soul_amount(self.oid)
        common_soul_needs = soul_needs_amount - self_soul_amount
        if common_soul_needs > 0:
            # need common soul
            resource_needs['stuffs'] = [(22, common_soul_needs)]

        resource = Resource(self.char_id, "Hero Step Up",
                            'step up {0}'.format(self.id))
        try:
            resource.check_and_remove(**resource_needs)
        except SanguoException as e:
            if e.error_id == errormsg.SOUL_NOT_ENOUGH or e.error_id == errormsg.STUFF_NOT_ENOUGH:
                raise SanguoException(errormsg.HERO_STEP_UP_ALL_NOT_ENOUGH,
                                      self.char_id, "Hero Step Up",
                                      "soul not enough")
            raise e

        # 扣完东西了,开始搞一次
        self.hero.progress += 1
        if self.hero.progress >= self.max_socket_amount:
            # 真正的升阶
            # 否则仅仅是记录当前状态
            self.hero.step += 1
            self.hero.progress = 0

            hero_step_up_signal.send(sender=None,
                                     char_id=self.char_id,
                                     hero_id=self.id,
                                     new_step=self.hero.step)

        self.step = self.hero.step
        self.hero.save()
        hero_changed_signal.send(sender=None, hero_id=self.id)

        TimesLogHeroStepUp(self.char_id).inc()
        if self.step >= 5:
            ae = ActivityEntry(self.char_id, 40004)
            if ae:
                ae.enable(self.step)
                ActivityStatic(
                    self.char_id).send_update_notify(activity_ids=[40004])
Пример #28
0
    def special_buy(self, socket_id, tp):
        # FIXME
        try:
            this_socket = self.formation.sockets[str(socket_id)]
        except KeyError:
            raise SanguoException(errormsg.FORMATION_NONE_EXIST_SOCKET,
                                  self.char_id, "Formation Special Buy",
                                  "socket {0} not exist".format(socket_id))

        if not this_socket.hero:
            raise SanguoException(errormsg.FORMATION_NO_HERO, self.char_id,
                                  "Formation Special Buy",
                                  "socket {0} no hero".format(socket_id))

        oid = MongoHero.objects.get(id=this_socket.hero).oid

        this_hero = HEROS[oid]
        special_cls = [int(i) for i in this_hero.special_equip_cls.split(',')]

        def _find_speicial_id(equipments):
            for e in equipments:
                if e.step == 0 and e.cls in special_cls:
                    return e.id

            # FIXME
            raise Exception("Special buy, not find. tp = {0}".format(tp))

        from core.item import Item
        item = Item(self.char_id)

        if tp == SpecialEquipmentBuyRequest.SOCKET_WEAPON:
            on_id = _find_speicial_id(ALL_WEAPONS.values())
            new_id = item.equip_add(on_id)
            self.formation.sockets[str(socket_id)].weapon = new_id
        elif tp == SpecialEquipmentBuyRequest.SOCKET_ARMOR:
            on_id = _find_speicial_id(ALL_ARMORS.values())
            new_id = item.equip_add(on_id)
            self.formation.sockets[str(socket_id)].armor = new_id
        else:
            on_id = _find_speicial_id(ALL_JEWELRY.values())
            new_id = item.equip_add(on_id)
            self.formation.sockets[str(socket_id)].jewelry = new_id

        self.formation.save()
        socket_changed_signal.send(
            sender=None, socket_obj=self.formation.sockets[str(socket_id)])

        standard_drop = make_standard_drop_from_template()
        standard_drop['equipments'] = [(new_id, 1, 1)]
        standard_drop['income'] = 1
        standard_drop['func_name'] = "Special Buy"
        standard_drop['des'] = ''
        resource_logger(self.char_id, standard_drop)

        self.send_socket_changed_notify(socket_id,
                                        self.formation.sockets[str(socket_id)])
Пример #29
0
    def battle(self):
        counter = Counter(self.char_id, 'arena')
        try:
            # 免费次数
            counter.incr()
        except CounterOverFlow:
            counter = Counter(self.char_id, 'arena_buy')

            try:
                # 花费元宝次数
                counter.incr()
            except CounterOverFlow:
                char = Char(self.char_id).mc
                if char.vip < VIP_MAX_LEVEL:
                    raise SanguoException(
                        errormsg.ARENA_NO_TIMES, self.char_id, "Arena Battle",
                        "arena no times. vip current: {0}, max {1}".format(
                            char.vip, VIP_MAX_LEVEL))
                raise SanguoException(
                    errormsg.ARENA_NO_TIMES_FINAL, self.char_id,
                    "Arena Battle",
                    "arena no times. vip reach max level {0}".format(
                        VIP_MAX_LEVEL))

            else:
                resource = Resource(self.char_id, "Arena Battle",
                                    "battle for no free times")
                resource.check_and_remove(sycee=-ARENA_COST_SYCEE)

        rival_id = self.choose_rival()

        msg = protomsg.Battle()
        b = PVP(self.char_id, rival_id, msg)
        b.start()

        achievement = Achievement(self.char_id)

        if msg.self_win:
            score = ARENA_GET_SCORE_WHEN_WIN
            achievement.trig(11, 1)
            self.mongo_arena.continues_win += 1
        else:
            score = ARENA_GET_SCORE_WHEN_LOST
            self.mongo_arena.continues_win = 0

        self.mongo_arena.save()

        if score:
            self.mongo_day.score += score
            self.mongo_day.save()

        t = Task(self.char_id)
        t.trig(2)

        self.send_notify()
        return msg
Пример #30
0
 def check_max_amount(self, func_name):
     if self.cur_amount >= self.max_amount:
         if self.char.mc.vip < VIP_MAX_LEVEL:
             raise SanguoException(
                 errormsg.FRIEND_FULL, self.char_id, func_name,
                 "friends full. vip current: {0}, max: {1}".format(
                     self.char.mc.vip, VIP_MAX_LEVEL))
         raise SanguoException(
             errormsg.FRIEND_FULL_FINAL, self.char_id, func_name,
             "friends full. vip reach max level {0}".format(VIP_MAX_LEVEL))