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
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
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
def _pack_draw_response(self, data, hero_list, item_list, resource, search_num, next_time, now): """封装响应 返回客户端的是抽奖获得的英雄和物品(并未将已经拥有的英雄分解成将魂石) 客户端会自行进行分解 """ win_hero = [] for (basic_id, num) in hero_list: soldier_basic_id = HeroInfo.get_default_soldier_basic_id(basic_id) soldier_id = SoldierInfo.generate_id(data.id, soldier_basic_id) soldier = data.soldier_list.get(soldier_id, True) hero = HeroInfo.create(data.id, basic_id, soldier, technology_basic_ids = []) for i in range(0, num): win_hero.append(hero) win_item = [] for (basic_id, num) in item_list: item = ItemInfo.create(data.id, basic_id, num) win_item.append(item) res = wineShop_pb2.WineShopDrawRes() res.status = 0 for item in win_item: pack.pack_item_info(item, res.items.add()) for hero in win_hero: pack.pack_hero_info(hero, res.heroes.add(), now) pack.pack_resource_info(resource, res.resource) res.draw.search_num = search_num res.draw.next_left_time = max(0, next_time - now) return res
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
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
def _pack_signin_response(self, data, hero_list, item_list, now): """封装签到响应 """ #为了封装 response 构造 HeroInfo 和 ItemInfo win_hero = [] for (basic_id, num) in hero_list: soldier_basic_id = HeroInfo.get_default_soldier_basic_id(basic_id) soldier_id = SoldierInfo.generate_id(data.id, soldier_basic_id) soldier = data.soldier_list.get(soldier_id, True) hero = HeroInfo.create(data.id, basic_id, soldier, []) for i in range(0, num): win_hero.append(hero) win_item = [] for (basic_id, num) in item_list: item = ItemInfo.create(data.id, basic_id, num) win_item.append(item) res = user_pb2.SignInRes() res.status = 0 if len(win_hero) > 0: assert len(win_hero) == 1 pack.pack_hero_info(win_hero[0], res.hero, now) if len(win_item) > 0: assert len(win_item) == 1 pack.pack_item_info(win_item[0], res.item) return res
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)
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
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)
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
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
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
def _pack_treasure_draw_response(self, data, item_list, resource, alltimes, timer): win_item = [] for (basic_id, num) in item_list: item = ItemInfo.create(data.id, basic_id, num) win_item.append(item) res = activity_pb2.TurntableDrawRes() res.status = 0 for item in win_item: pack.pack_item_info(item, res.items.add()) pack.pack_resource_info(resource, res.resource) res.all_times = alltimes return res
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
def init_default_items(data, pattern): """创建一个新帐号时,初始化赠送的物品 Args: data[UserData]: 用户信息 pattern[int]: 初始化模式 """ basic_ids = data_loader.InitUserBasicInfo_dict[pattern].itembasicId nums = data_loader.InitUserBasicInfo_dict[pattern].itemNum assert len(basic_ids) == len(nums) for index in range(0, len(basic_ids)): item = ItemInfo.create(data.id, basic_ids[index], nums[index]) data.item_list.add(item) return True
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
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
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
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
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
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))
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
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)
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)
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)
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
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)
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
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