Ejemplo n.º 1
0
 def skill_up(self, msgtype, body):
     req = poem_pb.SkillUpRequest()
     req.ParseFromString(body)
     error = fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     p = self.player
     pet = p.pets.get(req.petID)
     if not pet:
         return error
     configs = get_config(PetLevelOrSkillLevelUpConfig)
     skill_level = getattr(pet, "skill%d" % req.skill, None)
     if skill_level is None:
         return error
     count = req.count or 1
     if skill_level + count > pet.level:
         return error
     cost = {}
     for l in range(skill_level, skill_level + count):
         config = configs[l]
         combine_reward([getattr(config, "skill%d_cost" % req.skill, {})],
                        [], cost)
         cost["skillpoint"] = cost.setdefault("skillpoint", 0) + 1
     try:
         apply_reward(p, {}, cost, type=RewardType.PetSkillUp)
     except AttrNotEnoughError:
         return error
     setattr(pet, "skill%d" % req.skill, skill_level + count)
     from task.manager import on_skillup
     on_skillup(p, count)
     # p.update_power()
     pet.save()
     pet.sync()
     p.save()
     p.sync()
     return success_msg(msgtype, "")
Ejemplo n.º 2
0
def uproar_reward_in_campaign(must=None, drop=None):
    config = g_campaignManager.uproar_campaign.get_current()
    result = {}
    if not must:
        must = {}
    else:
        must = dict(must)
    if not drop:
        drop = {}
    else:
        drop = dict(drop)
    if not config:
        result = drop
        result.update(must)
        return drop
    cmoney, cjiutian, cdrop = str(config.group)
    cmoney = int(cmoney)
    cjiutian = int(cjiutian)
    cdrop = int(cdrop)
    if must.get("money"):
        must["money"] *= cmoney
    if must.get("jiutian"):
        must["jiutian"] *= cjiutian
    result.update(must)
    for i in range(cdrop):
        combine_reward(drop, [], data=result)
    return result
Ejemplo n.º 3
0
 def breed(self, msgtype, body):
     from protocol.poem_pb import BreedRequest
     req = BreedRequest()
     req.ParseFromString(body)
     player = self.player
     from entity.manager import save_guide
     save_guide(player, req.guide_type)  # 保存新手引导进度
     c = req.count or 1
     pet = player.pets.get(req.petID)
     if not pet:
         return fail_msg(msgtype, reason='精灵不存在')
     if pet.level + c > pet.max_level:
         return fail_msg(msgtype, reason='超过最大等级')
     # info = get_config(PetConfig)[pet.prototypeID]
     # money, soul = breed_cost(info.cexp, pet.level, pet.level + c)
     cost = {}
     for level in range(pet.level, pet.level + c):
         linfo = get_config(PetLevelOrSkillLevelUpConfig)[level]
         combine_reward([linfo.units_cost1, linfo.units_cost2], {},
                        data=cost)
     try:
         apply_reward(player, None, cost=cost, type=RewardType.BreedPet)
     except AttrNotEnoughError:
         return fail_msg(msgtype, reason="金币或水晶不足")
     pet.level += c
     pet.save()
     from task.manager import on_breed
     on_breed(player, pet)
     # player.update_power()
     player.save()
     pet.sync()
     player.sync()
     return success_msg(msgtype, '')
Ejemplo n.º 4
0
Archivo: dlc.py Proyecto: kimch2/x8623
def apply_dlc_reward(fbID, reward=None, isfirst=False):
    if not reward:
        reward = {}
    config = get_config(DlcFbInfoConfig).get(fbID)
    if not config:
        return reward
    if isfirst:
        reward = combine_reward(reward, config.first_rewards)
    return combine_reward(reward, config.rewards)
Ejemplo n.º 5
0
 def maze_step(self, msgtype, body):
     p = self.player
     req = poem_pb.MazeStepRequest()
     req.ParseFromString(body)
     count = p.maze_rest_count if req.onekey else 1
     # check count
     if count > p.maze_rest_count:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     gains = {}
     attr = {}
     mazes = []
     incr = {}
     results = step_mazes(p, attr, incr, count)
     count = len(results)
     rsp = poem_pb.MazeStepResponse()
     for each in results:
         drop = each.get("drop", 0)
         if drop:
             maze_drop = open_reward(RewardType.MazeDrop, drop)
             rewards = maze_drop.apply_after()
             gains = combine_reward(rewards, {}, data=gains)
         if each.get("append", False):
             mazes.append(each)
         drop = get_cons_value("MazeMustDropID")
         must_drop = open_reward(RewardType.MazeDrop, drop)
         rewards = must_drop.apply_after()
         gains = combine_reward(rewards, {}, data=gains)
         rsp.events.add(**each)
     rsp.rewards = build_reward(gains)
     for each in mazes:
         p.mazes.append(each)
     apply_reward(p, gains, type=RewardType.MazeDrop)
     for each, value in attr.items():
         setattr(p, each, value)
     for each, value in incr.items():
         setattr(p, each, getattr(p, each) + value)
     if "mall_silver_open_remain" in attr:
         try:
             del p.malls[MallType.Silver]
         except KeyError:
             pass
     if "mall_golden_open_remain" in attr:
         try:
             del p.malls[MallType.Golden]
         except KeyError:
             pass
     p.touch_mazes()
     p.maze_step_count += count
     on_maze_count(p, count)
     p.save()
     p.sync()
     return success_msg(msgtype, rsp)
Ejemplo n.º 6
0
def advance_equip(p, petID, equipID, equips):
    pet = p.pets.get(petID)
    if not pet:
        return msgTips.FAIL_MSG_INVALID_REQUEST
    equip = get_or_create_equip(p, pet, equipID)
    if not equip:
        return msgTips.FAIL_MSG_INVALID_REQUEST
    equip_config = get_config(NewEquipConfig).get(equip.prototypeID)
    if not equip_config:
        return msgTips.FAIL_MSG_INVALID_REQUEST
    binding = p.equipeds.get(equip.entityID)
    if petID != binding:
        return msgTips.FAIL_MSG_INVALID_REQUEST
    advance_configs = get_config(EquipAdvanceConfig)
    advance_config = advance_configs.get(equip.step)
    if equip.step + 1 > max(advance_configs):
        return msgTips.FAIL_MSG_INVALID_REQUEST
    # 宠物必须满足等级要求
    if pet.level < advance_config.level:
        return msgTips.FAIL_MSG_INVALID_REQUEST
    advance_cost_config = get_config(EquipAdvanceCostConfig).get(
        equip_config.gup_id)
    if not advance_cost_config:
        return msgTips.FAIL_MSG_INVALID_REQUEST
    cost = parse_reward(advance_cost_config.costs[equip.step - 1])
    combine_reward({"money": advance_config.money}, {}, data=cost)
    equipList = sorted([i[0] for i in cost.pop("equipList", [])])
    try:  # 扣除装备,宠物 TODO
        equips = [p.equips[i] for i in equips]
        equips_prototypeID = sorted([i.prototypeID for i in equips])
        if len(equips_prototypeID) != len(equipList):
            raise KeyError
        for i in range(len(equips_prototypeID)):
            if equips_prototypeID[i] != equipList[i]:
                raise KeyError
        apply_reward(p, {}, cost, type=RewardType.EquipAdvance)
        p.del_equips(*equips)
    except KeyError:
        return msgTips.FAIL_MSG_INVALID_REQUEST
    except (AttrNotEnoughError or MatNotEnoughError):
        return msgTips.FAIL_MSG_INVALID_REQUEST
    equip.step += 1
    from task.manager import on_advance_equip
    on_advance_equip(p, equip)
    update_ranking_equip(p, equip)
    equip.save()
    equip.sync()
    p.save()
    p.sync()
    return SUCCESS
Ejemplo n.º 7
0
 def trigger_chest_recv(self, msgtype, body):
     p = self.player
     if not check_trigger_event_type(p, EventType.Chest):
         return fail_msg(msgtype, reason="无触发事件或错误的事件类型")
     req = poem_pb.TriggerChestRecvRequest()
     req.ParseFromString(body)
     config = get_config(TriggerEventConfig)[p.trigger_event]
     chest = get_config(TriggerChestConfig).get(config.event_param)
     if not chest:
         return fail_msg(msgtype, reason="不存在的宝箱")
     if req.is_double:
         cost = {"gold": get_cons_value("TriggerChestDoubleCost")}
         gain = {}
         for i in range(get_cons_value("TriggerChestMultiple")):
             gain = combine_reward([chest.reward], [], data=gain)
     else:
         cost = {}
         gain = parse_reward([chest.reward])
     try:
         apply_reward(p, gain, cost=cost, type=RewardType.TriggerChest)
     except AttrNotEnoughError:
         return fail_msg(msgtype, reason="钻石不足")
     p.trigger_event = 0
     p.save()
     p.sync()
     rsp = poem_pb.TriggerChestRecv()
     build_reward_msg(rsp, gain)
     return success_msg(msgtype, rsp)
Ejemplo n.º 8
0
def visit(p, count):
    gain = {}
    cost = {}
    configs = get_config(VisitConfig)
    incr_groups = get_config(VisitIncrByGroupConfig)
    choices = []
    campaign = g_campaignManager.visit_campaign
    campaign_opened = campaign.is_open()
    luck = {}
    for i in range(count):
        weighted_samples = []
        rewards = None
        for k, config in configs.items():
            if config.flag and campaign_opened:
                current = campaign.get_current()
                incr_configs = incr_groups.get(current.reward_group)
                VISIT_COUNT = incr_visit_flag()
                for incr_config in incr_configs:
                    if VISIT_COUNT % incr_config.count == 0:
                        choice = incr_config
                        reward = open_reward(RewardType.Visit, choice.drop)
                        rewards = reward.apply_after()
                        combine_reward(rewards, {}, data=luck)
                        break
                if rewards:
                    break
            else:
                weighted_samples.append([config, config.prob])
        if not rewards:
            choice = weighted_random2(weighted_samples)
            rewards = choice.rewards
            choices.append(choice.id)
        gain_pious = {"pious": 1}
        gain = combine_reward(rewards, gain_pious, data=gain)
    if p.visit_free_rest_count < count:
        count = count - p.visit_free_rest_count
        if p.dream:
            cost["dream"] = min(p.dream, count)
            count -= cost["dream"]
        if count:
            cost["gold"] = p.visit_cost * count
    return gain, cost, choices, luck
Ejemplo n.º 9
0
 def city_contend_drop_event(self, msgtype, body):
     p = self.player
     if not p.factionID:
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_HAS_NOT_FACTION)
     if not g_campaignManager.city_contend_campaign.is_open():
         return fail_msg(msgtype, msgTips.FAIL_MSG_CITY_CAMPAIGN_CLOSED)
     if not g_cityContend.check_event(p, CityContendEventType.Drop):
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     event = g_cityContend.get_current_step(p)
     if g_cityContend.is_top_faction(p.factionID):
         result = open_reward(RewardType.CityContend, event["argv"])
     else:
         result = open_reward(RewardType.CityContend, event["argv"])
     rewards = result.apply(p)
     rsp = poem_pb.CityContendDropEventResponse()
     combine_reward(rewards, {}, p.city_contend_rewards)
     rsp.rewards = build_reward(p.city_contend_rewards)
     p.city_contend_step += 1
     p.city_contend_total_step += 1
     p.save()
     p.sync()
     return success_msg(msgtype, rsp)
Ejemplo n.º 10
0
 def treasure_end(self, msgtype, body):
     p = self.player
     req = poem_pb.EndTreasure()
     req.ParseFromString(body)
     if not PlayerTreasureLock.unlock(p.entityID, req.verify_code):
         logger.debug("verify_code %s", req.verify_code)
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     if not p.treasure_cache:
         logger.debug("not treasure_cache")
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     rewards = []
     for type, subtype, count in p.treasure_cache:
         if type == TreasureGrid.TreasureGridTypeReward:
             rewards.append(poem_pb.RewardData(
                 type=subtype, count=count))
     r1 = parse_reward(req.rewards)
     r2 = parse_reward(rewards)
     logger.debug("reward %r %r", r1, r2)
     if not compare_reward(r1, r2):
         logger.debug("compare reward fail")
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     config = get_config(TreasureChestConfig)[p.treasure_type]
     gain_chest = bool(req.gain_chest)
     if gain_chest:
         reward = open_reward(RewardType.Treasure, config.drop)
         result = reward.apply_after()
     else:
         result = {}
     result = combine_reward(r1, result)
     rsp = poem_pb.EndTreasureResponse()
     finisheds = []
     finisheds.append(gain_chest)
     finisheds.append(bool(req.kill_monster))
     need = get_cons_value("TreasureNeedBuffCount")
     finisheds.append(len(req.rewards) >= need)
     rsp.stars = len(filter(lambda s: s, finisheds))
     if rsp.stars == len(finisheds):
         rewardex = open_reward(RewardType.Treasure, config.dropex)
         rsp.rewardsex = build_reward(rewardex.apply(p))
     rsp.finisheds = finisheds
     apply_reward(p, result, type=RewardType.Treasure)
     build_reward_msg(rsp, result)
     now = int(time.time())
     p.treasure_used_count += 1
     p.treasure_cd = now + 10 * 60
     p.treasure_cache = []
     refresh_treasure(p)
     on_treasure_count(p)
     p.save()
     p.sync()
     return success_msg(msgtype, rsp)
Ejemplo n.º 11
0
def cleanfbs(p, fbID, count, cost):
    assert count > 0
    items = []
    rewards = {}
    useless = poem_pb.EnterFbResponse()
    # cost_ = dict(cost)
    # cost.clear()
    for i in range(count):
        item = poem_pb.CleanFbRspStruct()
        set_fb_score(p, fbID, 3)
        item.curFbInfo = poem_pb.FbInfo(**get_fb_info(p, fbID))
        reward = open_reward(RewardType.FB, p, fbID, False, useless)
        result = filter_cleanfb_reward(reward)
        item.rewards = build_reward(result)
        rewards = combine_reward(rewards, result)
        # combine_reward(cost_, [], cost)
        items.append(item)
    apply_reward(p, rewards, cost=cost, type=RewardType.CleanFB)
    p.save()
    p.sync()
    return items
Ejemplo n.º 12
0
Archivo: rank.py Proyecto: kimch2/x8623
 def give_reward(self, season_key, player=None):
     logger.info('Give reward {}'.format(season_key))
     hist = self.get_hist(season_key)
     if not hist:
         return
     ranks, configs = hist["ranks"], hist["configs"]
     if player:
         players = [player]
     else:
         players = g_entityManager.players.values()
     for p in players:
         rank = ranks.get(p.entityID)
         if not rank:
             continue
         title = ""
         content = ""
         rewards = {}
         for i in sorted(rank.get("rewards", []), reverse=True):
             title = configs[i]["title"]
             content = configs[i]["content"]
             rewards = combine_reward(rewards, configs[i]["rewards"])
         if rewards:
             grad = rank.get("grad", 0)
             self.send_mail(p, title, content, rewards, grad, season_key)
Ejemplo n.º 13
0
 def battle(self, p, targetID, fight, raw, rsp):
     target_win_count = 0  # 对手连胜次数
     max_win_count = 0
     history = None  # 战斗记录
     shutdown = False
     self_message = ""
     full_message = ""
     horn = False
     red_message = ""
     red_count = 0
     self_shutdown_message = ""
     full_shutdown_message = ""
     peer_shutdown_message = ""
     count = 0
     rsp.before_daily_win_count = p.daily_win_count
     if fight.fightResult:  # 胜利
         # 终结对手连胜
         target_win_count = int(self.pool.execute(
             "GETSET", "daily_win_count_p{%d}" % targetID, 0) or 0)
         self.pool.execute("SET", "daily_dead_p{%d}" % targetID, 1)
         # 添加自己连胜
         daily_win_count = int(self.pool.execute(
             "INCRBY", "daily_win_count_p{%d}" % p.entityID, 1) or 0)
         p.clear_daily_win_count()
         # 更新最大连胜次数
         if p.daily_win_count > p.daily_max_win_count:
             p.daily_max_win_count = p.daily_win_count
             count = update_daily_rank(
                 PlayerDailyRankRanking, p.entityID, p.daily_max_win_count)
             # PlayerDailyRankRanking.update_score(
             #     p.entityID, p.daily_max_win_count)
             # 连胜任务
             from task.manager import on_dailypvp_count
             on_dailypvp_count(p, p.daily_max_win_count)
             # 取全服最大次数
             top = PlayerDailyRankRanking.get_range_by_score(
                 "-inf", "+inf", withscores=True, count=1)
             if top:
                 max_win_count = top[1]
             rsp.max_win_count = max_win_count
         daily_win_config = get_config(DailyWinConfig).get(
             p.daily_win_count)
         if not daily_win_config and \
                 p.daily_win_count > max(get_config(DailyWinConfig)):
             daily_win_config = get_config(
                 DailyWinConfig)[max(get_config(DailyWinConfig))]
         if daily_win_config:
             if not daily_win_config.multiple or (
                     daily_win_config.multiple and count == 1):
                 self_message = daily_win_config.single_desc
                 full_message = daily_win_config.all_desc
                 horn = daily_win_config.horn
                 if daily_win_config.red_paper:
                     red_message = daily_win_config.red_paper_desc
                     red_count = daily_win_config.red_paper_count
                     red_drop = daily_win_config.red_paper
         daily_lose_config = get_config(DailyLoseConfig).get(
             target_win_count)
         if not daily_lose_config and \
                 target_win_count > max(get_config(DailyLoseConfig)):
             daily_lose_config = get_config(
                 DailyLoseConfig)[max(get_config(DailyLoseConfig))]
         if daily_lose_config:
             self_shutdown_message = daily_lose_config.single_win_desc
             peer_shutdown_message = daily_lose_config.single_lose_desc
             full_shutdown_message = daily_lose_config.all_desc
         # 增加胜利次数
         p.daily_kill_count += 1
         # 奖励加成系数
         multi = min(40, 2 * daily_win_count) + min(
             80, target_win_count * 4)
         shutdown = target_win_count > 2
         history = {
             "active": False, "name": p.name,
             "win": not fight.fightResult,
             "faction_name": p.faction_name,
             "daily_win_count": p.daily_win_count,
             "fight": raw.encode("base64"),
             "prototypeID": p.prototypeID,
             "borderID": p.borderID,
             "shutdown": shutdown}
         for each in fight.player_team:
             pet = p.pets[each.entityID]
             if each.restHP == 0:
                 pet.daily_dead = True
             else:
                 pet.daily_restHP = each.restHP
             pet.save()
             pet.sync()
     else:
         if not p.daily_rank:
             PlayerDailyRankRanking.update_score(
                 p.entityID, p.daily_max_win_count)
         # 自己连胜被终结
         daily_win_count = int(self.pool.execute(
             "GETSET", "daily_win_count_p{%d}" % p.entityID, 0) or 0)
         # 死亡
         self.pool.execute("SET", "daily_dead_p{%d}" % p.entityID, 1)
         p.clear_daily_win_count()
         # 奖励加成系数
         multi = 0
         daily_lose_config = get_config(DailyLoseConfig).get(
             daily_win_count)
         if not daily_lose_config and \
                 daily_win_count > max(get_config(DailyLoseConfig)):
             daily_lose_config = get_config(
                 DailyLoseConfig)[max(get_config(DailyLoseConfig))]
         if daily_lose_config:
             self_shutdown_message = daily_lose_config.single_lose_desc
             peer_shutdown_message = daily_lose_config.single_win_desc
             full_shutdown_message = daily_lose_config.all_desc
     # 取对手数据
     data = g_entityManager.get_players_info(
         [targetID], [
             "entityID", "name", "daily_win_count",
             "faction_name", "prototypeID", "borderID"])[0]
     # 终结连胜
     shutdown = target_win_count > 2
     data.update({
         "active": True, "shutdown": shutdown,
         "win": fight.fightResult,
         "fight": raw.encode("base64")
     })
     # 自己的战斗记录
     p.daily_histories.appendleft(data)
     p.daily_histories.ltrim(0, MAX_HIST_LEN - 1)
     # 更新排名
     p.daily_rank = PlayerDailyRankRanking.get_rank(p.entityID)
     rewards = {}
     reward = open_reward(
         RewardType.DailyPVP, get_cons_value("DailyPVPDrop"))
     rewards = reward.apply_after()
     # 奖励加成
     if multi:
         for k, v in rewards.items():
             if isinstance(v, int) and k != 'exp':
                 rewards[k] = int(v * (100 + multi) / float(100))
     # 记录累计奖励
     apply_reward(p, rewards, type=RewardType.DailyPVP)
     combine_reward(rewards, [], data=p.daily_rewards)
     p.daily_rewards = dict(p.daily_rewards)
     p.daily_count += 1
     p.daily_cache_targetID = 0
     p.save()
     p.sync()
     # 添加直播
     self.add_live({
         "self_name": p.name,
         "self_prototypeID": p.prototypeID,
         "self_borderID": p.borderID,
         "peer_name": data["name"],
         "peer_prototypeID": data["prototypeID"],
         "peer_borderID": data["borderID"],
         "is_win": fight.fightResult,
     }, top=p.daily_rank and p.daily_rank <= 5)
     rsp.daily_win_count = p.daily_win_count
     rsp.rewards = build_reward(rewards)
     if self_message:
         self_message = self_message.format(data["name"], p.daily_win_count)
         g_redManager.send_red_message(
             p, self_message, to_self=True, type=RedType.Normal)
     if full_message:
         full_message = full_message.format(
             p.name, data["name"], p.daily_win_count)
         _type = RedType.Horn if horn else RedType.Normal
         g_redManager.send_red_message(
             p, full_message, type=_type)
     if red_count and red_message:
         if daily_win_count == 1:
             red_message = red_message.format(
                 p.name, red_count)
         else:
             red_message = red_message.format(
                 p.name, daily_win_count, red_count)
         g_redManager.send_red_message(
             p, red_message, red_drop=red_drop,
             red_count=red_count, type=RedType.Red)
     if full_shutdown_message:
         if fight.fightResult:
             full_shutdown_message = full_shutdown_message.format(
                 p.name, data["name"], target_win_count)
         else:
             full_shutdown_message = full_shutdown_message.format(
                 data["name"], p.name, daily_win_count)
         _type = RedType.Horn if horn else RedType.Normal
         g_redManager.send_red_message(
             p, full_shutdown_message, type=_type)
     if fight.fightResult:
         if self_shutdown_message:
             self_shutdown_message = self_shutdown_message.format(
                 data["name"], target_win_count)
             g_redManager.send_red_message(
                 p.entityID, self_shutdown_message,
                 to_self=True, type=RedType.Normal)
         if peer_shutdown_message:
             peer_shutdown_message = peer_shutdown_message.format(
                 p.name, target_win_count)
             g_redManager.send_red_message(
                 data["entityID"], peer_shutdown_message,
                 to_self=True, type=RedType.Normal)
     else:
         if self_shutdown_message:
             self_shutdown_message = self_shutdown_message.format(
                 data["name"], daily_win_count)
             g_redManager.send_red_message(
                 p.entityID, self_shutdown_message,
                 to_self=True, type=RedType.Normal)
         if peer_shutdown_message:
             peer_shutdown_message = peer_shutdown_message.format(
                 p.name, daily_win_count)
             g_redManager.send_red_message(
                 data["entityID"], peer_shutdown_message,
                 to_self=True, type=RedType.Normal)
     proxy.sync_daily_rank(targetID, history)
     return rewards
Ejemplo n.º 14
0
Archivo: city.py Proyecto: kimch2/x8623
 def battle(self, p, fight, rsp):
     treasures = get_config(CityTreasureConfig)
     self_message = ""
     full_message = ""
     red_message = ""
     red_count = 0
     horn = False
     target = p.city_contend_cache_target
     if self.is_top_faction(p.factionID):
         message_configs = get_config(CityContendDefendMessageConfig)
         message_config = message_configs.get(p.city_contend_count)
         if not message_config:
             message_config = message_configs[max(message_configs)]
         if fight.fightResult:
             event = self.get_current_step(p)
             drop = event["argv"]
             reward = open_reward(RewardType.CityContendDefend, drop)
             rewards = reward.apply(p)
             combine_reward(rewards, {}, p.city_contend_rewards)
             try:
                 target_name = target.get("name", u"").decode("utf-8")
                 target_faction_name = (target.get(
                     "faction_name", u"") or u"").decode("utf-8")
             except UnicodeEncodeError:
                 target_name = target.get("name", u"")
                 target_faction_name = target.get("faction_name", u"")
             self_message = message_config.single_defend_win_desc.format(
                 target_faction_name, target_name
             )
             # {{ 使用每日PVP
             for each in fight.player_team:
                 pet = p.pets[each.entityID]
                 if each.restHP == 0:
                     pet.daily_dead = True
                 else:
                     pet.daily_restHP = each.restHP
                 pet.save()
                 pet.sync()
             # }}
             rsp.rewards = build_reward(rewards)
         else:
             sub = p.city_contend_treasure * get_cons_value(
                 "CityContendFailPunish") / float(100)
             p.city_contend_treasure = max(
                 p.city_contend_treasure - sub, 1)
             # {{ 每日PVP
             now = int(time.time())
             p.daily_dead_cd = now + get_cons_value("DailyDeadCD")
             # }}
             try:
                 target_name = target.get("name", u"").decode("utf-8")
                 target_faction_name = (target.get(
                     "faction_name", u"") or u"").decode("utf-8")
             except UnicodeEncodeError:
                 target_name = target.get("name", u"")
                 target_faction_name = target.get("faction_name", u"")
             self_message = message_config.single_defend_lose_desc.format(
                 target_faction_name, target_name
             )
         module = RedModuleType.CityContendDefend
     else:
         message_configs = get_config(CityContendAttackMessageConfig)
         message_config = message_configs.get(p.city_contend_count + 1)
         if not message_config:
             message_config = message_configs[max(message_configs)]
         if fight.fightResult:
             p.city_contend_count += 1
             self_count = CityContendAttackRanking.update_score(
                 p.entityID, p.city_contend_count)
             count = CityContendAttackRanking.pool.execute(
                 "ZCOUNT", CityContendAttackRanking.key, self_count, "+inf")
             CityContendFactionRanking.incr_score(
                 p.factionID, 1)
             treasure = treasures.get(
                 p.city_contend_cache_target.get("level", 1))
             if not treasure:
                 treasure = treasures[max(treasures)]
             money = treasure.attack_treasure * get_cons_value(
                 "CityContendAttackMoney")
             soul = treasure.attack_treasure * get_cons_value(
                 "CityContendAttackSoul")
             event = self.get_current_step(p)
             drop = event["argv"]
             gain = {"money": money, "soul": soul}
             reward = open_reward(
                 RewardType.CityContendAttack, drop
             )
             drop_reward = reward.apply_after()
             total_reward = apply_reward(
                 p, combine_reward(gain, drop_reward),
                 type=RewardType.CityContendAttack)
             combine_reward(total_reward, {}, p.city_contend_rewards)
             p.city_contend_total_treasure += treasure.attack_treasure
             rsp.rewards = build_reward(drop_reward)
             rsp.treasure_rewards = build_reward(gain)
             rsp.treasure_count = treasure.attack_treasure
             if not message_config.multiple1 or message_config.multiple1 \
                     and count == 1:
                 full_message = message_config.attack_count_desc.format(
                     p.faction_name, p.name, p.city_contend_count
                 )
                 horn = message_config.horn1
             try:
                 target_name = target.get("name", u"").decode("utf-8")
             except UnicodeEncodeError:
                 target_name = target.get("name", u"")
             self_message = message_config.single_attack_win_desc.format(
                 target_name
             )
             if not message_config.multiple2 or message_config.multiple2 \
                     and count == 1:
                 red_count = message_config.red_paper_count
                 red_drop = message_config.red_paper
                 red_message = message_config.red_paper_desc.format(
                     p.faction_name, p.name,
                     p.city_contend_count, red_count
                 )
             # {{ 使用每日PVP
             for each in fight.player_team:
                 pet = p.pets[each.entityID]
                 if each.restHP == 0:
                     pet.daily_dead = True
                 else:
                     pet.daily_restHP = each.restHP
                 pet.save()
                 pet.sync()
             # }}
         else:
             # {{ 每日PVP
             now = int(time.time())
             p.daily_dead_cd = now + get_cons_value("DailyDeadCD")
             # }}
             # FIXME
             try:
                 target_name = target.get("name", u"").decode("utf-8")
             except UnicodeEncodeError:
                 target_name = target.get("name", u"")
             self_message = message_config.single_attack_lose_desc.format(
                 target_name
             )
         module = RedModuleType.CityContendAttack
     if self_message:
         g_redManager.send_red_message(
             p, self_message,
             to_self=True,
             module=module)
     if full_message:
         _type = RedType.Horn if horn else RedType.Normal
         g_redManager.send_red_message(
             p, full_message, type=_type,
             module=module)
     if red_message and red_count:
         g_redManager.send_red_message(
             p, red_message, red_drop=red_drop,
             red_count=red_count, type=RedType.Red,
             module=module)
     p.save()
     p.sync()
Ejemplo n.º 15
0
Archivo: city.py Proyecto: kimch2/x8623
 def battle(self, p, fight, rsp):
     mg = p.city_dungeon_mg_cache
     message_configs = get_config(CityDungeonMessageConfig)
     self_message = ""
     message_config = message_configs.get(mg["id"])
     if not message_config:
         message_config = message_configs[max(message_configs)]
     if fight.fightResult:
         kills = len(mg.get("monsters", []))
         config = self.get_mg_config_by_id(mg["id"])
         rewards = parse_reward(config.rewards)
         self_message = message_config.single_win_desc.format(mg["id"])
         # 玩家损血
         # {{ 使用每日PVP
         for each in fight.player_team:
             pet = p.pets[each.entityID]
             if each.restHP == 0:
                 pet.daily_dead = True
             else:
                 pet.daily_restHP = each.restHP
             pet.save()
             pet.sync()
         # }}
     else:
         kills = 0
         pending = []
         for enemy in fight.enemy_team:
             for m in mg["monsters"]:
                 if m["pos"] == enemy.posIndex:
                     if not enemy.restHP:
                         pending.append(m)
                         kills += 1
                     else:
                         m["restHP"] = enemy.restHP
         for m in pending:
             mg["monsters"].remove(m)
         self.add_mg_into_pool(p, mg)
         now = int(time.time())
         # {{ 使用每日PVP
         p.daily_dead_cd = now + get_cons_value("DailyDeadCD")
         # }}
         rewards = {}
         self_message = message_config.single_lose_desc.format(mg["id"])
     if fight.total_damage:
         CityDungeonSelfRanking.incr_score(
             p.entityID, fight.total_damage)
     if kills:
         self.incr_mg_kill(p, mg["id"], kills)
         if fight.fightResult:
             self.sync_city_dungeon_current_info(p)
     if rewards:
         rewards = combine_reward(
             rewards, config.must_rewards)
         rewards = apply_reward(
             p, rewards, type=RewardType.CityDungeon)
         build_reward_msg(rsp, rewards)
         combine_reward(rewards, {}, p.city_dungeon_rewards)
     if self_message:
         g_redManager.send_red_message(
             p, self_message, to_self=True,
             module=RedModuleType.CityDungeon)
     p.city_dungeon_mg_cache.clear()
     p.save()
     p.sync()
Ejemplo n.º 16
0
    def refining(self, msgtype, body):
        from lineup.manager import in_lineup
        from config.configs import get_config
        from config.configs import RefineryConfig
        req = poem_pb.RefiningRequest()
        req.ParseFromString(body)
        player = self.player
        from entity.manager import save_guide
        save_guide(player, req.guide_type)  # 保存新手引导进度

        # 统计材料的种类和数量
        total_mat = 0
        mats = {}
        for matInfo in req.materials:
            total_mat += 1
            if matInfo.id in mats:
                mats[matInfo.id] += matInfo.count
            else:
                mats[matInfo.id] = matInfo.count

        if len(req.pet_ids) + len(req.equip_ids) + total_mat > 6:
            return fail_msg(msgtype, reason='总共可以炼化6个精灵和装备')
        if len(req.pet_ids) != len(set(req.pet_ids)):
            return fail_msg(msgtype, reason='重复的精灵实体ID')
        if len(req.equip_ids) != len(set(req.equip_ids)):
            return fail_msg(msgtype, reason='重复的装备实体ID')
        refining_pet = []
        configs = get_config(RefineryConfig)
        rewards = {}
        for petID in req.pet_ids:
            pet = player.pets.get(petID)
            if not pet:
                return fail_msg(msgtype, reason='找不到精灵炼化')
            if in_lineup(player, pet.entityID) and \
                    not in_lineup(player, pet.entityID, type=LineupType.ATK):
                return fail_msg(msgtype, reason='阵上将不可作为材料')
            petInfo = get_config(PetConfig)[pet.prototypeID]
            if not petInfo:
                return fail_msg(msgtype, msgTips.FAIL_MSG_PET_NOTCONFIG)
            refinery = configs.get(petInfo.cls)
            if not refinery:
                return fail_msg(msgtype, msgTips.FAIL_MSG_PET_NOTCONFIG)
            addition_rewards = {}
            # 升级消耗
            level_configs = get_config(PetLevelOrSkillLevelUpConfig)
            level_configs = [level_configs[i] for i in filter(
                lambda s: s < pet.level, level_configs)]
            for each in level_configs:
                combine_reward(
                    [each.units_cost1, each.units_cost2],
                    {}, data=addition_rewards)
            # 技能消耗
            level_configs = get_config(PetLevelOrSkillLevelUpConfig)
            for l in [1, 2, 3, 4, 5]:
                slevel = getattr(pet, "skill%d" % l, 1)
                skilllevel_configs = [
                    level_configs[i] for i in filter(
                        lambda s: s < slevel, level_configs)]
                for each in skilllevel_configs:
                    combine_reward(
                        [getattr(each, "skill%d_cost" % l, {})],
                        {}, data=addition_rewards)
            # 升阶消耗
            step = petInfo.rarity * 10 + petInfo.step
            grow_configs = get_config(GrowthConfig)
            grow_configs = [grow_configs[i] for i in filter(
                lambda s: s < step, grow_configs)]
            for each in grow_configs:
                combine_reward(
                    {"money": int(each.evo_cost * petInfo.cexp)},
                    {}, data=addition_rewards)
            # 升星消耗
            break_configs = get_config(BreakConfig)
            break_configs = [break_configs[i] for i in filter(
                lambda s: s < pet.breaklevel, break_configs)]
            for each in break_configs:
                combine_reward(
                    {"money": each.money},
                    {}, data=addition_rewards)
            for k, v in addition_rewards.items():
                if isinstance(v, int):
                    addition_rewards[k] = int(v * refinery.scale)
            for i in range(pet.star // petInfo.need_patch):
                combine_reward(refinery.rewards, {}, data=rewards)
            combine_reward(addition_rewards, {}, data=rewards)
            refining_pet.append(pet)

        # 神将身上的装备
        equips = []
        for pet in refining_pet:
            for e in pet.equipeds.values():
                equips.append(player.equips[e])

        from config.configs import EquRefineConfig
        equ_refine_config = get_config(EquRefineConfig)

        # 单个分解的装备
        for equID in req.equip_ids:
            equ = player.equips[equID]
            if not equ:
                return fail_msg(msgtype, reason='找不到装备炼化')

            equips.append(equ)

            _equ_refine_config = equ_refine_config.get(equ.prototypeID)
            if not _equ_refine_config:
                return fail_msg(msgtype, msgTips.FAIL_MSG_PET_NOTCONFIG)

            combine_reward(_equ_refine_config.equ_rewards, {}, data=rewards)

        # 单个分解的材料
        matList = []
        for matID, count in mats.iteritems():
            mat1 = player.mats.get(matID, 0)
            if mat1 < count:
                return fail_msg(msgtype, reason='材料数量不足炼化')

            matList.append([matID, count])

            mat_refine_config = equ_refine_config.get(matID)
            if not mat_refine_config:
                return fail_msg(msgtype, msgTips.FAIL_MSG_PET_NOTCONFIG)

            for i in range(0, count):
                combine_reward(mat_refine_config.mat_rewards, {}, data=rewards)

        l = list(player.lineups.get(LineupType.ATK, [0, 0, 0, 0]))
        # 攻击阵型可以被炼化
        flag = False
        for each in refining_pet:
            if in_lineup(player, each.entityID, type=LineupType.ATK):
                flag = True
                l[l.index(each.entityID)] = 0
        if flag:
            save_lineup(player, l, LineupType.ATK)

        player.del_pets(*refining_pet)
        player.del_equips(*equips)
        apply_reward(player, rewards, cost={"matList": matList}, type=RewardType.REFINING)
        player.save()
        player.sync()
        rsp = poem_pb.RefiningResponse()
        build_reward_msg(rsp, rewards)
        logger.debug(rsp)
        return success_msg(msgtype, rsp)
Ejemplo n.º 17
0
    def mall_info(self, msgtype, body):
        p = self.player
        req = poem_pb.MallInfoRequest()
        req.ParseFromString(body)
        logger.debug(req)
        type = req.type
        if not check_open(p, type):
            # 限制
            return fail_msg(msgtype, reason="商店未开启")
        refresh_info = get_config(MallRefreshConfig)[type]
        times = p.mall_refresh_times.get(type, 0)
        now = int(time.time())
        need_refresh = not p.malls.get(type)
        if req.refresh:
            cost_amount = refresh_info.cost
            try:
                if p.shopping > 0:
                    cost = {"shopping": 1}
                else:
                    cost = parse_reward([{
                        'type': refresh_info.refresh_cost_type,
                        'count': cost_amount,
                    }])
                apply_reward(
                    p, {}, cost, type=RewardType.RefreshMall)
            except AttrNotEnoughError:
                return fail_msg(msgtype, reason="消耗不足")
            need_refresh = True
            # 增加刷新次数
            times += 1
            p.mall_refresh_times[type] = times
            from task.manager import on_refresh_shop
            on_refresh_shop(p)

            # 刷新商店的时候
            from campaign.manager import g_campaignManager
            if g_campaignManager.exchange_campaign.is_open():
                start_time, end_time = g_campaignManager.exchange_campaign.get_current_time()
                if p.exchange_campaign_last_time < start_time or p.exchange_campaign_last_time > end_time:
                    p.exchange_campaign_counter = 0
                p.exchange_campaign_counter = p.exchange_campaign_counter + 1
                p.exchange_campaign_last_time = now

                current = g_campaignManager.exchange_campaign.get_current()
                from config.configs import ExchangeCampaignByGroupConfig
                group = get_config(ExchangeCampaignByGroupConfig).get(current.group)

                ex_rsp = poem_pb.ExchangeCampaignItemResponse()

                rewards = {}
                for i in range(0, len(group.consumes)):
                    tmp_count = group.refresh_counts[i]
                    if not tmp_count or tmp_count <= 0:
                        continue

                    if p.exchange_campaign_counter % tmp_count == 0:
                        tmp_config = group.consumes[i]
                        print tmp_config
                        r = parse_reward([{
                            "arg": tmp_config["arg"],
                            "type": tmp_config["type"],
                            "count": 1,
                        }])
                        combine_reward(r, {}, rewards)

                        info = {}
                        info["arg"] = tmp_config["arg"]
                        info["type"] = tmp_config["type"]
                        info["count"] = 1
                        ex_rsp.items.add(**info)

                if len(rewards) > 0:
                    apply_reward(p, rewards, type=RewardType.RefreshMall)

                    from player.manager import g_playerManager
                    ex_msg = success_msg(msgid.EXCHANGE_CAMPAIGN_ITEM_RESULT, ex_rsp)
                    g_playerManager.sendto(p.entityID, ex_msg)

            if g_campaignManager.refresh_store_campaign.is_open():
                start_time, end_time = g_campaignManager.refresh_store_campaign.get_current_time()
                if p.refresh_store_campaign_last_time < start_time or p.refresh_store_campaign_last_time > end_time:
                    p.refresh_store_campaign_counter = 0
                p.refresh_store_campaign_counter = p.refresh_store_campaign_counter + 1
                p.refresh_store_campaign_last_time = now

                from config.configs import RefreshStoreConfig
                packs = get_config(RefreshStoreConfig)
                exempts = set(p.refresh_reward_end).union(p.refresh_reward_done)
                samples = sorted(set(packs).difference(exempts))
                for i in samples:
                    pack = packs[i]
                    if p.refresh_store_campaign_counter >= pack.count:
                        p.refresh_reward_done.add(i)
                    else:
                        break
                p.clear_refresh_reward_done_count()

        next = None
        dt = datetime.fromtimestamp(now)
        # NOTE 跨天问题
        last_ts = p.mall_last_refresh.get(type, 0)
        if not last_ts:
            need_refresh = True
            last_ts = now
        last = datetime.fromtimestamp(last_ts)
        logger.debug("上次刷新时间 %s", last)
        flag = False
        for date, daytimes in (
                [last.date(), refresh_info.daytimes],
                # 跨天不刷新
                [last.date() + timedelta(days=1), refresh_info.daytimes],
                [dt.date(), refresh_info.daytimes],
                [dt.date() + timedelta(days=1), refresh_info.daytimes]):
            for each in daytimes:
                refresh_dt = datetime.combine(date, timetime(each))
                if not flag and dt < refresh_dt:
                    next = refresh_dt
                    flag = True
                if last < refresh_dt and refresh_dt <= dt:
                    need_refresh = True
        # 临时商店不自动刷新
        if type == MallType.Golden:
            if now < p.mall_golden_open_remain:
                need_refresh = False or req.refresh
        elif type == MallType.Silver:
            if now < p.mall_silver_open_remain:
                need_refresh = False or req.refresh
        if need_refresh or not p.malls.get(type):
            refresh_mall(p, type)
            p.mall_last_refresh[type] = now
        mall = p.malls.get(type, [])
        configs = get_config(MallConfig)
        default_locked = (type == MallType.Faction)
        if default_locked:
            if p.factionID:
                mall_products = Faction.simple_load(
                    p.factionID, ['mall_products']).mall_products
        else:
            mall_products = set()
        unlock_costs = {type: {k: v.cost for k, v in get_config(
            FactionMallUnlockConfig).items()}}
        rsp = poem_pb.MallInfoResponse()
        for productID in mall:
            config = configs[productID]
            count = p.mall_limits.get(productID, 0)
            last = p.mall_times.get(productID, 0)
            remain = 0
            if last and config.cd:
                remain = max(config.cd - (now - last), 0)
            product = config._asdict()
            locked = default_locked and (config.pos not in mall_products)
            rsp.products.add(
                unlock_cost=unlock_costs.get(type, {}).get(config.pos, 0),
                count=count, remain=remain, locked=locked, **product)
        if next:
            rsp.time = next.hour
            rsp.cd = int(time.mktime(next.timetuple()) - now)
        else:
            # 不自动刷新
            rsp.time = 25
        logger.debug("下次刷新时间 %s", next)
        rsp.cost = refresh_info.cost
        rsp.cost_type = refresh_info.refresh_cost_type
        p.save()
        p.sync()
        return success_msg(msgtype, rsp)
Ejemplo n.º 18
0
    def mall_buy_product(self, msgtype, body):
        p = self.player
        req = poem_pb.MallBuyProduct()
        req.ParseFromString(body)
        logger.debug(req)
        config = get_config(MallConfig)[req.ID]
        if not check_open(p, config.type):
            return fail_msg(msgtype, reason="商店未开启")
        # 限制
        count = p.mall_limits.get(req.ID, 0)
        if config.limit > 0 and count >= config.limit:
            return fail_msg(msgtype, reason="超过购买次数")
        now = int(time.time())
        last = p.mall_times.get(req.ID, 0)
        if last and now < last + config.cd:
            return fail_msg(msgtype, reason="购买冷却中")
        reward = parse_reward([{
            'type': config.product_type,
            'arg': config.productID,
            'count': config.product_amount}])
        cost = parse_reward([{
            'type': config.item_type,
            'count': config.price,
        }])
        try:
            apply_reward(
                p, reward, cost,
                type=RewardType.MallBuy)
        except AttrNotEnoughError:
            return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)

        from campaign.manager import g_campaignManager
        if g_campaignManager.exchange_campaign.is_open():
            start_time, end_time = g_campaignManager.exchange_campaign.get_current_time()
            if p.exchange_campaign_last_time < start_time or p.exchange_campaign_last_time > end_time:
                p.exchange_campaign_counter = 0
            p.exchange_campaign_counter = p.exchange_campaign_counter + 1
            p.exchange_campaign_last_time = now

            current = g_campaignManager.exchange_campaign.get_current()
            from config.configs import ExchangeCampaignByGroupConfig
            group = get_config(ExchangeCampaignByGroupConfig).get(current.group)

            ex_rsp = poem_pb.ExchangeCampaignItemResponse()

            rewards = {}
            for i in range(0, len(group.consumes)):
                tmp_count = group.refresh_counts[i]
                if not tmp_count or tmp_count <= 0:
                    continue

                if p.exchange_campaign_counter % tmp_count == 0:
                    tmp_config = group.consumes[i]
                    print tmp_config
                    r = parse_reward([{
                        "arg": tmp_config["arg"],
                        "type": tmp_config["type"],
                        "count": 1,
                    }])
                    combine_reward(r, {}, rewards)

                    info = {}
                    info["arg"] = tmp_config["arg"]
                    info["type"] = tmp_config["type"]
                    info["count"] = 1
                    ex_rsp.items.add(**info)

            if len(rewards) > 0:
                apply_reward(p, rewards, type=RewardType.RefreshMall)

                from player.manager import g_playerManager
                ex_msg = success_msg(msgid.EXCHANGE_CAMPAIGN_ITEM_RESULT, ex_rsp)
                g_playerManager.sendto(p.entityID, ex_msg)

        #if g_campaignManager.refresh_store_campaign.is_open():
        #    start_time, end_time = g_campaignManager.refresh_store_campaign.get_current_time()
        #    if p.refresh_store_campaign_last_time < start_time or p.refresh_store_campaign_last_time > end_time:
        #        p.refresh_store_campaign_counter = 0
        #    p.refresh_store_campaign_counter = p.refresh_store_campaign_counter + 1
        #    p.refresh_store_campaign_last_time = now

        #    from config.configs import RefreshStoreConfig
        #    packs = get_config(RefreshStoreConfig)
        #    exempts = set(p.refresh_reward_end).union(p.refresh_reward_done)
        #    samples = sorted(set(packs).difference(exempts))
        #    for i in samples:
        #        pack = packs[i]
        #        if p.refresh_store_campaign_counter >= pack.count:
        #            p.refresh_reward_done.add(i)
        #        else:
        #            break
        #    p.clear_refresh_reward_done_count()

        p.mall_limits[req.ID] = count + 1
        p.mall_times[req.ID] = now
        from task.manager import on_shopping
        on_shopping(p)
        p.save()
        p.sync()
        return success_msg(msgtype, '')