def match(self, friend_id): friend_id = int(friend_id) if not self.check_friend_exist(friend_id): raise GameException( ConfigErrorMessage.get_error_id("FRIEND_NOT_OK")) club_one = Club(self.server_id, self.char_id) club_two = Club(self.server_id, friend_id) f_one = Formation(self.server_id, self.char_id) f_two = Formation(self.server_id, self.char_id) match = ClubMatch(club_one, club_two, 6, f_one.get_skill_sequence(), f_two.get_skill_sequence()) msg = match.start() msg.key = "" msg.map_name = GlobalConfig.value_string("MATCH_MAP_FRIEND") friend_match_signal.send(sender=None, server_id=self.server_id, char_id=self.char_id, target_id=friend_id, win=msg.club_one_win) return msg
def make_3_way_clubs(self, _id, _info): """ :rtype: list[core.abstract.AbstractClub] """ clubs = [] skill_sequences = [] if is_npc(_id): for i in range(1, 4): npc_id = _info['ways_npc'][i - 1] club = ConfigNPCFormation.get(npc_id) club.id = _id club.name = _info['name'] club.flag = _info['flag'] clubs.append(club) skill_sequences.append({}) else: cs = Championship(self.server_id, int(_id)) for i in range(1, 4): way = cs.get_way_object(i) club = Club(self.server_id, int(_id), load_staffs=False) club.formation_staffs = way.formation_staffs clubs.append(club) skill_sequences.append(way.get_skill_sequence()) return clubs, skill_sequences
def use_formation(self, fid): if fid != 0: config = ConfigFormation.get(fid) if not config: raise GameException(ConfigErrorMessage.get_error_id("FORMATION_NOT_EXIST")) level = self.doc['levels'].get(str(fid), 0) if level == 0: raise GameException(ConfigErrorMessage.get_error_id("FORMATION_NOT_ACTIVE")) if not self.is_formation_valid(fid): raise GameException(ConfigErrorMessage.get_error_id("FORMATION_CAN_NOT_USE")) updater = {'using': fid} self.doc['using'] = fid # 把格子策略设置为默认值 for k in self.doc['slots']: self.doc['slots'][k]['policy'] = 1 updater['slots.{0}.policy'.format(k)] = 1 self.MONGO_COLLECTION.db(self.server_id).update_one( {'_id': self.char_id}, {'$set': updater} ) self.send_slot_notify(slot_ids=self.doc['slots'].keys()) self.send_formation_notify(formation_ids=[]) # 阵型改变,从而改变天赋 # 所以这里暴力重新加载staffs club = Club(self.server_id, self.char_id, load_staffs=False) club.force_load_staffs(send_notify=True)
def send_notify(self, ids=None): notify = FriendNotify() if ids: projection = {"friends.{0}".format(_id): 1 for _id in ids} act = ACT_UPDATE else: projection = {"friends": 1} act = ACT_INIT notify.act = act notify.max_amount = MAX_FRIEND_AMOUNT doc = MongoFriend.db(self.server_id).find_one({'_id': self.char_id}, projection) friend_ids = [int(i) for i in doc['friends'].keys()] online_char_ids = OperationLog.get_recent_action_char_ids(self.server_id) for f in friend_ids: notify_friend = notify.friends.add() notify_friend.status = FRIEND_STATUS_TABLE[doc['friends'][str(f)]] friend_club = Club(self.server_id, f) notify_friend.club.MergeFrom(friend_club.make_protomsg()) notify_friend.online = f in online_char_ids MessagePipe(self.char_id).put(msg=notify)
def send_notify(self, ids=None): notify = FriendNotify() if ids: projection = {"friends.{0}".format(_id): 1 for _id in ids} act = ACT_UPDATE else: projection = {"friends": 1} act = ACT_INIT notify.act = act notify.max_amount = MAX_FRIEND_AMOUNT doc = MongoFriend.db(self.server_id).find_one({'_id': self.char_id}, projection) friend_ids = [int(i) for i in doc['friends'].keys()] online_char_ids = OperationLog.get_recent_action_char_ids( self.server_id) for f in friend_ids: notify_friend = notify.friends.add() notify_friend.status = FRIEND_STATUS_TABLE[doc['friends'][str(f)]] friend_club = Club(self.server_id, f) notify_friend.club.MergeFrom(friend_club.make_protomsg()) notify_friend.online = f in online_char_ids MessagePipe(self.char_id).put(msg=notify)
def get_leaderboard(request): server_id = request._game_session.server_id char_id = request._game_session.char_id info = ClubLeaderBoard(server_id, char_id).get_info() response = ClubLeaderBoardResponse() response.ret = 0 response.next_update_at = info['next_update_at'] response.my_level_rank = info['my_level_rank'] response.my_power_rank = info['my_power_rank'] for _id, level, power in info['level']: obj = Club(server_id, _id, load_staffs=False) response_level = response.clubs_by_level.add() response_level.MergeFrom(obj.make_protomsg()) response_level.level = level response_level.power = power for _id, level, power in info['power']: obj = Club(server_id, _id, load_staffs=False) response_power = response.clubs_by_power.add() response_power.MergeFrom(obj.make_protomsg()) response_power.level = level response_power.power = power return ProtobufResponse(response)
def levelup_formation(self, fid): from core.challenge import Challenge config = ConfigFormation.get(fid) if not config: raise GameException(ConfigErrorMessage.get_error_id("FORMATION_NOT_EXIST")) level = self.doc['levels'].get(str(fid), 0) if level == 0: raise GameException(ConfigErrorMessage.get_error_id("FORMATION_NOT_ACTIVE")) if level >= config.max_level: raise GameException(ConfigErrorMessage.get_error_id("FORMATION_REACH_MAX_LEVEL")) Challenge(self.server_id, self.char_id).check_starts(config.levels[level].level_up_need_star) rc = ResourceClassification.classify(config.levels[level].level_up_need_items) rc.check_exist(self.server_id, self.char_id) rc.remove(self.server_id, self.char_id, message="Formation.levelup_formation:{0}".format(fid)) self.doc['levels'][str(fid)] = level + 1 self.MONGO_COLLECTION.db(self.server_id).update_one( {'_id': self.char_id}, {'$set': { 'levels.{0}'.format(fid): level + 1 }} ) self.send_formation_notify(formation_ids=[fid]) if fid == self.doc['using']: # 阵型改变,从而改变天赋 # 所以这里暴力重新加载staffs club = Club(self.server_id, self.char_id, load_staffs=False) club.force_load_staffs(send_notify=True)
def test_add_gold(self): gold = 99 club = Club(1, 1) club.update(gold=gold) doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club': 1}) assert doc['club']['gold'] == gold assert club.gold == gold
def test_level_up_to_two(self): renown = club_level_up_need_renown(1) + 1 club = Club(1, 1) club.update(renown=renown) doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club': 1}) assert doc['club']['level'] == 2 assert club.level == 2
def test_add_gold(self): gold = 99 club = Club(1, 1) club.update(gold=gold) doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club': 1}) assert doc['club']['gold'] == gold assert club.gold == gold
def test_level_up_to_two(self): renown = club_level_up_need_renown(1) + 1 club = Club(1, 1) club.update(renown=renown) doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club': 1}) assert doc['club']['level'] == 2 assert club.level == 2
def test_set_policy(self): policy = random.choice(ConfigPolicy.INSTANCES.keys()) club = Club(1, 1) club.set_policy(policy) assert club.policy == policy doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club.policy': 1}) assert doc['club']['policy'] == policy
def test_set_policy(self): policy = random.choice(ConfigPolicy.INSTANCES.keys()) club = Club(1, 1) club.set_policy(policy) assert club.policy == policy doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club.policy': 1}) assert doc['club']['policy'] == policy
def sync_slots(self, slots_data): super(Formation, self).sync_slots(slots_data) self.send_slot_notify(slot_ids=self.doc['slots'].keys()) # 阵型改变,从而改变天赋 # 所以这里暴力重新加载staffs club = Club(self.server_id, self.char_id, load_staffs=False) club.force_load_staffs(send_notify=True)
def make_way_club(self, way_id): """ :rtype: core.abstract.AbstractClub """ way = self.get_way_object(way_id) club = Club(self.server_id, self.char_id, load_staffs=False) club.formation_staffs = way.formation_staffs return club
def make_way_club(self, way_id): """ :rtype: core.abstract.AbstractClub """ way = self.get_way_object(way_id) club = Club(self.server_id, self.char_id, load_staffs=False) club.formation_staffs = way.formation_staffs return club
def test_match(self): self.set_friend_data() staff_ids = random.sample(ConfigStaff.INSTANCES.keys(), 10) for i in staff_ids: StaffManger(1, 1).add(i) StaffManger(1, 2).add(i) Club(1, 1).set_match_staffs(staff_ids) Club(1, 2).set_match_staffs(staff_ids) FriendManager(1, 1).match(2)
def set_unit(self, slot_id, unit_id): super(Formation, self).set_unit(slot_id, unit_id) # 检测阵型是否还可用 if self.doc['using'] and not self.is_formation_valid(self.doc['using']): self.use_formation(0) else: self.send_slot_notify(slot_ids=[slot_id]) # NOTE 兵种改变可能会导致牵绊改变,从而改变天赋 # 所以这里暴力重新加载staffs club = Club(self.server_id, self.char_id, load_staffs=False) club.force_load_staffs(send_notify=True)
def test_level_up_to_five(self): renown = 0 for i in range(1, 5): renown += club_level_up_need_renown(i) renown += 1 club = Club(1, 1) club.update(renown=renown) doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club': 1}) assert doc['club']['level'] == 5 assert club.level == 5
def test_level_up_to_five(self): renown = 0 for i in range(1, 5): renown += club_level_up_need_renown(i) renown += 1 club = Club(1, 1) club.update(renown=renown) doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club': 1}) assert doc['club']['level'] == 5 assert club.level == 5
def make_product(cls, server_id): def _make(doc): config = ConfigBaseStationLevel.get(doc['product_level']) items = config.get_product(100 - doc['loss_percent']) rc = ResourceClassification.classify(items) rc.add(server_id, doc['_id'], message="Plunder.make_product") MongoPlunder.db(server_id).update_one( {'_id': doc['_id']}, {'$set': { 'product_level': doc['level'], 'loss_percent': 0, # 'revenge_list': [], 'drop': rc.to_json(), }} ) char_ids = Club.get_recent_login_char_ids(server_id) char_ids = [i for i in char_ids] docs = MongoPlunder.db(server_id).find( {'_id': {'$in': char_ids}}, {'level': 1, 'product_level': 1, 'loss_percent': 1} ) for d in docs: _make(d)
def test_set_staffs(self): staff_ids = random.sample(ConfigStaff.INSTANCES.keys(), 10) sm = StaffManger(1, 1) for sid in staff_ids: sm.add(sid) Club(1, 1).set_match_staffs(staff_ids) assert len(Club(1, 1).match_staffs) == 5 assert len(Club(1, 1).tibu_staffs) == 5 for c in Club(1, 1).match_staffs: assert c != 0 for c in Club(1, 1).tibu_staffs: assert c != 0
def try_auto_transfer(cls, server_id): transfer = [] for doc in MongoUnion.db(server_id).find({}, {'owner': 1}): if Club.days_since_last_login(server_id, doc['owner']) <= 7: continue u = Union(server_id, doc['owner']) assert isinstance(u, UnionOwner) if u.get_members_amount() == 1: continue members = u.get_members() next_char_id = members[1].id u.transfer(next_char_id, send_mail=False) MailManager(server_id, doc['owner']).add( title=UNION_AUTO_TRANSFER_OLD_OWNER_MAIL_TITLE, content=UNION_AUTO_TRANSFER_OLD_OWNER_MAIL_CONTENT ) MailManager(server_id, next_char_id).add( title=UNION_AUTO_TRANSFER_NEW_OWNER_MAIL_TITLE, content=UNION_AUTO_TRANSFER_NEW_OWNER_MAIL_CONTENT ) transfer.append((doc['_id'], doc['owner'], next_char_id)) return transfer
def try_initialize(self): if self.doc['active']: return ways = [ self.get_way_object(1), self.get_way_object(2), self.get_way_object(3) ] club = Club(self.server_id, self.char_id) formation_staffs = club.formation_staffs """:type: list[core.staff.Staff]""" way_index = 0 slot_id = 1 for s in formation_staffs: ways[way_index].set_staff(slot_id, s.id) if s.unit: ways[way_index].set_unit(slot_id, s.unit.id) if way_index == 2: way_index = 0 slot_id += 1 else: way_index += 1 self.doc['active'] = True MongoPlunder.db(self.server_id).update_one({'_id': self.char_id}, {'$set': { 'active': True }}) self.send_formation_notify()
def start(self, dungeon_id, formation_slots=None): grade_conf = ConfigDungeonGrade.get(dungeon_id) if not grade_conf: raise GameException( ConfigErrorMessage.get_error_id("DUNGEON_NOT_EXIST")) map_name = ConfigDungeon.get(grade_conf.belong).map_name club_level = get_club_property(self.server_id, self.char_id, 'level') if grade_conf.need_level > club_level: raise GameException( ConfigErrorMessage.get_error_id( "DUNGEON_CLUB_LEVEL_NOT_ENOUGH")) f = Formation(self.server_id, self.char_id) if formation_slots: f.sync_slots(formation_slots) Energy(self.server_id, self.char_id).check(ConfigDungeon.get(grade_conf.belong).cost) ri = TimesInfo(self.server_id, self.char_id, grade_conf.belong) if not ri.remained_match_times: # 购买 self.buy_times(grade_conf.belong) club_one = Club(self.server_id, self.char_id) club_two = ConfigNPCFormation.get(grade_conf.npc) msg = ClubMatch(club_one, club_two, 6, f.get_skill_sequence(), {}).start() msg.key = str(dungeon_id) msg.map_name = map_name return msg
def send_rank_reward_and_reset_star(cls, server_id): char_ids = Club.get_recent_login_char_ids(server_id) char_ids = [i for i in char_ids] condition = {'$and': [ {'_id': {'$in': char_ids}}, {'today_max_star': {'$ne': 0}} ]} docs = MongoTower.db(server_id).find(condition, {'_id': 1}).sort('today_max_star', -1) rank = 1 for doc in docs: cid = doc['_id'] config = ConfigTowerRankReward.get(rank) rc = ResourceClassification.classify(config.reward) m = MailManager(server_id, cid) m.add( config.mail_title, config.mail_content, attachment=rc.to_json(), ) rank += 1 # reset today max star MongoTower.db(server_id).update_many( {}, {'$set': { 'today_max_star': 0, }} )
def skill_level_up(self, skill_id): config = ConfigUnionSkill.get(skill_id) if not config: raise GameException( ConfigErrorMessage.get_error_id("UNION_SKILL_NOT_EXIST")) current_level = self.member_doc['skills'].get(str(skill_id), 0) if current_level >= config.max_level: raise GameException( ConfigErrorMessage.get_error_id( "UNION_SKILL_REACH_SELF_MAX_LEVEL")) if current_level >= self.union_doc['level'] * 3: raise GameException( ConfigErrorMessage.get_error_id( "UNION_SKILL_LEVEL_LIMITED_BY_UNION_LEVEL")) rc = ResourceClassification.classify(config.levels[current_level].cost) rc.check_exist(self.server_id, self.char_id) rc.remove(self.server_id, self.char_id, message="UnionJoined.skill_level_up") self.member_doc['skills'][str(skill_id)] = current_level + 1 MongoUnionMember.db(self.server_id).update_one( {'_id': self.char_id}, {'$set': { 'skills.{0}'.format(skill_id): current_level + 1 }}) Club(self.server_id, self.char_id, load_staffs=False).force_load_staffs(send_notify=True) self.send_skill_notify(skill_id=skill_id)
def add(self, staff_oid, force_load_staffs=True): from core.club import Club if isinstance(staff_oid, (list, tuple)): staff_oids = staff_oid else: staff_oids = [staff_oid] new_add = [] for i in staff_oids: if i in self.doc['staffs']: continue if i not in ConfigCollection.INSTANCES: continue self.doc['staffs'].append(i) new_add.append(i) if new_add: MongoStaffCollection.db(self.server_id).update_one( {'_id': self.char_id}, {'$set': { 'staffs': self.doc['staffs'] }}) self.send_notify(staff_ids=new_add) if force_load_staffs: Club(self.server_id, self.char_id, load_staffs=False).force_load_staffs(send_notify=True)
def make_product(cls, server_id): def _make(doc): config = ConfigBaseStationLevel.get(doc['product_level']) items = config.get_product(100 - doc['loss_percent']) rc = ResourceClassification.classify(items) rc.add(server_id, doc['_id'], message="Plunder.make_product") MongoPlunder.db(server_id).update_one( {'_id': doc['_id']}, { '$set': { 'product_level': doc['level'], 'loss_percent': 0, # 'revenge_list': [], 'drop': rc.to_json(), } }) char_ids = Club.get_recent_login_char_ids(server_id) char_ids = [i for i in char_ids] docs = MongoPlunder.db(server_id).find({'_id': { '$in': char_ids }}, { 'level': 1, 'product_level': 1, 'loss_percent': 1 }) for d in docs: _make(d)
def try_auto_transfer(cls, server_id): transfer = [] for doc in MongoUnion.db(server_id).find({}, {'owner': 1}): if Club.days_since_last_login(server_id, doc['owner']) <= 7: continue u = Union(server_id, doc['owner']) assert isinstance(u, UnionOwner) if u.get_members_amount() == 1: continue members = u.get_members() next_char_id = members[1].id u.transfer(next_char_id, send_mail=False) MailManager(server_id, doc['owner']).add( title=UNION_AUTO_TRANSFER_OLD_OWNER_MAIL_TITLE, content=UNION_AUTO_TRANSFER_OLD_OWNER_MAIL_CONTENT) MailManager(server_id, next_char_id).add( title=UNION_AUTO_TRANSFER_NEW_OWNER_MAIL_TITLE, content=UNION_AUTO_TRANSFER_NEW_OWNER_MAIL_CONTENT) transfer.append((doc['_id'], doc['owner'], next_char_id)) return transfer
def check_exist(self, server_id, char_id): from core.club import Club from core.bag import Bag from core.staff import StaffManger, StaffRecruit from core.territory import Territory from core.arena import Arena from core.energy import Energy money_text = self.money_as_text_dict() if money_text: Club(server_id, char_id).check_money(**money_text) if self.bag: Bag(server_id, char_id).check_items(self.bag) if self.staff: StaffManger(server_id, char_id).check_original_staff_is_initial_state( self.staff) if self.territory_product: Territory(server_id, char_id).check_product(self.territory_product) if self.work_card: Territory(server_id, char_id).check_work_card(self.work_card) if self.arena_point: Arena(server_id, char_id).check_point(self.arena_point) if self.energy: Energy(server_id, char_id).check(self.energy) if self.staff_recruit_score: StaffRecruit(server_id, char_id).check_score(self.staff_recruit_score) if self.resource_data: _r = _Resource() _r.resource = dict(self.resource_data) _r.check_exists(server_id, char_id)
def help(self, friend_id, building_id): friend_id = int(friend_id) if not FriendManager(self.server_id, self.char_id).check_friend_exist(friend_id): raise GameException( ConfigErrorMessage.get_error_id("FRIEND_NOT_OK")) if not self.get_remained_help_times(): raise GameException( ConfigErrorMessage.get_error_id( "TERRITORY_NO_HELP_FRIEND_TIMES")) if not TerritoryFriend(self.server_id, friend_id).get_remained_got_help_times(): raise GameException( ConfigErrorMessage.get_error_id("TERRITORY_NO_GOT_HELP_TIMES")) t = Territory(self.server_id, friend_id) building = t.get_building_object(building_id, slots_ids=[]) event_id = building.event_id if not event_id: raise GameException( ConfigErrorMessage.get_error_id("TERRITORY_BUILDING_NO_EVENT")) MongoTerritory.db(self.server_id).update_one( {'_id': friend_id}, {'$set': { 'buildings.{0}.event_id'.format(building_id): 0 }}) config = ConfigTerritoryEvent.get(event_id) if not config.npc: resource_classified = ResourceClassification.classify( config.reward_win) resource_classified.add(self.server_id, self.char_id, message="TerritoryFriend.help") # NOTE: 战斗要等到结算的时候再记录次数 ValueLogTerritoryHelpFriendTimes(self.server_id, self.char_id).record() self.send_remained_times_notify() Territory(self.server_id, friend_id).got_help(self.char_id, building_id, config.target_exp) return None, resource_classified npc_club = ConfigNPCFormation.get(config.npc) my_club = Club(self.server_id, self.char_id) f = Formation(self.server_id, self.char_id) match = ClubMatch(my_club, npc_club, 6, f.get_skill_sequence(), {}) msg = match.start() msg.key = "{0}:{1}:{2}".format(friend_id, building_id, event_id) msg.map_name = GlobalConfig.value_string("MATCH_MAP_TERRITORY_FRIEND") return msg, None
def end(self, party_level, member_ids): ret = api_handle.API.Party.EndDone() ret.ret = 0 config = ConfigPartyLevel.get(party_level) talent_id = random.choice(config.talent_skills) self.doc['talent_id'] = talent_id MongoParty.db(self.server_id).update_one( {'_id': self.char_id}, {'$set': { 'talent_id': talent_id }}) # apply talent_id to club Club(self.server_id, self.char_id).force_load_staffs(send_notify=True) reward = [ (config.item_id, 1), ] rc = ResourceClassification.classify(reward) attachment = rc.to_json() char_ids = [self.char_id] char_ids.extend(member_ids) for c in char_ids: m = MailManager(self.server_id, c) m.add(config.mail_title, config.mail_content, attachment=attachment) ret.talent_id = talent_id return ret
def add(self, server_id, char_id, message=""): from core.club import Club from core.bag import Bag from core.staff import StaffManger, StaffRecruit from core.talent import TalentManager from core.territory import Territory from core.vip import VIP from core.arena import Arena from core.energy import Energy from core.plunder import Plunder club_property = self.money_as_text_dict() if self.club_exp: club_property['exp'] = self.club_exp if club_property: club_property['message'] = message Club(server_id, char_id).update(**club_property) if self.vip_exp: VIP(server_id, char_id).add_exp(self.vip_exp) if self.bag: bag = Bag(server_id, char_id) bag.batch_add(self.bag) sm = StaffManger(server_id, char_id) if self.staff: sm.batch_add(self.staff) if self.staff_exp_pool: sm.add_exp_pool(self.staff_exp_pool) if self.talent_point: TalentManager(server_id, char_id).add_talent_points(self.talent_point) if self.arena_point: Arena(server_id, char_id).add_point(self.arena_point) if self.territory_product: Territory(server_id, char_id).add_product(self.territory_product) if self.work_card: Territory(server_id, char_id).add_work_card(self.work_card) if self.energy: Energy(server_id, char_id).add(self.energy) if self.staff_recruit_score: StaffRecruit(server_id, char_id).add_score(self.staff_recruit_score) if self.station_exp: Plunder(server_id, char_id).add_station_exp(self.station_exp) if self.resource_data: _r = _Resource() _r.resource = dict(self.resource_data) _r.add(server_id, char_id)
def test_set_staffs_not_own(self): staff_ids = random.sample(ConfigStaff.INSTANCES.keys(), 10) try: Club(1, 1).set_match_staffs(staff_ids) except GameException as e: assert e.error_id == ConfigErrorMessage.get_error_id( "STAFF_NOT_EXIST") else: raise RuntimeError("can not be here!")
def test_set_policy_not_exists(self): def _get_policy(): while True: policy = random.randint(1, 1000) if policy not in ConfigPolicy.INSTANCES.keys(): return policy policy = _get_policy() club = Club(1, 1) try: club.set_policy(policy) except GameException as e: assert e.error_id == ConfigErrorMessage.get_error_id("POLICY_NOT_EXIST") doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club.policy': 1}) assert doc['club']['policy'] != policy else: raise Exception("can not be here")
def load_formation_staffs(self): # NOTE: 这段代码其实是从 Club.force_load_staffs 抄来的 from core.formation import Formation from core.unit import UnitManager from core.talent import TalentManager from core.collection import Collection from core.party import Party from core.inspire import Inspire self.formation_staffs = [] """:type: list[core.staff.Staff]""" sm = StaffManger(self.server_id, self.char_id) fm = Formation(self.server_id, self.char_id) um = UnitManager(self.server_id, self.char_id) ins = Inspire(self.server_id, self.char_id) staffs = sm.get_staffs_data() in_formation_staffs = self.in_formation_staffs() for k, v in in_formation_staffs.iteritems(): obj = Staff(self.server_id, self.char_id, k, staffs[k]) self.formation_staffs.append(obj) obj.policy = in_formation_staffs[k]['policy'] obj.formation_position = in_formation_staffs[k]['position'] unit_id = in_formation_staffs[k]['unit_id'] if unit_id: obj.set_unit(um.get_unit_object(unit_id)) club = Club(self.server_id, self.char_id, load_staffs=False) club.formation_staffs = self.formation_staffs working_staff_oids = self.working_staff_oids() for obj in self.formation_staffs: obj.check_qianban(working_staff_oids) obj.add_self_talent_effect(club) talent_effects_1 = TalentManager(self.server_id, self.char_id).get_talent_effects() talent_effects_2 = Collection(self.server_id, self.char_id).get_talent_effects() talent_effects_3 = fm.get_talent_effects() talent_effects_4 = Party(self.server_id, self.char_id).get_talent_effects() club.add_talent_effects(talent_effects_1) club.add_talent_effects(talent_effects_2) club.add_talent_effects(talent_effects_3) club.add_talent_effects(talent_effects_4) config_inspire_level_addition, config_inspire_step_addition = ins.get_addition_config( ) for obj in self.formation_staffs: obj.config_inspire_level_addition = config_inspire_level_addition obj.config_inspire_step_addition = config_inspire_step_addition obj.calculate()
def destroy(self, staff_id, tp): from core.club import Club from core.formation import Formation self._destroy_check(staff_id) staff = self.get_staff_object(staff_id) if not staff: raise GameException( ConfigErrorMessage.get_error_id("STAFF_NOT_EXIST")) if tp == 0: # 普通分解 items = staff.get_cost_items(70) crystal = ConfigStaffNew.get(staff.oid).crystal items.append((money_text_to_item_id('crystal'), crystal)) else: if staff.is_initial_state(): raise GameException( ConfigErrorMessage.get_error_id( "STAFF_CANNOT_DESTROY_INITIAL_STATE")) # TODO diamond count resource_classified = ResourceClassification.classify([ (money_text_to_item_id('diamond'), 50) ]) resource_classified.check_exist(self.server_id, self.char_id) resource_classified.remove( self.server_id, self.char_id, message="StaffManger.destroy:{0},{1}".format(staff.oid, tp)) items = staff.get_cost_items(100) resource_classified = ResourceClassification.classify(items) resource_classified.add(self.server_id, self.char_id, message="StaffManger.destroy:{0},{1}".format( staff.oid, tp)) if tp == 0: self.remove(staff_id) else: staff.reset() in_formation_staff_ids = Formation( self.server_id, self.char_id).in_formation_staffs().keys() if staff.id in in_formation_staff_ids: Club(self.server_id, self.char_id, load_staffs=False).force_load_staffs(send_notify=True) else: staff.calculate() staff.make_cache() self.send_notify(ids=[staff_id]) self.after_staffs_change_for_trig_signal() return resource_classified
def __init__(self, server_id, char_id): self.server_id = server_id self.char_id = char_id self.doc = MongoActivityPurchaseContinues.db(self.server_id).find_one({'_id': self.char_id}) if not self.doc: self.doc = MongoActivityPurchaseContinues.document() self.doc['_id'] = self.char_id MongoActivityPurchaseContinues.db(self.server_id).insert_one(self.doc) self.create_days = Club.create_days(self.server_id, self.char_id)
def after_staff_change(self, staff_id, force_load_staffs=False): # force_load_staffs: 只有这个staff的改变可能会影响到其他staff的时候,才为True from core.club import Club from core.plunder import Plunder from core.championship import Championship if force_load_staffs: Club(self.server_id, self.char_id, load_staffs=False).force_load_staffs(send_notify=True) else: Club(self.server_id, self.char_id).send_notify() p = Plunder(self.server_id, self.char_id) if p.find_way_id_by_staff_id(staff_id): p.send_formation_notify() c = Championship(self.server_id, self.char_id) if c.find_way_id_by_staff_id(staff_id): c.send_formation_notify()
def get_new_player_item_status(self, _id, login_days=None): if _id in self.doc['new_player']: return WELFARE_HAS_GOT if login_days is None: login_days = Club.create_days(self.server_id, self.char_id) if login_days >= _id: return WELFARE_CAN_GET return WELFARE_CAN_NOT
def test_match(self): staff_ids = ConfigStaff.INSTANCES.keys() staff_ids = random.sample(staff_ids, 10) sm = StaffManger(1, 1) for i in staff_ids: sm.add(i) Club(1, 1).set_match_staffs(staff_ids) Challenge(1, 1).start()
def test_set_policy_not_exists(self): def _get_policy(): while True: policy = random.randint(1, 1000) if policy not in ConfigPolicy.INSTANCES.keys(): return policy policy = _get_policy() club = Club(1, 1) try: club.set_policy(policy) except GameException as e: assert e.error_id == ConfigErrorMessage.get_error_id( "POLICY_NOT_EXIST") doc = MongoDB.get(1).character.find_one({'_id': 1}, {'club.policy': 1}) assert doc['club']['policy'] != policy else: raise Exception("can not be here")
def auto_increase_product(cls, server_id): level_limit = GlobalConfig.value("TERRITORY_BUILDING_AUTO_INCREASE_LEVEL") level_condition = {'level': {'$gte': level_limit}} char_ids = Club.get_recent_login_char_ids(server_id, other_conditions=[level_condition]) char_ids = [i for i in char_ids] docs = MongoTerritory.db(server_id).find({'_id': {'$in': char_ids}}) for doc in docs: t = Territory(server_id, doc['_id'], doc) t.building_auto_increase_product()
def __init__(self, server_id, char_id): self.server_id = server_id self.char_id = char_id self.doc = MongoActivityPurchaseContinues.db(self.server_id).find_one( {'_id': self.char_id}) if not self.doc: self.doc = MongoActivityPurchaseContinues.document() self.doc['_id'] = self.char_id MongoActivityPurchaseContinues.db(self.server_id).insert_one( self.doc) self.create_days = Club.create_days(self.server_id, self.char_id)
def set_staff(self, slot_id, staff_id): old_staff_id = super(Formation, self).set_staff(slot_id, staff_id) # 检测阵型是否还可用 if self.doc['using'] and not self.is_formation_valid(self.doc['using']): self.use_formation(0) else: self.send_slot_notify(slot_ids=[slot_id]) # NOTE 阵型改变,重新load staffs # 这里不直接调用 club.force_load_staffs 的 send_notify # 是因为这里 改变的staff 还可能包括下阵的 changed_staff_ids = self.in_formation_staffs().keys() if old_staff_id: changed_staff_ids.append(old_staff_id) club = Club(self.server_id, self.char_id, load_staffs=False) club.force_load_staffs() club.send_notify() StaffManger(self.server_id, self.char_id).send_notify(ids=changed_staff_ids) return old_staff_id
def after_change(self, uid): from core.formation import Formation from core.plunder import Plunder from core.championship import Championship self.load_units() unit = self.get_unit_object(uid) all_units = self.get_units_data() all_units_object = [ self.get_unit_object(k) for k, _ in all_units.iteritems() ] changed_units = {} for u in all_units_object: if u.config.race == unit.config.race: changed_units[u.id] = u self.send_notify_with_unit_objs(changed_units.values()) fm = Formation(self.server_id, self.char_id) _changed = False for k, v in fm.in_formation_staffs().iteritems(): if v['unit_id'] in changed_units: _changed = True break if _changed: club = Club(self.server_id, self.char_id, load_staffs=False) club.force_load_staffs(send_notify=True) _p = Plunder(self.server_id, self.char_id) if _p.find_way_id_by_unit_id(uid): _p.send_formation_notify() _c = Championship(self.server_id, self.char_id) if _c.find_way_id_by_unit_id(uid): _c.send_formation_notify()
def send_revenge_notify(self): notify = PlunderRevengeNotify() notify.remained_times = self.get_revenge_remained_times() for unique_id, real_id in self.doc['revenge_list']: notify_target = notify.target.add() notify_target.id = unique_id club = Club(self.server_id, real_id, load_staffs=False) target_plunder = Plunder(self.server_id, real_id) notify_target.name = club.name for way_id in [1, 2, 3]: way_object = target_plunder.get_way_object(way_id) club.formation_staffs = way_object.formation_staffs skill_sequence = way_object.get_skill_sequence() _club_match = ClubMatch(None, None, 3, None, None) notify_target_troop = notify_target.troop.add() notify_target_troop.MergeFrom(_club_match.make_club_troop_msg(club, skill_sequence)) MessagePipe(self.char_id).put(msg=notify)
def auto_add_plunder_times(cls, server_id): char_ids = Club.get_recent_login_char_ids(server_id) char_ids = [i for i in char_ids] condition = {'$and': [ {'_id': {'$in': char_ids}}, {'plunder_remained_times': {'$lt': PLUNDER_TIMES_RECOVER_LIMIT}} ]} MongoPlunder.db(server_id).update_many( condition, {'$inc': {'plunder_remained_times': 1}} )
def after_change(self, uid): from core.formation import Formation from core.plunder import Plunder from core.championship import Championship self.load_units() unit = self.get_unit_object(uid) all_units = self.get_units_data() all_units_object = [self.get_unit_object(k) for k, _ in all_units.iteritems()] changed_units = {} for u in all_units_object: if u.config.race == unit.config.race: changed_units[u.id] = u self.send_notify_with_unit_objs(changed_units.values()) fm = Formation(self.server_id, self.char_id) _changed = False for k, v in fm.in_formation_staffs().iteritems(): if v['unit_id'] in changed_units: _changed = True break if _changed: club = Club(self.server_id, self.char_id, load_staffs=False) club.force_load_staffs(send_notify=True) _p = Plunder(self.server_id, self.char_id) if _p.find_way_id_by_unit_id(uid): _p.send_formation_notify() _c = Championship(self.server_id, self.char_id) if _c.find_way_id_by_unit_id(uid): _c.send_formation_notify()
def create(request): name = request._proto.name flag = request._proto.flag session = request._game_session account_id = session.account_id server_id = session.server_id if Character.objects.filter(Q(account_id=account_id) & Q(server_id=server_id)).exists(): raise GameException(ConfigErrorMessage.get_error_id("CLUB_ALREADY_CREATED")) try: char = Character.objects.create( account_id=account_id, server_id=server_id, name=name, ) except IntegrityError: raise GameException(ConfigErrorMessage.get_error_id("CLUB_NAME_TAKEN")) # NOTE: 返回的时候middleware就是根据 request._game_session.char_id # 来从 队列里取 消息的。 所以这里得设置 request._game_session.char_id = char.id Club.create(server_id, char.id, name, flag) game_start_signal.send( sender=None, server_id=server_id, char_id=char.id, ) club = Club(server_id, char.id, load_staffs=False) response = CreateClubResponse() response.ret = 0 response.session = session.serialize() response.club.MergeFrom(club.make_protomsg()) response.create_at = club.create_at return ProtobufResponse(response)
def load_formation_staffs(self): # NOTE: 这段代码其实是从 Club.force_load_staffs 抄来的 from core.formation import Formation from core.unit import UnitManager from core.talent import TalentManager from core.collection import Collection from core.party import Party from core.inspire import Inspire self.formation_staffs = [] """:type: list[core.staff.Staff]""" sm = StaffManger(self.server_id, self.char_id) fm = Formation(self.server_id, self.char_id) um = UnitManager(self.server_id, self.char_id) ins = Inspire(self.server_id, self.char_id) staffs = sm.get_staffs_data() in_formation_staffs = self.in_formation_staffs() for k, v in in_formation_staffs.iteritems(): obj = Staff(self.server_id, self.char_id, k, staffs[k]) self.formation_staffs.append(obj) obj.policy = in_formation_staffs[k]['policy'] obj.formation_position = in_formation_staffs[k]['position'] unit_id = in_formation_staffs[k]['unit_id'] if unit_id: obj.set_unit(um.get_unit_object(unit_id)) club = Club(self.server_id, self.char_id, load_staffs=False) club.formation_staffs = self.formation_staffs working_staff_oids = self.working_staff_oids() for obj in self.formation_staffs: obj.check_qianban(working_staff_oids) obj.add_self_talent_effect(club) talent_effects_1 = TalentManager(self.server_id, self.char_id).get_talent_effects() talent_effects_2 = Collection(self.server_id, self.char_id).get_talent_effects() talent_effects_3 = fm.get_talent_effects() talent_effects_4 = Party(self.server_id, self.char_id).get_talent_effects() club.add_talent_effects(talent_effects_1) club.add_talent_effects(talent_effects_2) club.add_talent_effects(talent_effects_3) club.add_talent_effects(talent_effects_4) config_inspire_level_addition, config_inspire_step_addition = ins.get_addition_config() for obj in self.formation_staffs: obj.config_inspire_level_addition = config_inspire_level_addition obj.config_inspire_step_addition = config_inspire_step_addition obj.calculate()
def __init__(self, server_id, char_id): self.server_id = server_id self.char_id = char_id self.doc = MongoActivityNewPlayer.db(self.server_id).find_one({'_id': self.char_id}) if not self.doc: self.doc = MongoActivityNewPlayer.document() self.doc['_id'] = self.char_id MongoActivityNewPlayer.db(self.server_id).insert_one(self.doc) self.create_day = Club.create_days(server_id, char_id) today = get_start_time_of_today() self.create_start_date = today.replace(days=-(self.create_day - 1)) self.activity_end_at = self.create_start_date.replace(days=7).timestamp self.reward_end_at = self.create_start_date.replace(days=8).timestamp
def send_rank_reward(cls, server_id): char_ids = Club.get_recent_login_char_ids(server_id) # 加上一分钟,确保已经到了第二天 # 定时任务要是 23:59:59 启动,那天数判断就错了 weekday = arrow.utcnow().to(settings.TIME_ZONE).replace(minutes=1).weekday() for cid in char_ids: arena = Arena(server_id, cid) rank = arena.get_current_rank() # 每日奖励 config = ConfigArenaRankReward.get(rank) rc = ResourceClassification.classify(config.reward) m = MailManager(server_id, cid) m.add( config.mail_title, config.mail_content, attachment=rc.to_json(), ) if weekday == 0: # 周一发周奖励 config_weekly = ConfigArenaRankRewardWeekly.get(rank) rc = ResourceClassification.classify(config_weekly.reward) m = MailManager(server_id, cid) m.add( config_weekly.mail_title, config_weekly.mail_content, attachment=rc.to_json() ) if weekday == 0: docs = MongoArena.db(server_id).find( {'_id': {'$regex': '^\d+$'}}, {'_id': 1} ) default_score_doc = MongoArenaScore.db(server_id).find_one({'_id': ARENA_DEFAULT_SCORE}) for doc in docs: if doc['_id'] in default_score_doc['char_ids']: continue ArenaScore(server_id, int(doc['_id'])).set_score(ARENA_DEFAULT_SCORE)
def match(self, formation_slots=None): sweep_end_at = self.doc.get('sweep_end_at', 0) if sweep_end_at: raise GameException(ConfigErrorMessage.get_error_id("TOWER_IN_SWEEP_CANNOT_OPERATE")) level = self.get_current_level() if not level: raise GameException(ConfigErrorMessage.get_error_id("TOWER_ALREADY_ALL_PASSED")) f = Formation(self.server_id, self.char_id) if formation_slots: f.sync_slots(formation_slots) config = ConfigTowerLevel.get(level) club_one = Club(self.server_id, self.char_id) if config.talent_id: club_one.add_talent_effects([config.talent_id]) club_two = config.make_club() if not club_one.formation_staffs: club_one.load_staffs() if not club_two.formation_staffs: club_two.load_staffs() club_one.add_tower_temporary_talent_effects() club_one.make_temporary_staff_calculate() club_two.add_tower_temporary_talent_effects() club_two.make_temporary_staff_calculate() club_match = ClubMatch(club_one, club_two, 6, f.get_skill_sequence(), {}) msg = club_match.start() msg.key = str(level) msg.map_name = config.map_name return msg
def send_new_player_notify(self, _id=None): if _id: act = ACT_UPDATE ids = [_id] else: act = ACT_INIT ids = ConfigWelfareNewPlayer.INSTANCES.keys() login_days = Club.create_days(self.server_id, self.char_id) notify = WelfareNewPlayerNotify() notify.act = act for i in ids: notify_item = notify.items.add() notify_item.id = i notify_item.status = self.get_new_player_item_status(i, login_days=login_days) MessagePipe(self.char_id).put(msg=notify)
def _send_to_one_server(sid, m, attachment): if m.has_condition(): club_level = m.condition_club_level vip_level = m.condition_vip_level if m.condition_login_at_1: login_range = [ arrow.get(m.condition_login_at_1).timestamp, arrow.get(m.condition_login_at_2).timestamp, ] else: login_range = None exclude_char_ids = m.get_parsed_condition_exclude_chars() result_list = [] if club_level or login_range: result_list.append(Club.query_char_ids(sid, min_level=club_level, login_range=login_range)) if vip_level: result_list.append(VIP.query_char_ids(sid, vip_level)) if not result_list: return result = set(result_list[0]) for i in range(1, len(result_list)): result &= set(result_list[i]) result -= set(exclude_char_ids) to_char_ids = list(result) if not to_char_ids: return else: to_char_ids = ModelCharacter.objects.filter(server_id=sid).values_list('id', flat=True) to_char_ids = list(to_char_ids) SharedMail(sid).add(to_char_ids, m.title, m.content, attachment=attachment)
def generate(cls, server_id): char_ids = Club.get_recent_login_char_ids(server_id) leaderboard_docs = [] for cid in char_ids: obj = Club(server_id, cid) leaderboard_docs.append({ '_id': cid, 'level': obj.level, 'power': obj.power, }) db = MongoClubLeaderboard.db(server_id) db.delete_many({}) if leaderboard_docs: try: db.insert_many(leaderboard_docs) except BulkWriteError as e: pprint.pprint(e) raise e