Beispiel #1
0
def compose(data, src_info, dest_basic_id, now, dest_num=1):
    """物品合成
    Args:
        src_info[list(basic_id)]: 原材料物品信息
        dest_basic_id[int]: 合成物品的 basic id
        dest_num[int]: 合成的物品的数量,默认是1
    Returns:
        True: 合成成功
        False:合成失败
    """
    src_basic_id = data_loader.ItemComposeBasicInfo_dict[dest_basic_id].srcId
    src_num = data_loader.ItemComposeBasicInfo_dict[dest_basic_id].srcNum
    money_cost = data_loader.ItemComposeBasicInfo_dict[
        dest_basic_id].moneyCost * dest_num
    assert len(src_basic_id) == len(src_num)

    #花费金钱
    resource = data.resource.get()
    resource.update_current_resource(now)
    if not resource.cost_money(money_cost):
        logger.warning("not enough money[money=%d][need=%d]" %
                       (resource.money, money_cost))
        return False

    if set(src_info) != set(src_basic_id):
        logger.debug("Source item error[expect=%s][source=%s]" %
                     (src_basic_id, src_info))
        return False
    output_items = []
    for index in range(0, len(src_basic_id)):
        src_id = ItemInfo.generate_id(data.id, src_basic_id[index])
        src_item = data.item_list.get(src_id)
        consume = src_item.consume(src_num[index] * dest_num)
        if not consume[0]:
            return False
        output_items.append("[item=")
        output_items.append(utils.join_to_string(list(consume[1])))
        output_items.append("]")
    item = ''.join(output_items)
    log = log_formater.output_item(data, "compose consume",
                                   log_formater.COMPOSE_CONSUME, item)
    logger.notice(log)

    dest_id = ItemInfo.generate_id(data.id, dest_basic_id)
    dest = data.item_list.get(dest_id)
    if dest is None:
        #新物品
        dest = ItemInfo.create(data.id, dest_basic_id, dest_num)
        data.item_list.add(dest)
    else:
        dest.acquire(dest_num)
    compose_item = "[item=" + utils.join_to_string(
        [dest_basic_id, dest_num, dest.num]) + "]"
    log = log_formater.output_item(data, "compose gain",
                                   log_formater.COMPOSE_GAIN, compose_item)
    logger.notice(log)
    return dest
Beispiel #2
0
    def _calc_use_speed_item(self, data, req, timer):
        res = speed_pb2.UseSpeedItemRes()
        res.status = 0

        building = None
        technology = None
        if req.HasField("building"):
            building_id = BuildingInfo.generate_id(data.id,
                                                   req.building.city_basic_id,
                                                   req.building.location_index,
                                                   req.building.basic_id)
            building = data.building_list.get(building_id)

        elif req.HasField("tech"):
            technology_id = TechnologyInfo.generate_id(data.id,
                                                       req.tech.basic_id,
                                                       req.tech.type)
            technology = data.technology_list.get(technology_id)

        item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
        item = data.item_list.get(item_id)

        use_num = item.num - req.item.num
        if not item_business.use_speed_item(item, use_num, building,
                                            technology):
            logger.warning("Use speed item failed")
            res.return_ret = speed_pb2.UseSpeedItemRes.SPEED_ITEM_ERROR
        else:
            res.return_ret = 0

        compare.check_item(data, req.item)

        defer = DataBase().commit(data)
        defer.addCallback(self._use_speed_item_succeed, req, res, timer)
        return defer
Beispiel #3
0
    def _calc_drum(self, data, req, timer):
        union = data.union.get(True)
        if not union.is_belong_to_target_union(req.union_id):
            res = union_battle_pb2.DrumForUnionBattleRes()
            res.status = 0
            res.ret = union_pb2.UNION_NOT_MATCHED

            defer = DataBase().commit(data)
            defer.addCallback(self._drum_succeed, req, res, timer)
            return defer

        cost_gold = 0
        if req.HasField("gold"):
            cost_gold = req.gold
        item = None
        if req.HasField("item"):
            item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
            item = data.item_list.get(item_id)

        if not union_battle_business.is_able_to_drum(data, item, cost_gold):
            raise Exception("Not able to drum")

        union_req = internal_union_pb2.InternalDrumForUnionBattleReq()
        union_req.user_id = data.id
        union_req.user_level = data.user.get(True).level
        defer = GlobalObject().remote['gunion'].callRemote(
            "drum_for_battle", req.union_id, union_req.SerializeToString())
        defer.addCallback(self._calc_drum_result, data, item, cost_gold, req,
                          timer)
        return defer
Beispiel #4
0
def is_able_to_start_aid(data, item_basic_id, item_num, now):
    """发起联盟援助
    """
    union = data.union.get(True)

    #需要拥有对应英雄或者拥有将魂石
    item_id = ItemInfo.generate_id(data.id, item_basic_id)
    item = data.item_list.get(item_id, True)
    if item is not None and not item.is_starsoul_item():
        logger.warning("Item is not a starsoul stone[item_basic_id=%d]" %
                       item_basic_id)
        return False

    hero_basic_id = ItemInfo.get_corresponding_value(item_basic_id)
    hero_id = HeroInfo.generate_id(data.id, hero_basic_id)
    hero = data.hero_list.get(hero_id, True)

    if item is None and hero is None:
        logger.warning("Can not start aid[item_basic_id=%d]" % item_basic_id)
        return False

    #数量正确
    expect_num = union.calc_aid_item_num(item_basic_id)
    if item_num != expect_num:
        logger.warning("Aid item num error[wrong_num=%d][item_num=%d]" %
                       (item_num, expect_num))
        return False

    return True
Beispiel #5
0
def gain_item(data, infos, str, use_type):
    """获得新物品
    如果原来已经拥有物品,物品数量增加
    如果原来没有这件物品,添加物品
    Args:
        infos[list(basic_id, num)]: 奖励的物品信息
    Returns:
        True: 成功
        False: 失败
    """
    output_items = []
    for (basic_id, num) in infos:
        id = ItemInfo.generate_id(data.id, basic_id)
        item = data.item_list.get(id)
        if item is not None:
            item.acquire(num)
        else:
            item = ItemInfo.create(data.id, basic_id, num)
            data.item_list.add(item)
        item = [basic_id, num, item.num]
        output_items.append("[item=")
        output_items.append(utils.join_to_string(item))
        output_items.append("]")
    item = ''.join(output_items)
    log = log_formater.output_item(data, str, use_type, item)
    logger.notice(log)
    #logger.notice("gain items %s"% ''.join(output_items))
    return True
Beispiel #6
0
    def _calc_increase(self, data, req, timer):
        """
        """
        #涉及到跨天的数据统计,所以此处要更新所有跨天数据
        if not account_business.update_across_day_info(data, timer.now):
            raise Exception("Update across day info failed")

        node_id = NodeInfo.generate_id(data.id, req.node.basic_id)
        node = data.node_list.get(node_id)

        use_gold = req.node.increase.use_gold
        rate = req.node.increase.rate
        duration = req.node.increase.total_time

        if use_gold:
            item = None
        else:
            item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
            item = data.item_list.get(item_id)

        if not increase_business.increase(data, node, rate, use_gold, duration,
                                          item, timer.now):
            raise Exception("Increase failed")

        #记录次数
        trainer = data.trainer.get()
        trainer.add_daily_increase_item_num(1)

        return DataBase().commit(data)
Beispiel #7
0
def calc_sweep_income(data, anneal, attack_num, sweep_rewards, items, now):
    """计算试炼场战斗的扫荡奖励
       sweep_reward : list(list(item_basic_id, item_num)) out 记录每轮扫荡的奖励
       items[list((ItemInfo)  out]
    """
    #计算扫荡奖励
    reward_items = []
    is_normal = True
    reward_total_money = 0
    reward_total_food = 0
    for i in range(attack_num):
        if is_normal:
            type = AnnealInfo.NORMAL_MODE
            is_normal = not is_normal
        else:
            type = AnnealInfo.HARD_MODE
            is_normal = not is_normal

        #enemy的level
        level = anneal.get_anneal_enemy_level(type, anneal.sweep_floor,
                                              AnnealInfo.LEVEL_NUM_PER_FLOOR)

        #随机奖励
        spoils = reward_module.random_anneal_spoils(level, type, True,
                                                    anneal.sweep_direction)
        for spoil in spoils:
            reward_items.append(spoil)

        #资源奖励
        (reward_money, reward_food) = calc_resource_income(level)
        reward_total_money += reward_money
        reward_total_food += reward_food

        sweep_rewards.append((reward_money, reward_food, spoils))  #返回每轮奖励

    resource = data.resource.get()
    resource.update_current_resource(now)
    resource.gain_money(reward_total_money)
    resource.gain_food(reward_total_food)

    if not item_business.gain_item(data, reward_items, "sweep reward",
                                   log_formater.SWEEP_REWARD):
        logger.warning("gain reward item failed")
        return False

    #合并重复的 item
    merge_items = {}
    for (basic_id, num) in reward_items:
        if basic_id not in merge_items:
            merge_items[basic_id] = num
        else:
            merge_items[basic_id] += num

    for key in merge_items:
        item_id = ItemInfo.generate_id(data.id, key)
        item = data.item_list.get(item_id)
        items.append(item)  #返回有变化的item列表

    return True
Beispiel #8
0
    def _calc_upgrade_level(self, data, req, timer):
        """重现客户端英雄升级计算逻辑,和请求进行比较
        Args:
            data[UserData]: 升级前的数据,从数据库中获得
            req[UpdateHeroReq]: 升级后的数据,客户端发送的请求
        Returns:
            data[UserData]: 升级后的数据
        """
        items = []
        for item in req.item:
            item_id = ItemInfo.generate_id(data.id, item.basic_id)
            item = data.item_list.get(item_id)
            items.append(item)

        #新逻辑,传过来经验丹的消耗数量,以防客户端和服务器物品数量不一致
        use_items = []
        for item in req.use_item:
            item_id = ItemInfo.generate_id(data.id, item.basic_id)
            item = data.item_list.get(item_id)
            use_items.append(item)

        hero_id = HeroInfo.generate_id(data.id, req.hero.basic_id)
        hero = data.hero_list.get(hero_id)

        if (len(items) == 0 and len(use_items) == 0) or hero is None:
            raise Exception("Items or hero not exist")
        if len(use_items) != 0:
            #走新逻辑
            for i in range(len(use_items)):
                consume_num = req.use_item[i].num
                if not hero_business.level_upgrade_by_item(
                        data, hero, use_items[i], consume_num, timer.now):
                    raise Exception("Hero level upgrade failed")
        else:
            for i in range(len(items)):
                consume_num = items[i].num - req.item[i].num
                if not hero_business.level_upgrade_by_item(
                        data, hero, use_items[i], consume_num, timer.now):
                    raise Exception("Hero level upgrade failed")
        #验证
        compare.check_hero(data, req.hero, with_level=True, with_soldier=True)
        #for item in req.item:
        #    compare.check_item(data, item)

        return DataBase().commit(data)
Beispiel #9
0
def calc_sweep_reward(data, anneal, attack_num, sweep_rewards, items, now):
    """扫荡奖励(新版)"""
    reward_total_money = 0
    reward_total_food = 0
    reward_items = []

    for i in xrange(attack_num):
        level = anneal.get_anneal_enemy_level(anneal.sweep_mode,
                                              anneal.sweep_floor,
                                              AnnealInfo.LEVEL_NUM_PER_FLOOR)

        at_least = False
        if i == attack_num - 1 and anneal.sweep_at_least:
            """保底掉落"""
            at_least = True

        #随机奖励
        spoils = reward_module.random_anneal_spoils(anneal.sweep_floor,
                                                    anneal.sweep_mode, True,
                                                    anneal.sweep_direction,
                                                    at_least)
        reward_items.extend(spoils)

        #资源奖励
        (reward_money, reward_food) = calc_resource_income(level)
        reward_total_money += reward_money
        reward_total_food += reward_food

        sweep_rewards.append((reward_money, reward_food, spoils))  #返回每轮奖励

    resource = data.resource.get()
    resource.update_current_resource(now)
    resource.gain_money(reward_total_money)
    resource.gain_food(reward_total_food)

    if not item_business.gain_item(data, reward_items, "new sweep reward",
                                   log_formater.NEW_SWEEP_REWARD):
        logger.warning("gain reward item failed")
        return False

    #合并重复的 item
    merge_items = {}
    for (basic_id, num) in reward_items:
        if basic_id not in merge_items:
            merge_items[basic_id] = num
        else:
            merge_items[basic_id] += num

    for key in merge_items:
        item_id = ItemInfo.generate_id(data.id, key)
        item = data.item_list.get(item_id)
        items.append(item)  #返回有变化的item列表

    return True
Beispiel #10
0
    def _calc_upgrade_star(self, data, req, timer):
        """重现客户端升星计算逻辑,和请求进行比较
        """
        res = hero_pb2.UpdateHeroRes()
        res.status = 0

        hero_id = HeroInfo.generate_id(data.id, req.hero.basic_id)
        hero = data.hero_list.get(hero_id)
        item_id = ItemInfo.generate_id(data.id, req.item[0].basic_id)
        item = data.item_list.get(item_id)

        if hero is None or item is None:
            raise Exception("Hero or item not exist")

        #消耗精魄
        soul_num = 0
        open_flags = account_business.get_flags()
        if "HeroUpStarUseSoul" in open_flags:
            soul_num = data_loader.HeroStarLevelBasicInfo_dict[
                req.hero.star_level].soul

        #使用灵魂石
        consume_num = data_loader.HeroStarLevelBasicInfo_dict[
            req.hero.star_level].perceptivity
        ret = hero_business.star_upgrade(data, hero, item, consume_num,
                                         soul_num, timer.now)
        if ret != hero_pb2.HERO_OK:
            res.ret = ret
            return self._upgrade_star_succeed(data, req, res, timer)

        #和请求进行比较
        if req.hero.star_level != hero.star:
            raise Exception("Unexpect hero star[expect star=%d]" % hero.star)

        #验证
        compare.check_hero(data, req.hero, with_star=True)
        compare.check_item(data, req.item[0])

        resource = data.resource.get()
        resource.update_current_resource(timer.now)

        res.ret = hero_pb2.HERO_OK
        pack.pack_resource_info(resource, res.resource)

        try:
            if hero.is_need_broadcast_star_level():
                self._add_upgrade_star_level_broadcast(data.user.get(), hero)
        except:
            logger.warning("Send upgrade star level broadcast failed")

        defer = DataBase().commit(data)
        defer.addCallback(self._upgrade_star_succeed, req, res, timer)
        return defer
Beispiel #11
0
def _calc_mission(data, mission, now, force):
    """结算已经完成的任务
    1 获得奖励
    2 开启后续任务(如果有后续的话)
    """
    #检查是否结束
    user = data.user.get(True)
    if not force and not mission.is_finish(user.level):
        logger.warning("Mission not finish[basic id=%d]" % (mission.basic_id))
        return False

    reward = data_loader.AllMission_dict[mission.basic_id].reward
    #获得资源
    resource = data.resource.get()
    original_gold = resource.gold
    resource.update_current_resource(now)
    resource.gain_money(reward.money)
    resource.gain_food(reward.food)
    resource.gain_gold(reward.gold)
    log = log_formater.output_gold(data,
                                   reward.gold,
                                   log_formater.MISSION_REWARD_GOLD,
                                   "Gain gold from compelete mission",
                                   before_gold=original_gold)
    logger.notice(log)

    #获得政令
    energy = data.energy.get()
    energy.update_current_energy(now)
    energy.gain_energy(reward.energy)

    #获得战利品
    item_list = mission.get_reward_items()
    if not item_business.gain_item(data, item_list, "mission reward",
                                   log_formater.MISSION_REWARD):
        return False
    for i in range(0, len(item_list)):
        id = ItemInfo.generate_id(data.id, item_list[i][0])
        item = data.item_list.get(id)

    #用户获得经验
    if not user_business.level_upgrade(data, reward.monarchExp, now,
                                       "mission exp",
                                       log_formater.EXP_MISSION):
        return False

    #创建后续任务
    next_mission = mission.create_next()
    if next_mission is not None:
        data.mission_list.add(next_mission)

    return True
Beispiel #12
0
def check_item_r(data, message):
    """更加健壮的验证物品信息的方法"""
    item_id = ItemInfo.generate_id(data.id, message.basic_id)
    item = data.item_list.get(item_id, True)
    if item is None:
        item_num = 0
    else:
        item_num = item.num
    if item_num != message.num:
        logger.warning("check item error[basic_id=%d][num=%d][req_num=%d]" %
                       (item.basic_id, item_num, message.num))
        return False
    else:
        return True
Beispiel #13
0
    def _pack_valid_cdkey_response(self, data, goodybag_id, resource,
                                   item_list):
        """封装响应
        """
        res = user_pb2.UseCDkeyRes()
        res.status = 0

        res.goodybag_id = goodybag_id
        pack.pack_resource_info(resource, res.resource)
        for (basic_id, num) in item_list:
            item_id = ItemInfo.generate_id(data.id, basic_id)
            item = data.item_list.get(item_id)
            pack.pack_item_info(item, res.items.add())

        return res
Beispiel #14
0
def is_able_to_respond_aid(data, item_basic_id):
    """是否可以进行捐赠
    """
    item_id = ItemInfo.generate_id(data.id, item_basic_id)
    item = data.item_list.get(item_id, True)
    if item is None:
        logger.warning("No item to respond aid[item_basic_id=%d]" %
                       item_basic_id)
        return False
    elif item.num < 1:
        logger.warning(
            "Not enough item num to respond aid[item_basic_id=%d][item_num=%d]"
            % (item_basic_id, item.num))
        return False

    return True
Beispiel #15
0
    def _calc_update_country(self, data, req, timer):
        """
        """
        #使用将军令
        item_id = ItemInfo.generate_id(data.id, req.item_basic_id)
        item = data.item_list.get(item_id)
        if item is None:
            logger.warning("Item not exist")
        else:
            item.consume(max(0, req.item_num))

        request = req.SerializeToString()

        logger.debug("sync common country[req=%s]" % req)
        defer = GlobalObject().remote["common"].callRemote(
            "update_country", 1, request)
        defer.addCallback(self._check_update_country_result, data, req, timer)
        return defer
Beispiel #16
0
    def _calc_refresh_goods(self, data, req, types, timer):
        #涉及到跨天的数据统计,所以此处要更新所有跨天数据
        if not account_business.update_across_day_info(data, timer.now):
            raise Exception("Update across day info failed")

        shops = []
        index = 1
        if req.HasField("index"):
            index = req.index
        for type in types:
            shop_id = ShopInfo.generate_id(data.id, type, index)
            shops.append(data.shop_list.get(shop_id))

        is_refresh_with_item = False
        refresh_item = None
        if req.HasField("item"):
            #用刷新代币刷新商铺
            is_refresh_with_item = True
            item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
            refresh_item = data.item_list.get(item_id)
            if refresh_item is None:
                raise Exception("Item not exist")

        free = False
        if shops[0].is_able_to_refresh_free(timer.now):
            free = True

        goods = []
        if not shop_business.refresh_goods(data, shops, goods, timer.now,
                                           refresh_item, free):
            raise Exception("Refresh goods failed")

        if is_refresh_with_item:
            compare.check_item(data, req.item)

        resource = data.resource.get(True)
        #任意选择一个商店的刷新次数
        res = self._pack_refresh_goods_response(goods, shops[0], resource, req,
                                                timer.now)

        defer = DataBase().commit(data)
        defer.addCallback(self._refresh_goods_succeed, types, req, res, timer)
        return defer
Beispiel #17
0
def respond_aid(data, item_basic_id, honor, exp, gold, now):
    """响应援助,进行捐赠
    获得奖励
    """
    union = data.union.get()

    #消耗物品
    item_id = ItemInfo.generate_id(data.id, item_basic_id)
    item = data.item_list.get(item_id)
    consume = item.consume(1)
    if not consume[0]:
        return False
    output_items = []
    output_items.append("[item=")
    output_items.append(utils.join_to_string(list(consume[1])))
    output_items.append("]")
    log = log_formater.output_item(data, "respond aid",
                                   log_formater.RESPOND_AID,
                                   ''.join(output_items))
    logger.notice(log)
    #logger.notice("respond aid %s"%''.join(output_items))
    #获得联盟荣誉
    union.gain_honor(honor)

    #获得主公经验
    if not user_business.level_upgrade(data, exp, now, "exp aid",
                                       log_formater.EXP_AID):
        return False

    #获得元宝奖励
    resource = data.resource.get()
    resource.update_current_resource(now)
    original_gold = resource.gold
    resource.gain_gold(gold)
    log = log_formater.output_gold(data,
                                   gold,
                                   log_formater.RESPOND_AID_REWARD,
                                   "Gain gold from respond aid",
                                   before_gold=original_gold)
    logger.notice(log)

    return True
Beispiel #18
0
def check_item(data, message):
    """
    验证物品信息
    Args:
        data[UserData]
        message[protobuf]
    """
    item_id = ItemInfo.generate_id(data.id, message.basic_id)
    item = data.item_list.get(item_id, True)

    #logger.debug("checkout item[basic_id=%d][num=%d]" % (item.basic_id, item.num))
    #客户端bug导致此处经常失败,先放过
    #assert item.num == message.num
    if item is None:
        if message.num != 0:
            logger.warning("check item error[basic_id=%d][num=0][req_num=%d]" %
                           (message.basic_id, message.num))
    elif item.num != message.num:
        logger.warning("check item error[basic_id=%d][num=%d][req_num=%d]" %
                       (item.basic_id, item.num, message.num))
Beispiel #19
0
    def _calc_buy_buff(self, data, req, timer):
        city_id = LegendCityInfo.generate_id(data.id, req.city_id)
        legendcity = data.legendcity_list.get(city_id)

        if req.HasField("item"):
            #消耗物品获得 buff
            item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
            item = data.item_list.get(item_id)
            if not item.use_legendcity_buff_item():
                raise Exception("Use legendcity buff item failed")

            #检查 buff 和 item 是否匹配
            if not legendcity.check_buff_available(req.city_buff_id,
                                                   req.item.basic_id):
                raise Exception("Check buff available failed")
        else:
            #消耗元宝获得 buff
            need = legendcity.get_buff_gold_cost(req.city_buff_id)
            if need != req.gold:
                raise Exception("Unmatch gold cost[need=%d][cost=%d]" %
                                (need, req.gold))
            resource = data.resource.get()
            original_gold = resource.gold
            if not resource.cost_gold(need):
                raise Exception("Cost gold failed")
            log = log_formater.output_gold(data,
                                           -need,
                                           log_formater.LEGENDCITY_BUY_BUFF,
                                           "Buy buff by gold",
                                           before_gold=original_gold)
            logger.notice(log)

        if not legendcity.add_buff(req.city_buff_id, timer.now):
            raise Exception("Add legendcity buff failed")

        if req.HasField("item"):
            compare.check_item(data, req.item)

        defer = DataBase().commit(data)
        defer.addCallback(self._buy_buff_succeed, req, timer)
        return defer
Beispiel #20
0
    def _calc_enchant_equipment(self, data, req, timer):
        #涉及到跨天的数据统计,所以此处要更新所有跨天数据
        if not account_business.update_across_day_info(data, timer.now):
            raise Exception("Update across day info failed")

        #精炼后的装备 id
        if req.type == HeroInfo.EQUIPMENT_TYPE_WEAPON:
            dest_equipment_id = req.hero.equipment_weapon_id
        elif req.type == HeroInfo.EQUIPMENT_TYPE_ARMOR:
            dest_equipment_id = req.hero.equipment_armor_id
        elif req.type == HeroInfo.EQUIPMENT_TYPE_TREASURE:
            dest_equipment_id = req.hero.equipment_treasure_id
        else:
            raise Exception("Invalid input equipment type[type=%d]" % req.type)

        #精炼消耗的材料
        cost_item = []
        for item_info in req.items:
            item_id = ItemInfo.generate_id(data.id, item_info.basic_id)
            item = data.item_list.get(item_id)
            cost_num = item.num - item_info.num
            cost_item.append((item.id, cost_num))

        #精炼消耗的元宝
        cost_gold = 0
        if req.HasField("gold"):
            cost_gold = req.gold

        if not hero_business.equipment_enchant(
                data, req.hero.basic_id, req.type, dest_equipment_id,
                cost_item, cost_gold, timer.now):
            raise Exception("Enchant equipment failed")

        #验证
        compare.check_hero(data, req.hero, with_equipment_type = req.type)
        for item_info in req.items:
            compare.check_item(data, item_info)

        return DataBase().commit(data)
Beispiel #21
0
    def _calc_buy_attack_num(self, data, req, timer):
        """
        """
        #涉及到跨天的数据统计,所以此处要更新所有跨天数据
        if not account_business.update_across_day_info(data, timer.now):
            raise Exception("Update across day info failed")

        anneal = data.anneal.get()
        anneal.update_current_attack_num(timer.now)

        item = None
        if req.HasField("item"):
            item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
            item = data.item_list.get(item_id)

        need_gold, original_gold = anneal_business.buy_attack_num(
            data, anneal, item, timer.now)
        if need_gold < 0:
            raise Exception("Buy attack num failed")

        #记录次数
        #trainer = data.trainer.get()
        #trainer.add_daily_buy_attack_num(1)

        if req.HasField("item"):
            compare.check_item(data, req.item)

        if need_gold > 0:
            log = log_formater.output_gold(
                data,
                -need_gold,
                log_formater.BUY_ATTACK_NUM,
                "Buy attack num by gold",
                before_gold=original_gold,
                attack_num=anneal.get_attack_num_of_buy())
            logger.notice(log)

        return DataBase().commit(data)
Beispiel #22
0
    def _calc_upgrade_evolution_level(self, data, req, timer):
        """重现客户端升星计算逻辑,和请求进行比较
        """
        hero_id = HeroInfo.generate_id(data.id, req.hero.basic_id)
        hero = data.hero_list.get(hero_id)
        item_id = ItemInfo.generate_id(data.id, req.item[0].basic_id)
        item = data.item_list.get(item_id)

        if hero is None or item is None:
            raise Exception("Hero or item not exist")

        #使用突破石
        consume_num = item.num - req.item[0].num
        if not hero_business.evolution_level_upgrade(data, hero, item,
                                                     consume_num, timer.now):
            raise Exception("Hero evolution level upgrade failed]")

        #和请求进行比较
        if req.hero.evolution_level != hero.evolution_level:
            raise Exception(
                "Unexpect hero evolution level[expect evolution level=%d]" %
                hero.evolution_level)

        #验证
        compare.check_hero(data, req.hero, with_evolution=True)
        compare.check_item(data, req.item[0])

        if hero.is_need_broadcast():
            #玩家英雄达到一定等级时,广播
            try:
                self._add_upgrade_evolution_level_broadcast(
                    data.user.get(), hero)
            except:
                logger.warning("Send upgrade evolution level broadcast failed")

        return DataBase().commit(data)
Beispiel #23
0
def use_item(data, item, num, resource, now):
    """使用物品
    未来替代use_resource_item use_monarch_exp
    Args:
        item[ItemInfo out]: 物品信息
        num[int]: 消耗物品个数
        resource[ResourceInfo out]: 资源信息
        now[int]:时间
    Returns:
        使用物品正确,返回 True
        否则返回 False
    """
    if item.is_vip_point_item():
        vip_point = item.use_vip_point_item(num)
        if vip_point is None:
            return False
        user = data.user.get()
        #vip点数需要先折算成price
        ratio = float(
            data_loader.OtherBasicInfo_dict["ratio_pay_price_to_vip_points"].
            value)
        user.gain_vip_points(int(vip_point / ratio))

    elif item.is_package_item():
        package_basic_info = item.use_package_item(num)
        if package_basic_info is None:
            return False

        original_gold = resource.gold
        gold = package_basic_info.gold * num
        if gold > 0:
            resource.gain_gold(gold)
        log = log_formater.output_gold(data,
                                       gold,
                                       log_formater.ITEM_GOLD,
                                       "Gain gold from item",
                                       before_gold=original_gold)
        logger.notice(log)

        gain_items = []
        for i in range(0, len(package_basic_info.itemsBasicId)):
            gain_items.append((package_basic_info.itemsBasicId[i],
                               package_basic_info.itemsNum[i] * num))
        gain_item(data, gain_items, "resource item award",
                  log_formater.RESOURCE)

        for i in range(0, len(gain_items)):
            id = ItemInfo.generate_id(data.id, gain_items[i][0])
            item = data.item_list.get(id)

    elif item.is_month_card_item():
        month_card_type = item.use_month_card_item(num)
        if month_card_type is None:
            return False
        pay = data.pay.get()
        pay.add_card(month_card_type, now)

    else:
        logger.warning("Invalid item[basic id=%d]" % item.basic_id)
        return False

    return True
Beispiel #24
0
    def _calc_start_appoint(self, data, req, timer):
        item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
        item = data.item_list.get(item_id)
        if item is None:
            raise Exception("Item not exist")

        #扣减1个虎符
        if not item.use_appoint_item(1):
            raise Exception("Use appoint item failed")

        compare.check_item(data, req.item)

        #参战team/英雄
        teams = []
        heroes = []
        for team in req.battle.attack_teams:
            team_id = TeamInfo.generate_id(data.id, team.index)
            team = data.team_list.get(team_id)
            if team is None:
                continue

            teams.append(team)

            for hero_id in team.get_heroes():
                if hero_id != 0:
                    hero = data.hero_list.get(hero_id)
                    heroes.append(hero)

        if len(teams) == 0:
            raise Exception("Appoint teams is NULL")

        #敌人信息
        node_basic_id = req.node.basic_id
        node_id = NodeInfo.generate_id(data.id, node_basic_id)
        rival_id = node_id
        node = data.node_list.get(node_id)
        rival = data.rival_list.get(rival_id)

        if node.rival_type in (NodeInfo.ENEMY_TYPE_PVE_BANDIT,
                               NodeInfo.ENEMY_TYPE_PVE_REBEL):
            """山贼"""
            rival.reward_user_exp = int(
                float(data_loader.
                      OtherBasicInfo_dict['bandit_battle_cost_energy'].value))
        else:
            """侦察敌军"""
            rival.reward_user_exp = int(
                float(data_loader.
                      OtherBasicInfo_dict['keynode_battle_cost_energy'].value))

        user = data.user.get()
        if not appoint_business.start_appoint(
                data, user, node, rival, teams, heroes, timer.now, force=True):
            raise Exception("Start appoint failed")

        #构造返回
        res = self._pack_start_appoint_response(data, timer.now)

        defer = DataBase().commit(data)
        defer.addCallback(self._start_appoint_succeed, node, rival, req, res,
                          timer)
        return defer
Beispiel #25
0
    def _calc_draw(self, data, basic_data, req, type, timer):
        #涉及到跨天的数据统计,所以此处要更新所有跨天数据
        if not account_business.update_across_day_info(data, timer.now):
            raise Exception("Update across day info failed")

        user = data.user.get()
        resource = data.resource.get()
        draw = data.draw.get()

        resource.update_current_resource(timer.now)

        is_draw_with_item = False
        draw_item = None
        if req.HasField("item"):
            #用抽奖券抽
            is_draw_with_item = True
            item_id = ItemInfo.generate_id(data.id, req.item.basic_id)
            draw_item = data.item_list.get(item_id)
            if draw_item is None:
                raise Exception("Item not exist")

        hero_list = []
        item_list = []
        if type == self._TYPE_GOLD_DRAW:
            if not draw_business.draw_with_gold(
                    basic_data, data, user, resource, draw,
                    hero_list, item_list, timer.now, draw_item, req.free):
                raise Exception("Draw with gold failed")
        elif type == self._TYPE_MONEY_DRAW:
            if not draw_business.draw_with_money(
                    user, resource, draw, hero_list, item_list, timer.now, draw_item, req.free):
                raise Exception("Draw with money failed")
        elif type == self._TYPE_GOLD_MULTI_DRAW:
            if not draw_business.multi_draw_with_gold(
                    basic_data, data, user, resource, draw, hero_list, item_list, 
                    timer.now, draw_item):
                raise Exception("Multi draw with gold failed")
        elif type == self._TYPE_MONEY_MULTI_DRAW:
            if not draw_business.multi_draw_with_money(
                    user, resource, draw, hero_list, item_list, timer.now, draw_item):
                raise Exception("Multi draw with money failed")
        #elif type == self._TYPE_TREASURE_DRAW:
        #    pass
        #elif type == self._TYPE_TREASURE_MULTI_DRAW:
        #    pass 
        else:
            raise Exception("Invalid draw type[type=%d]" % type)

        #添加抽奖得到的英雄和物品
        for (hero_basic_id, hero_num) in hero_list:
            if not hero_business.gain_hero(data, hero_basic_id, hero_num):
                raise Exception("Gain hero failed")
        if not item_business.gain_item(data, item_list, "draw ", log_formater.DRAW):
            raise Exception("Gain item failed")

        if is_draw_with_item:
            compare.check_item(data, req.item)

        #获得S级武将要播广播
        for (hero_basic_id, hero_num) in hero_list:
            if hero_business.is_need_broadcast(hero_basic_id):
                try:
                    self._add_get_hero_broadcast(data.user.get(), draw, hero_basic_id)
                except:
                    logger.warning("Send get hero broadcast failed")

        #构造返回
        if type == self._TYPE_GOLD_DRAW or type == self._TYPE_GOLD_MULTI_DRAW:
            free_num = draw.gold_draw_free_num
            free_time = draw.gold_draw_free_time
        else:
            free_num = draw.money_draw_free_num
            free_time = draw.money_draw_free_time

        res = self._pack_draw_response(data, hero_list, item_list, resource,
                free_num, free_time, timer.now)

        defer = DataBase().commit(data)
        defer.addCallback(self._draw_succeed, type, req, res, timer)
        return defer
Beispiel #26
0
def casting(data, src_info, dest_basic_id, dest_num, building_level):
    """物品熔铸
    Args:
        src_info[list((basic_id, casting_num))]: 原材料物品信息
        dest_basic_id[int]: 熔铸物品的 basic id
        building_level[int]:铁匠铺等级
    Returns:
        True: 合成成功
        False:合成失败
    """
    if not data_loader.BlackSmithBasicInfo_dict.has_key(building_level):
        logger.warning(
            "BlackSmith building level is error[building_level=%d]" %
            building_level)
        return (False, None)

    #dest
    dest_item_basic = data_loader.ItemBasicInfo_dict[dest_basic_id]
    dest_casting_value = dest_item_basic.value
    if (dest_item_basic.type != int(
            float(data_loader.OtherBasicInfo_dict["item_equipment_upgrade"].
                  value)) or dest_casting_value == 0):
        logger.warning("Casting dest item error[basic_id=%d]" % dest_basic_id)
        return (False, None)
    if dest_basic_id not in data_loader.BlackSmithBasicInfo_dict[
            building_level].itemIds:
        logger.warning(
            "BlackSmith building level is not reached[building_level=%d][dest_basic_id=%d]"
            % (building_level, dest_basic_id))
        return (False, None)

    #p
    p = float(data_loader.OtherBasicInfo_dict["P_BlackSmith"].value)

    #src
    src_casting_value = 0
    output_items = []
    for info in src_info:
        src_id = ItemInfo.generate_id(data.id, info[0])
        src_item = data.item_list.get(src_id)
        if not src_item.is_equipment_upgrade_item():
            logger.warning("Casting source item type error[basic_id=%d]" %
                           info[0])
            return (False, None)

        #消耗熔铸的原材料
        consume = src_item.consume(info[1])
        if not consume[0]:
            logger.warning(
                "Casting source item num error[basic_id=%d][num=%d]" %
                (src_item.basic_id, src_item.num))
            return (False, None)
        output_items.append("[item=")
        output_items.append(utils.join_to_string(list(consume[1])))
        output_items.append("]")
        src_casting_value += min(
            data_loader.ItemBasicInfo_dict[info[0]].value * p,
            dest_casting_value) * info[1]
    item = ''.join(output_items)
    log = log_formater.output_item(data, "casting consume",
                                   log_formater.CASTING_CONSUME, item)
    logger.notice(log)
    #logger.notice("casting %s"%''.join(output_items))
    #熔铸成功率
    p_casting = 1.0 * src_casting_value / (dest_casting_value * dest_num)

    random.seed()
    p_random = random.random()
    dest_item = None
    if p_random < p_casting:
        #熔铸成功
        dest_id = ItemInfo.generate_id(data.id, dest_basic_id)
        dest_item = data.item_list.get(dest_id)
        if dest_item is None:
            #新物品
            dest_item = ItemInfo.create(data.id, dest_basic_id, dest_num)
            data.item_list.add(dest_item)
        else:
            dest_item.acquire(dest_num)
        casting_item = "[item=" + utils.join_to_string(
            [dest_basic_id, dest_num, dest_item.num]) + "]"
        log = log_formater.output_item(data, "casting gain",
                                       log_formater.CASTING_GAIN, casting_item)
        logger.notice(log)

#logger.notice("gain item[item=%d#%d#%d]"%(dest_basic_id, dest_num, dest_item.num))

    logger.debug(
        "Casting result[src_value=%d][dest_value=%d][p_casting=%f][p_random=%f]"
        % (src_casting_value, dest_casting_value, p_casting, p_random))
    return (True, dest_item)
Beispiel #27
0
def get_item_by_id(data, item_id, readonly=False):
    """通过物品id获取物品"""
    id = ItemInfo.generate_id(data.id, item_id)
    return data.item_list.get(id, readonly)
Beispiel #28
0
def buy_goods(data, shop, id, now, tax=0):
    """购买货物
    Args:
        shop[ShopInfo out]: 酒肆信息
        resource[ResourceInfo out]: 资源信息
        id[int]: 货物的 id
        tax[int]: 税率 [0-100]
    Returns:
        True/False 是否成功
    """
    resource = data.resource.get()
    original_gold = resource.gold
    resource.update_current_resource(now)

    goods = shop.buy_goods(id)
    if goods is None:
        return False

    #记录次数
    trainer = data.trainer.get()

    if shop.type == ShopInfo.GOODS_TYPE_MONEY:
        #消耗金钱
        if not resource.cost_money(goods.get_real_price()):
            return False
        trainer.add_daily_buy_goods_in_wineshop(1)
    elif shop.type == ShopInfo.GOODS_TYPE_GOLD:
        #消耗元宝
        if not resource.cost_gold(goods.get_real_price()):
            return False
        trainer.add_daily_buy_goods_in_wineshop(1)
    elif shop.type == ShopInfo.GOODS_TYPE_ACHIEVEMENT:
        #消耗成就值
        if not resource.cost_achievement(goods.get_real_price()):
            return False
        trainer.add_daily_buy_goods_in_achievement_shop(1)

    elif shop.type == ShopInfo.GOODS_TYPE_LEGENDCITY:
        pass
        trainer.add_daily_buy_goods_in_legendcity_shop(1)
    elif shop.type == ShopInfo.GOODS_TYPE_UNION:
        #消耗联盟荣誉
        union = data.union.get()
        if not union.consume_honor(goods.get_real_price()):
            return False
        trainer.add_daily_buy_goods_in_union_shop(1)
    elif shop.type == ShopInfo.GOODS_TYPE_ARENA:
        #消耗演武场代币
        arena = data.arena.get()
        if not arena.cost_coin(goods.get_real_price()):
            return False
    elif shop.type == ShopInfo.GOODS_TYPE_SOUL_SOUL:
        #消耗精魄
        if not resource.cost_soul(goods.get_real_price()):
            return False
        trainer.add_daily_buy_goods_in_soul_shop(1)
    elif shop.type == ShopInfo.GOODS_TYPE_SOUL_GOLD:
        #消耗元宝
        if not resource.cost_gold(goods.get_real_price()):
            return False
        trainer.add_daily_buy_goods_in_soul_shop(1)
    else:
        logger.warning("Invalid shop type[type=%d]" % shop.type)
        return False

    #得到物品
    if not item_business.gain_item(data, [(goods.item_basic_id, goods.item_num)
                                          ], "shop", log_formater.SHOP):
        return False
    id = ItemInfo.generate_id(data.id, goods.item_basic_id)
    item = data.item_list.get(id)
    if shop.type == ShopInfo.GOODS_TYPE_GOLD:
        log = log_formater.output_gold(data,
                                       -goods.get_real_price(),
                                       log_formater.BUY_GOODS,
                                       "Buy goods by gold",
                                       before_gold=original_gold,
                                       items_id=[goods.item_basic_id],
                                       items_num=[goods.item_num])
        logger.notice(log)

    return True
Beispiel #29
0
def choose_card(data, choose_index, cost_gold):
    """翻牌
    """
    pray = data.pray.get()
    #消耗祈福令
    cost_item = pray.calc_choose_card_use_item()
    id = ItemInfo.generate_id(data.id, cost_item[0])
    item = data.item_list.get(id)
    if cost_item[1] != 0 and item == None and cost_gold == 0:
        logger.warning("Pray item and gold error")
        return False
    if cost_item[1] != 0:
        need_gold = 0
        output_items = []
        if item == None:
            need_gold = cost_item[1] * int(
                float(
                    data_loader.OtherBasicInfo_dict["ItemPrayGoldCost"].value))
        elif cost_item[1] > item.num:
            need_gold = (cost_item[1] - item.num) * int(
                float(
                    data_loader.OtherBasicInfo_dict["ItemPrayGoldCost"].value))
            consume = item.consume(item.num)
            output_items.append("[item=")
            output_items.append(utils.join_to_string(list(consume[1])))
            output_items.append("]")
        else:
            consume = item.consume(cost_item[1])
            output_items.append("[item=")
            output_items.append(utils.join_to_string(list(consume[1])))
            output_items.append("]")
        log = log_formater.output_item(data, "choose card",
                                       log_formater.CHOOSE_CARD,
                                       ''.join(output_items))
        logger.notice(log)
        if need_gold != cost_gold:
            logger.warning(
                "choose card gold cost is error[need_gold=%d][cost_gold=%d]" %
                (need_gold, cost_gold))
            return False

        resource = data.resource.get()
        original_gold = resource.gold
        if need_gold != 0 and not resource.cost_gold(need_gold):
            logger.warning("not enough gold[need_gold=%d][has_gold=%d]" %
                           (need_gold, resource.gold))
            return False
        log = log_formater.output_gold(data,
                                       -need_gold,
                                       log_formater.CHOOSE_CARD,
                                       "Choose card by gold ",
                                       before_gold=original_gold)
        logger.notice(log)

    #翻牌
    get_item = pray.choose_card(choose_index)
    if get_item is None:
        return False
    if not PrayInfo.is_item_pray_multi(get_item[0]):
        id = ItemInfo.generate_id(data.id, get_item[0])
        item = data.item_list.get(id)
        #if item == None:
        items = []
        items.append(get_item)
        item_business.gain_item(data, items, "choose card",
                                log_formater.CHOOSE_CARD)
        #else:
        #    item.acquire(get_item[1])

    #统计
    trainer = data.trainer.get()
    trainer.add_daily_choose_card_num(1)

    return True