def trigger_event(p): if p.trigger_packs_flag: return 0 prob = 0 triggers = get_config(TriggerAfterFbConfig) for tg in triggers: if p.trigger_event_sp >= tg.sp: prob = tg.trigger_event_prob else: break if not guess(prob): return 0 configs = { k: v for k, v in get_config(TriggerEventConfig).items() if p.level >= v.open_level } if not configs: return 0 logger.debug("trigger_event_sp: %r", p.trigger_event_sp) logger.debug("trigger event prob: %r", prob) ID = weighted_random2([[k, v.prob] for k, v in configs.items()]) config = configs[ID] logger.debug("%r", config) if config.event_type == EventType.Fb: logger.debug("EventType.Fb") if p.is_pets_full(): logger.debug("pet full") return 0 elif config.event_type == EventType.Chest: logger.debug("EventType.Chest") elif config.event_type == EventType.Chests: logger.debug("EventType.Chests") p.trigger_chests.clear() elif config.event_type == EventType.Store: logger.debug("EventType.Store") elif config.event_type == EventType.Task: logger.debug("EventType.Task") taskID = config.event_param if taskID in p.trigger_tasks: tasks = {} for k, v in configs.items(): if v.event_type == EventType.Task: tasks[k, v.event_param] = v.prob while tasks: ID, taskID = weighted_random2(tasks.items()) if taskID not in p.trigger_tasks: break del tasks[ID, taskID] if taskID in p.trigger_tasks: # 已经存在的任务,那么就不触发了 return 0 p.trigger_tasks.add(taskID) p.trigger_event_sp = 0 p.trigger_event = ID p.save() p.sync() return config.event_type
def enchant_equip(p, equipID, locks=None, ex=False): if not locks: locks = [] equip = p.equips[equipID] info = get_config(NewEquipConfig).get(equip.prototypeID) if not info: return advance_config = get_config(EquipAdvanceConfig).get(equip.step) if not advance_config: return configs = get_config(EnchantByQualityConfig) group = configs.get(advance_config.color) if not group: return if ex: prob = "gold_prob" else: prob = "prob" for index in range(equip.slugs): if index in locks: try: attr = equip.enchants[index] except IndexError: attr = info.enchID else: attr = weighted_random2([[i.ID, getattr(i, prob)] for i in group]) try: equip.enchants[index] = attr except IndexError: equip.enchants.append(attr) update_ranking_equip(p, equip) from task.manager import on_enhant_equip on_enhant_equip(p) equip.save() equip.sync()
def ambition_up(self, msgtype, body): p = self.player req = poem_pb.AmbitionUpRequest() req.ParseFromString(body) if not req.type: configs = get_config(AmbitionConfig) level = p.level ambition = str(p.ambition) or '' attr = "ambition" else: configs = get_config(VipAmbitionConfig) level = p.vip ambition = str(p.vip_ambition) or '' attr = "vip_ambition" index = req.index or 0 config = configs.get(index + 1) if not config: return fail_msg(msgtype, reason="没有下一个了") if level < config.level: return fail_msg(msgtype, reason="等级不足") random_configs = get_config(RandomAmbitionConfig) if req.use_gold: c = weighted_random2([[ i.step, i.golden_pro] for i in random_configs.values()]) cost = {"gold": get_cons_value("AmbitionGoldUpCost")} else: c = weighted_random2([[ i.step, i.pro] for i in random_configs.values()]) cost = {"soul": get_cons_value("AmbitionUpCost")} if c not in random_configs: return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST) try: ll = list(ambition) ll[index] = str(c) ambition = ''.join(ll) except IndexError: return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST) apply_reward(p, {}, cost, type=RewardType.AmbitionUp) setattr(p, attr, ambition) if c >= 5: p.ambition_count += 1 from task.manager import on_ambition on_ambition(p) p.save() p.sync() return success_msg(msgtype, "")
def loot_refresh_targets(player): targets = [] configs = get_config(LootConfig) best = max([cs.type for cs in configs]) has_best = False length = len(configs) for i in range(length): if has_best: # 最高品质只出一个 c = weighted_random2([(c, c.prob) for c in configs if c.type != best]) else: c = weighted_random2([(c, c.prob) for c in configs]) if c.type == best: player.loot_reset_crit_count = 0 has_best = True targets.append({"type": c.type, "count": random.randint(c.min, c.max)}) # 最高品质必须在最中间 mid = length / 2 for index, target in enumerate(targets): if target["type"] == best: if index != mid: # 不在中间则交换位置 targets[index], targets[mid] = targets[mid], targets[index] break if player.loot_reset_crit_count and player.loot_reset_crit_count % 5 == 0: # 刷新设保底,每刷5次必定出一个最高品质,刷到最高品质重新计算 if targets[mid]["type"] != best: cc = configs[-1] targets[mid] = { "type": cc.type, "count": random.randint(cc.min, cc.max) } player.loot_reset_crit_count = 0 lv = player.level kmap = {1: 0.7, 2: 0.8, 3: 0.9} base = 4 * lv * (62 + 0.0045 * lv * lv + 0.18 * lv) for target in targets: curr = kmap[target['type']] * base pmin = curr * 0.92 - 88 pmax = curr * 1.08 + 88 power = random.randint(int(pmin), int(pmax)) target['power'] = power player.loot_targets_cache = targets player.loot_reset_crit_count += 1 player.save() player.sync() return targets
def trigger_friendfb(p): if p.trigger_packs_flag: return None now = datetime.now() ts = time.mktime(now.timetuple()) if not p.friendfb_remain_count: return None lconfig = get_config(LevelupConfig).get(p.level) if not lconfig or not lconfig.friendfb: return None if now.hour > 23 or now.hour < 9: return None last = p.friendfb_last_trigger_time # 同一时间只存在一个秘境副本 if last and ts < last + FRIENDFB_INTERVAL: return None if not p.friendfb_triggered_count: prob = 1 else: prob = 0 triggers = get_config(TriggerAfterFbConfig) for tg in triggers: if p.friend_total_sp >= tg.sp: prob = tg.friendfb_prob else: break if not guess(prob): return None configs = get_config(FriendfbConfig) samples = [] ffs_by_level = None ffs_by_levels = get_config(FriendfbByLevelConfig) for k in sorted(ffs_by_levels): if p.level >= k: ffs_by_level = ffs_by_levels[k] if not ffs_by_level: ffs_by_level = ffs_by_levels[min(ffs_by_levels)] for ff in ffs_by_level: if p.friendfb_last_trigger_fbID and \ p.friendfb_last_trigger_fbID == ff.fbID: continue ff = configs[ff.fbID] samples.append([ff.fbID, ff.prob]) assert samples, "impossible" fbID = weighted_random2(samples) info = get_config(FriendfbConfig)[fbID] friendfb = create_friendfb(p, info.fbID) p.friendfb_list.add(friendfb['friendfbID']) p.friend_total_sp = 0 p.friendfb_last_trigger_time = ts p.friendfb_last_trigger_fbID = fbID p.friendfb_triggered_count += 1 p.save() p.sync() return friendfb
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
def refresh_faction_task(p): configs = get_config(FactionTaskConfig) infos = get_config(TaskConfig) samples = [] for taskID, c in configs.items(): task = infos.get(taskID) if not task: continue if p.level < task.openlevel: continue if task.openfb: for f in task.openfb: if f not in p.fbscores: continue samples.append([taskID, c.prob]) # samples = [[k, v.prob] for k, v in configs.items()] taskID = weighted_random2(samples) p.faction_taskID = taskID p.save() p.sync()
def next_monster(p): rest_prob = 100 monsters = get_config(TapMonsterConfig) rushers = [] for k, v in monsters.items(): if v.prob: rushers.append([k, v.prob]) rest_prob -= v.prob rushers.append([None, rest_prob]) rusher = weighted_random2(rushers) if rusher: # 乱入 p.tap_monster = rusher else: loops = get_config(TapLoopConfig) # 取当前循环到的关卡 loop = loops[p.tap_loop_count % len(loops) + 1] p.tap_monster = weighted_random3(loop.monsters, loop.probs) p.tap_loop_count += 1 p.tap_hurts_index = 0 monster = monsters[p.tap_monster] p.tap_hurts = get_hurts(monster) return monster
def fbHandler(reward, player, fbID, isfirst, rsp): from config.configs import FbInfoConfig from config.configs import SceneInfoConfig from config.configs import RandomMonsterConfig from config.configs import PetConfig from config.configs import FbDropConfig from scene.manager import get_monster_groups from scene.constants import FbType from campaign.manager import g_campaignManager monsters = get_monster_groups(fbID) sumsoul = 0 summoney = 0 petinfos = get_config(PetConfig) randomms = get_config(RandomMonsterConfig) config = get_config(FbInfoConfig)[fbID] scene = get_config(SceneInfoConfig)[config.sceneID] rewards = {} drop_fields = ('itemfirst_id', 'itemdrops_id', 'exp_reward', 'monster_drop', 'gold_reward') for i in drop_fields: rewards[i] = getattr(config, i) # 怪物掉落 droped_pets_count = 0 # 已经掉落葫芦数 layer_count = len(monsters.items()) mulriple = 1 # 倍数 if g_campaignManager.fb_drop_campaign.is_open(): cfg = g_campaignManager.fb_drop_campaign.get_current() kind = (scene.type, scene.subtype) flag = g_campaignManager.fb_drop_campaign.kind.get(kind, None) if flag and flag & cfg.group > 0: mulriple = cfg.reward_group for layer, group in monsters.items(): monster_count = len(group) for monsterindex, (monsterlevel, monsterID) in group.items(): if monsterID < 0: # 负数代表需要随机 sample = randomms[monsterID] monsterID = weighted_random3( sample.monsters + [None], sample.weights + [BASENUMBER - sum(sample.weights)]) if not monsterID: # 可能不出现 continue rsp.replaces.append(monsterID) monster = petinfos[monsterID] drop = rsp.drops.add(index=monsterindex, layer=layer) # 必掉 # 金币 = sqrt(level)*coinUp/4+50 # 水晶 = sqrt(level)*expUp/7+30 money = monster.coinUp soul = monster.expUp # money = int( # math.sqrt(monsterlevel) * monster.coinUp / float(4) + 50) # soul = int( # math.sqrt(monsterlevel) * monster.expUp / float(7) + 30) drop.must.add(type=RewardItemType.Money, count=money) drop.must.add(type=RewardItemType.Soul, count=soul) summoney += money sumsoul += soul # boss if layer == layer_count and monsterindex == monster_count: alter_flag = False if isfirst: droppack = 0 else: droppack = config.boss_drop else: if monster.dtype == 0: # 从关卡配置中读取怪物掉落 droppack = rewards['monster_drop'] else: # 从怪物表本身读取怪物掉落 droppack = monster.droppack alter_flag = True # 可能掉 # print monster.name # print 'dtype', monster.dtype # print 'droppack', droppack if droppack: pets = zip( filter(lambda s: s, [monster.drop1, monster.drop2, monster.drop3]), [monster.num1, monster.num2, monster.num3]) if alter_flag: if pets: petID = weighted_random2(pets) else: petID = None matID = monster.drop_piece else: petID = None matID = None if droped_pets_count >= 4: # 留一个位置给最后一波 if layer == layer_count: skip_pet = (droped_pets_count >= 10) else: skip_pet = True else: skip_pet = False # not petID compute(droppack, reward, itemID=petID, matID=matID, skip_pet=skip_pet) if reward.computedDropPacks: # 多倍掉落 if mulriple > 1: for k, v in reward.computedDropPacks.items(): if isinstance(v, int): reward.computedDropPacks[k] = v * mulriple reward.attrReward[k] = v * mulriple elif isinstance(v, (list, tuple)): # computedDropPacks 并不是最终给的,所以要应用到 reward 上 reward.computedDropPacks[k] = [[ item, count * mulriple ] for (item, count) in v] items = getattr(reward, k) for (item, count) in reward.computedDropPacks[k]: for repl in items: if repl[0] == item: repl[1] += (mulriple - 1) drop.maybe = build_reward(reward.computedDropPacks) for m in drop.maybe: if m.type in (RewardItemType.Pet, RewardItemType.Mat, RewardItemType.Equip): droped_pets_count += 1 reward.clean_compute_droppacks() if summoney: reward.attrReward['money'] = reward.attrReward.setdefault('money', 0) + summoney # reward.attrReward['exp'] = reward.attrReward.setdefault('exp', 0) if sumsoul: reward.attrReward['soul'] = reward.attrReward.setdefault('soul', 0) + sumsoul fb_exp = int(rewards['exp_reward']) if fb_exp: reward.attrReward['exp'] = reward.attrReward.setdefault('exp', 0) + fb_exp rsp.rewards.add(type=RewardItemType.EXP, count=fb_exp) fb_gold = int(rewards['gold_reward']) if g_campaignManager.gold_campaign.is_open() and fb_gold: reward.attrReward['gold'] = reward.attrReward.setdefault('gold', 0) + fb_gold rsp.rewards.add(type=RewardItemType.Gold, count=fb_gold) campaign_drop = 0 if config.type == FbType.Normal: if g_campaignManager.normal_fb_campaign.is_open(): current = g_campaignManager.normal_fb_campaign.get_current() if current: campaign_drop = current.group elif config.type == FbType.Advanced: current = g_campaignManager.advanced_fb_campaign.get_current() if current: campaign_drop = current.group if campaign_drop: compute(campaign_drop, reward) for each in build_reward(reward.computedDropPacks, cls=dict): rsp.rewards.add(**each) reward.clean_compute_droppacks() # 关卡奖励 if isfirst: # 首通关卡 reward.clean_compute_droppacks() # # 场景首通 # if all( # map(lambda s: s in player.fbscores or s == fbID, scene.fbs)): # # 是否该场景全通 # if scene.drop: # compute(scene.drop, reward) # rsp.first = build_reward(reward.computedDropPacks) if rewards['itemfirst_id']: # 关卡首通 compute(rewards['itemfirst_id'], reward) else: if rewards['itemdrops_id']: # 多倍掉落 reward.dropPacks = [[rewards['itemdrops_id'], mulriple]] # 假概率掉落 config = get_config(FbDropConfig).get(fbID) if config: totalCount = player.fbscores.get(fbID, {}).get("totalCount", 0) index = totalCount % len(config.probs) prob = config.probs[index] if guess(prob): # 多倍掉落 reward.dropPacks.append([config.drop, mulriple]) return reward
def step_mazes(p, attr, incr, count): mazes = get_config(MazeConfig) maze_step_count = p.maze_step_count results = [] while count > 0: remain = time.time() + 3600 data = {} config = mazes[maze_step_count % len(mazes)] append = False # 是否加入事件组 attr["money_rest_pool"] = min( attr.get("money_rest_pool", p.money_rest_pool) + get_cons_value("MazeMustDropMoney"), p.money_most_pool) attr["maze_rest_count"] = attr.get("maze_rest_count", p.maze_rest_count) data["attr"] = attr data["incr"] = incr if config.type == MazeEventType.DoubleMoney: v = int( attr.get("money_rest_pool", p.money_rest_pool) * config.argv) v = max(min(v, p.money_most_pool), 0) attr["money_rest_pool"] = v elif config.type == MazeEventType.AddMoney: v = int( attr.get("money_rest_pool", p.money_rest_pool) + config.argv) v = max(min(v, p.money_most_pool), 0) attr["money_rest_pool"] = v elif config.type == MazeEventType.DoubleCount: origin = attr.get("maze_rest_count", p.maze_rest_count) v = int(origin * config.argv) v = max(v, 0) if v > origin: attr["maze_rest_count"] = origin incr["maze_rest_count"] = incr.get("maze_rest_count", 0) + v - origin else: attr["maze_rest_count"] = v elif config.type == MazeEventType.AddCount: origin = attr.get("maze_rest_count", p.maze_rest_count) v = int(origin + config.argv) v = max(v, 0) if v > origin: attr["maze_rest_count"] = origin incr["maze_rest_count"] = incr.get("maze_rest_count", 0) + v - origin else: attr["maze_rest_count"] = v elif config.type == MazeEventType.Drop: data.update({"drop": int(config.argv)}) elif config.type == MazeEventType.Shop: if config.argv == MallType.Silver: attr["mall_silver_open_remain"] = remain elif config.argv == MallType.Golden: attr["mall_golden_open_remain"] = remain data.update({"argv": int(config.argv)}) append = True elif config.type == MazeEventType.Case: weights = [] for each in get_config(MazeCaseConfig): if p.level >= each.level: weights.append([each.drop, each.prob]) else: break drop = weighted_random2(weights) data.update({"argv": int(drop)}) append = True elif config.type == MazeEventType.Boss: weights = [] for each in get_config(MazeBossConfig): if p.level >= each.level: weights.append([each.boss, each.prob]) else: break boss = weighted_random2(weights) data.update({"argv": int(boss)}) append = True elif config.type == MazeEventType.Noop: pass else: break result = { "type": config.type, "time": remain, "append": append, } result.update(**data) result.setdefault("argv", config.argv) results.append(result) attr["maze_rest_count"] = max(attr["maze_rest_count"] - 1, 0) maze_step_count += 1 if "maze_rest_count" in attr and attr["maze_rest_count"] == 0: break if attr["money_rest_pool"] >= p.money_most_pool: break count -= 1 return results
def lottery(self, msgtype, body): req = poem_pb.LotteryRequest() req.ParseFromString(body) p = self.player from entity.manager import save_guide save_guide(p, req.guide_type) # 保存新手引导进度 logger.debug("req: {}".format(req)) LOTTERY_ID2TYPE = { LotteryType.Lottery1: ("A", "ball", 1), LotteryType.Lottery2: ("B", "ball", 10), LotteryType.Lottery3: ("C", "gold", 1), LotteryType.Lottery4: ("D", "gold", 10), } kind_cfg = get_config(LotteryFunctionConfig)[req.type] if req.type not in LOTTERY_ID2TYPE: return fail_msg(msgtype, reason="类型不对") if p.level < kind_cfg.level: return fail_msg(msgtype, reason="等级不足") kind, cost_type, cost_count = LOTTERY_ID2TYPE[req.type] cost = kind_cfg.Price if req.type == LotteryType.Lottery2: if p.ball < 10: cost_count = p.ball cost = p.ball now = time.time() loterry_hero_count = getattr( p, "loterry_hero_count_{}".format(kind)) loterry_hero_gold_first = getattr( p, "loterry_hero_gold_first_{}".format(kind)) loterry_hero_used_free_count = getattr( p, "loterry_hero_used_free_count_{}".format(kind)) or 0 loterry_hero_cd = getattr( p, "loterry_hero_cd_{}".format(kind)) cd = datetime.fromtimestamp(loterry_hero_cd).strftime('%Y-%m-%d %H:%M') logger.debug('loterry_hero_cd: {}'.format(cd)) cd = datetime.fromtimestamp(loterry_hero_cd).strftime('%Y-%m-%d %H:%M') logger.debug('loterry_hero_cd: {}'.format(cd)) key = "NormalGold{}".format(kind) if loterry_hero_cd <= now and \ loterry_hero_used_free_count < kind_cfg.FreeTimes: # 免费 if not loterry_hero_count: # 引导抽 key = "FirstFree{}".format(kind) ID = kind_cfg.rangeset[1] elif loterry_hero_count == 1: # 首抽 key = "NormalFree{}".format(kind) ID = kind_cfg.rangeset[2] else: # 普通 key = "NormalFree{}".format(kind) ID = kind_cfg.rangeset[0] else: # 付费 if not loterry_hero_count: # 引导抽 key = "FirstGold{}".format(kind) ID = kind_cfg.rangeset[1] if not ID: ID = kind_cfg.rangeset[2] elif loterry_hero_count == 1: # 首抽 key = "FirstGold{}".format(kind) ID = kind_cfg.rangeset[2] else: key = "NormalGold{}".format(kind) ID = kind_cfg.rangeset[0] loterry_hero_count += 1 logger.debug( '\nused_free_count_A: {},\ \nused_free_count_B: {},\ \nused_free_count_C: {},\ \nused_free_count_D: {}'.format( p.loterry_hero_used_free_count_A, p.loterry_hero_used_free_count_B, p.loterry_hero_used_free_count_C, p.loterry_hero_used_free_count_D)) logger.debug('loterry_hero_key: {}'.format(key)) costs = {} if "Free" in key: cost = 0 loterry_hero_used_free_count += 1 loterry_hero_cd = now + kind_cfg.ColdDown else: costs = {cost_type: cost} if p.lottery_campaign_discount < 10: gold = costs.get("gold", 0) if gold: gold = int(gold * p.lottery_campaign_discount / float(10)) costs["gold"] = gold try: from reward.base import check_cost_attr check_cost_attr(p, costs) except AttrNotEnoughError: return fail_msg(msgtype, reason="材料不足") loterry_hero_gold_first = False if not ID: ID = kind_cfg.rangeset[0] attr_drop = get_config(AttributeDroppackConfig)[ID] dropID = attr_drop.RewardDroppack if cost_type == "gold": if cost_count > 1: if p.lottery_gold_accumulating10 >= abs( attr_drop.Accumulating): dropID = attr_drop.AccumDroppack if attr_drop.Accumulating > 0: p.lottery_gold_accumulating10 -= attr_drop.Accumulating else: if p.lottery_gold_accumulating >= abs( attr_drop.Accumulating): dropID = attr_drop.AccumDroppack if attr_drop.Accumulating > 0: p.lottery_gold_accumulating -= attr_drop.Accumulating else: if cost_count > 1: if p.lottery_money_accumulating10 >= abs( attr_drop.Accumulating): dropID = attr_drop.AccumDroppack if attr_drop.Accumulating > 0: p.lottery_money_accumulating10 -= \ attr_drop.Accumulating else: if p.lottery_money_accumulating >= abs( attr_drop.Accumulating): dropID = attr_drop.AccumDroppack if attr_drop.Accumulating > 0: p.lottery_money_accumulating -= attr_drop.Accumulating logger.debug("DropID:{}".format(dropID)) rsp = poem_pb.LotteryResponse() reward = open_reward(RewardType.Lottery, rsp, dropID, cost_count) from campaign.manager import g_campaignManager if g_campaignManager.hot_lottery_campaign.is_open() and\ req.type == LotteryType.Lottery4: campaign_config = g_campaignManager.hot_lottery_campaign.\ get_current() hot_configs = get_config(HotLotteryCampaignConfig).get( campaign_config.group, []) hot_rewards = weighted_random2([ [i.rewards, i.prob] for i in hot_configs]) reward.add(parse_reward(hot_rewards)) rsp.hot_rewards = hot_rewards reward.cost_after(p, **costs) extra = {} result = reward.apply(p, extra=extra) logger.debug("result {}:".format(result)) # Save setattr( p, "loterry_hero_count_{}".format(kind), loterry_hero_count) setattr( p, "loterry_hero_gold_first_{}".format(kind), loterry_hero_gold_first) setattr( p, "loterry_hero_used_free_count_{}".format(kind), loterry_hero_used_free_count) setattr( p, "loterry_hero_cd_{}".format(kind), loterry_hero_cd) is_first_consume = int(not p.consume_count and bool( p.lottery_count) and (cost_type == "gold")) role_custom.info(player=p, type=role_custom.Consume, arg1=ujson.dumps({ "type": RewardType.Lottery, "kind": req.type, "cost": costs, "is_first_consume": is_first_consume, })) p.lottery_count += cost_count from task.manager import on_lottery on_lottery(p, cost_count, (cost_type == "gold")) if kind == "D": from task.manager import on_lottery10 on_lottery10(p) ACCUMULATING_DELTA = 1 if cost_type == "gold": if cost_count > 1: p.lottery_gold_accumulating10 += \ ACCUMULATING_DELTA * kind_cfg.Price else: p.lottery_gold_accumulating += \ ACCUMULATING_DELTA * kind_cfg.Price p.consume_count += 1 else: if cost_count > 1: p.lottery_money_accumulating10 += \ ACCUMULATING_DELTA * kind_cfg.Price else: p.lottery_money_accumulating += \ ACCUMULATING_DELTA * kind_cfg.Price if "FirstFree" not in key: save_guide(p, "FAKE_GOLDEN_LOTTERY") from task.manager import on_collect_pet1 from task.manager import on_collect_pet2 pets = extra.get("pets", []) on_collect_pet1(p, *pets) on_collect_pet2(p, *pets) p.save() p.sync() from chat.manager import on_news_pet_quality_lottery from chat.manager import on_news_pet_special_lottery from chat.manager import on_news_equip_quality_lottery on_news_pet_quality_lottery(p, rsp.rewards) on_news_pet_special_lottery(p, rsp.rewards) on_news_equip_quality_lottery(p, rsp.rewards) return success_msg(msgtype, rsp)
def fusion(self, msgtype, body): req = poem_pb.FusionRequest() req.ParseFromString(body) p = self.player from entity.manager import save_guide save_guide(p, req.guide_type) # 保存新手引导进度 configs = get_config(PetConfig) cls = None # 品级 maxLevel = 1 maxStep = 0 maxSkill1 = 1 maxSkill2 = 1 maxSkill3 = 1 maxSkill4 = 1 maxSkill5 = 1 error = fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST) pets = [] bestEquips = {} equipsNeedDelete = [] if len(req.pets) != 6: return error star = 0 for t in req.pets: pet = p.pets.get(t) if not pet: return error if in_lineup(p, t): if not in_lineup(p, t, type=LineupType.ATK): return error pets.append(pet) config = configs.get(pet.prototypeID) if not config: return error if cls and config.cls != cls: # 校验全部品级相同 return error cls = config.cls # 上一个品级 if cls >= 6: return error for i in pet.equipeds.values(): equip = p.equips.get(i) if not equip: continue if equip.type in (EquipType.FaBao, EquipType.ZuoQi): equipsNeedDelete.append(equip) else: best = bestEquips.get(equip.type) if not best or equip.step > best.step: # 比之前的装备好 bestEquips[equip.type] = equip if best: equipsNeedDelete.append(best) else: equipsNeedDelete.append(equip) maxLevel = max(maxLevel, pet.level) # 继承最大等级 maxStep = max(maxStep, config.herostep) # 继承最大阶级 maxSkill1 = max(maxSkill1, pet.skill1) maxSkill2 = max(maxSkill2, pet.skill2) maxSkill3 = max(maxSkill3, pet.skill3) maxSkill4 = max(maxSkill4, pet.skill4) maxSkill5 = max(maxSkill5, pet.skill5) star += pet.star / float(config.need_patch) pool = get_config(FusionPoolConfig).get(cls + 1, []) if not pool: return error t = weighted_random2([[c.prototypeID, c.prob] for c in pool]) config = configs.get(t) if not config: return error same = config.same # 继承阶级 config = None for t in get_config(PetBySameConfig).get(same): pp = configs.get(t.prototypeID) if not pp: return error if pp.herostep == maxStep: config = pp break if not config: return error fusion_cost = get_config(FusionCostConfig).get(cls) if not fusion_cost: return error cost = parse_reward([{ "type": fusion_cost.type, "count": fusion_cost.cost }]) gain = {'petList': [[config.prototypeID, 1]]} extra = {} try: apply_reward(p, gain, cost, type=RewardType.Fusion, extra=extra) except AttrNotEnoughError: return error except MatNotEnoughError: return error pet = extra.get("pets")[0] # 继承等级 for _, equip in bestEquips.items(): from equip.manager import install_equip install_equip(p, pet.entityID, equip.entityID, force=True, sync=False) pet.level = maxLevel # 继承星级 star = int(star / float(6) * config.need_patch) pet.add_star = star - pet.base_star # 继承技能 pet.skill1 = maxSkill1 pet.skill2 = maxSkill2 pet.skill3 = maxSkill3 pet.skill4 = maxSkill4 pet.skill5 = maxSkill5 l = list(p.lineups.get(LineupType.ATK, [0, 0, 0, 0])) # 攻击阵型可以被炼化 flag = False for each in pets: if in_lineup(p, each.entityID, type=LineupType.ATK): flag = True l[l.index(each.entityID)] = 0 if flag: save_lineup(p, l, LineupType.ATK) p.del_pets(*pets) p.del_equips(*equipsNeedDelete) from task.manager import on_collect_pet2 on_collect_pet2(p, pet) from task.manager import on_pet_fusion_count on_pet_fusion_count(p, pet) pet.save() pet.sync() rsp = poem_pb.FustionResponse() rsp.pet_entity_id = pet.entityID # p.update_power() p.save() p.sync() return success_msg(msgtype, rsp)