Example #1
0
 def get_target_detail(self, entityID, detail=True):
     originID = entityID
     swaprank = self.get_rank(entityID)
     name = None
     if entityID < 0:
         entityID = int(str(entityID)[:-4])
         config = get_config(RobotNameConfig).get(swaprank)
         if config:
             name = config.name
     if detail:
         detail = get_opponent_detail(entityID, type=LineupType.DEF)
         if not detail.get("pets"):
             detail = get_opponent_detail(entityID, type=LineupType.ATK)
     else:
         detail = g_entityManager.get_players_info([entityID], [
             'entityID',
             'name',
             'level',
             'prototypeID',
             'vip',
             'borderID',
             'point',
             'faction_name',
         ])
         if detail:
             detail = detail[0]
     if detail:
         detail['swaprank'] = swaprank
         detail["entityID"] = originID
         if name:
             detail["name"] = name
     return detail
Example #2
0
File: rank.py Project: kimch2/x8623
 def get_last_rank_list(self, count=50):
     if not self.hists:
         return []
     try:
         if not self.is_open():
             st, ed = key = sorted(self.hists.keys())[-2]
         else:
             st, ed = key = sorted(self.hists.keys())[-1]
     except IndexError:
         st, ed = key = sorted(self.hists.keys())[-1]
     hist = self.hists[key]
     logger.debug("Rank list %s - %s", datetime.fromtimestamp(st),
                  datetime.fromtimestamp(ed))
     rankers = [
         k for k, v in sorted(hist['ranks'].items(),
                              key=lambda s: s[1]['rank'])
     ][:count]
     needs = [
         'entityID', 'name', 'level', 'career', 'prototypeID', 'totalbp',
         'rank_win_count', "factionID"
     ]
     thumbs = g_entityManager.get_players_info(rankers, needs)
     for thumb in thumbs:
         thumb['pvprank'] = rankers.index(thumb['entityID']) + 1
         thumb['totalbp'] = hist['ranks'].get(thumb['entityID'],
                                              {}).get("score", 0)
         detail = get_opponent_detail_all(thumb["entityID"])
         thumb.update(detail)
         thumb["pvpgrad"] = hist["ranks"].get(thumb['entityID'],
                                              {}).get("grad", 0)
         thumb["rank_win_count"] = hist["ranks"].get(thumb['entityID'],
                                                     {}).get(
                                                         "win_count", 0)
     thumbs.sort(key=lambda s: s['pvprank'])
     return thumbs
Example #3
0
 def faction_invite_infos(self, msgtype, body):
     factionID = self.player.factionID
     if not factionID:
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_HAS_NOT_FACTION)
     faction = Faction.simple_load(factionID, ['leaderID', 'inviteset'])
     if self.player.entityID != faction.leaderID:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FACTION_PERMISSION_DENIED)
     memberIDs = faction.inviteset
     thumbs = g_entityManager.get_players_info(memberIDs, [
         'entityID',
         'name',
         'career',
         'prototypeID',
         'totalfp',
         'level',
         'todayfp',
         'lastlogin',
     ])
     rsp = poem_pb.MemberInfos()
     now = int(time.time())
     for thumb in thumbs:
         last = int(time.mktime(thumb['lastlogin'].timetuple()))
         thumb['time'] = now - last
         # rs = get_lineup_details_atk(thumb['entityID'])
         detail = get_opponent_detail(thumb["entityID"])
         thumb.update(detail)
         rsp.members.add(**thumb)
     return success_msg(msgtype, rsp)
Example #4
0
 def faction_member_infos(self, msgtype, body):
     factionID = self.player.factionID
     if not factionID:
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_HAS_NOT_FACTION)
     faction = Faction.simple_load(factionID, ['memberset'])
     thumbs = g_entityManager.get_players_info(list(faction.memberset), [
         'entityID',
         'name',
         'career',
         'prototypeID',
         'totalfp',
         'level',
         'todayfp',
         'lastlogin',
         'joinFactionTime',
     ])
     rsp = poem_pb.MemberInfos()
     now = int(time.time())
     DAY = 86400
     for thumb in thumbs:
         last = int(time.mktime(thumb['lastlogin'].timetuple()))
         thumb['time'] = now - last
         if thumb['time'] >= DAY:
             thumb['todayfp'] = 0
         thumb['jointime'] = now - thumb['joinFactionTime']
         detail = get_opponent_detail(thumb["entityID"])
         detail['beMyFriend'] = thumb["entityID"] in self.player.friendset
         detail['applied'] = thumb["entityID"] in self.player.friend_applys
         thumb.update(detail)
     update_onlines(thumbs)
     rsp.members = thumbs
     return success_msg(msgtype, rsp)
Example #5
0
def get_players_info():
    # 取多个玩家数据
    if request.json:
        data = request.json
    else:
        data = request.POST.dict
    playerIDs = map(lambda s: int(s), data.get('playerIDs', []))
    attrs = data.get('attrs', [])
    from entity.manager import g_entityManager
    result = g_entityManager.get_players_info(playerIDs, attrs)
    return json.dumps(result)
Example #6
0
File: rank.py Project: kimch2/x8623
 def get_rank_list(self, rank, page=0, count=50):
     if rank <= count:
         start = '-inf'
         end = '+inf'
         offset = count * page
         rankscores = PlayerRankRanking.get_range_by_score(
             start,
             end,
             count=count + 1,  # 多取一条,用于判断是否有下一页
             offset=offset,
             withscores=True,
         )
         infos = convert_list_to_dict(rankscores)
         rankers = [c for i, c in enumerate(rankscores) if i % 2 == 0]
         offset += 1
     else:
         start = max(rank + count * page, 0)
         end = start + count
         rankers = PlayerRankRanking.get_by_range(
             start,
             end + 1,  # 多取一条,用于判断是否有下一页
         )
         offset = start
         scores = PlayerRankRanking.get_scores(rankers)
         infos = dict(zip(rankers, scores))
     needs = [
         'entityID', 'name', 'level', 'career', 'prototypeID', 'totalbp',
         'rank_win_count', "factionID"
     ]
     thumbs = g_entityManager.get_players_info(rankers, needs)
     for thumb in thumbs:
         thumb['pvprank'] = rankers.index(thumb['entityID']) + offset
         thumb['totalbp'] = infos.get(thumb['entityID'], 0)
         detail = get_opponent_detail_all(thumb["entityID"])
         thumb.update(detail)
     thumbs.sort(key=lambda s: s['pvprank'])
     return thumbs
Example #7
0
def get_opponent_detail(oppID, type=None):
    if is_zombie(oppID):
        return get_zombie(oppID)
    from lineup.manager import get_lineup_info
    from equip.manager import get_equipeds_infos
    from entity.manager import g_entityManager
    pets = []
    try:
        pets = get_lineup_info(oppID, pet_required_fields, type=type)
    except AttributeError:
        logger.error("Not exists oppID %d", oppID)
        return None
    for pos, pet in enumerate(pets):
        # pet['posIndex'] = pos
        pet['isTeamLeader'] = (pos == 0)
    detail = g_entityManager.get_players_info(
        [oppID],
        [
            'entityID',
            'name',
            'level',
            'career',
            'prototypeID',
            'strengthen_hp_level',
            'strengthen_at_level',
            'strengthen_ct_level',
            'strengthen_df_level',
            'rank_win_count',
            'vip',
            'credits',
            'faction_name',
            'lastlogin',
            # 'worldID',
            'pvpgrad',
            'groupID',
            'borderID',
            'point',
            'swap_win_count',
            'power_cache',
            'daily_kill_count',
            'daily_inspire_buff',
            'daily_max_win_count',
            'ambition',
            'vip_ambition',
            'player_equip1',
            'player_equip2',
            'player_equip3',
            'player_equip4',
            'player_equip5',
            'player_equip6',
            'inlay1',
            'inlay2',
            'inlay3',
            'inlay4',
            'inlay5',
            'inlay6',
            'fbprocess',
            'fbadvance',
            'campaign_honor_point',
        ])[0]
    detail['power'] = detail['power_cache']
    detail['pets'] = pets
    detail["equipeds"] = []
    for pet in pets:
        if pet:
            detail["equipeds"].extend(
                get_equipeds_infos(oppID,
                                   pet["entityID"],
                                   pet["posIndex"],
                                   detail=True))
    # detail["online"] = PlayerOnlineIndexing.get_pk(detail["entityID"])
    return detail
Example #8
0
def search_targets(player):
    # dvalue = 100 + player.power * 0.06
    # s, e = int(max(0, player.power - dvalue)), int(player.power + dvalue)
    # sample = set(
    #     PlayerPowerRanking.get_range_by_score(
    #         s, e, count=SAMPLE_COUNT)
    # ) - set([player.entityID])
    s, e = max(0, player.level - 2), player.level + 2
    sample = set(
        PlayerLevelRanking.get_range_by_score(
            s, e, count=SAMPLE_COUNT)
    ) - set([player.entityID])
    try:
        sample = random.sample(sample, DETAIL_COUNT)
    except ValueError:
        pass
    logger.debug("random sample is {}".format(sample))
    from player.formulas import get_mine_level
    # 过滤未开启的
    types = [i for i in poem_pb.MineType1, poem_pb.MineType2
             if get_mine_level(i, player.level) > 0] or [poem_pb.MineType1]
    targets = g_entityManager.get_players_info(sample, [
        "entityID", "name", "level", "prototypeID", 'mine_protect_time'
    ] + reduce(lambda x, y: x + y, [[
        "mine_products%d" % t,
        "mine_productivity%d" % t,
        "mine_time%d" % t,
        "mine_maximum%d" % t,
        "mine_safety%d" % t,
    ] for t in types]))
    _targets = []
    for target in targets:
        for t in types:
            _target = dict(target)
            _target['type'] = t
            _target['mine_products'] = _target['mine_products%d' % t]
            _target['mine_productivity'] = _target['mine_productivity%d' % t]
            _target['mine_time'] = _target['mine_time%d' % t]
            mine_level = get_mine_level(t, _target['level'])
            _target['mine_safety'] = get_mine_safety(t, mine_level)
            _target['mine_maximum'] = get_mine_maximum(t, mine_level)
            if not _target['mine_productivity']:
                continue
            _targets.append(_target)
    now = int(time.time())
    targets = sorted(_targets, key=lambda s: int(s['mine_time'] or now))
    chosens = []
    filterset = set()  # 过滤重复的玩家, 只能被匹配一次
    for t in targets:
        if t['entityID'] in filterset:
            continue
        if PlayerMineLock.locked(t["entityID"]):
            continue
        if t['mine_protect_time'] > now:
            continue
        if len(chosens) >= SEARCH_COUNT:
            break
        booty = calc_booty(now,
                           t['mine_products'],
                           t['mine_time'],
                           t['mine_productivity'],
                           t['mine_maximum'],
                           t['mine_safety']
                           )
        if booty > 0:
            chosens.append({
                'booty': max(booty, 0),
                'fought': False,
                'entityID': t['entityID'],
                'name': t['name'],
                'prototypeID': t['prototypeID'],
                'level': t['level'],
                'type': t['type'],
            })
            filterset.add(t['entityID'])
        if len(chosens) >= 2:
            break
    if len(chosens) < SEARCH_COUNT:
        lv = get_open_level("get_money1")
        zombies1 = get_zombies_by_level(max(player.level - 2, lv), hide=True)
        lv = get_open_level("get_exp1")
        zombies2 = get_zombies_by_level(max(player.level - 2, lv), hide=True)

        if not zombies1:
            zombies1 = get_zombies()
        logger.debug("zombies1 is {}".format(zombies1))
        if not zombies2:
            zombies2 = get_zombies()
        logger.debug("zombies2 is {}".format(zombies2))
        if zombies1 or zombies2:
            configs = get_config(PvpGroupConfig)
            while len(chosens) < SEARCH_COUNT:
                type = choice_one(types)
                if type == poem_pb.MineType1:
                    zombies = zombies1
                    booty_field = "rob_money"
                else:
                    zombies = zombies2
                    booty_field = "rob_soul"
                if not zombies1 and not zombies2:
                    break
                got = choice_one(zombies)
                config = configs[got]
                if not config.visible:
                    continue
                booty = getattr(config, booty_field, 0)
                zombies.remove(got)
                chosens.append({
                    'booty': booty,
                    'fought': False,
                    'entityID': config.ID,
                    'name': config.name,
                    'prototypeID': config.monster_id1,
                    'level': config.level,
                    'type': type,
                })
    random.shuffle(chosens)
    logger.debug("search targets is {}".format(chosens))
    player.mine_targets_detail_cache = chosens
    player.save()
    player.sync()
    return chosens
Example #9
0
 def battle(self, p, targetID, fight, raw, rsp):
     target_win_count = 0  # 对手连胜次数
     max_win_count = 0
     history = None  # 战斗记录
     shutdown = False
     self_message = ""
     full_message = ""
     horn = False
     red_message = ""
     red_count = 0
     self_shutdown_message = ""
     full_shutdown_message = ""
     peer_shutdown_message = ""
     count = 0
     rsp.before_daily_win_count = p.daily_win_count
     if fight.fightResult:  # 胜利
         # 终结对手连胜
         target_win_count = int(self.pool.execute(
             "GETSET", "daily_win_count_p{%d}" % targetID, 0) or 0)
         self.pool.execute("SET", "daily_dead_p{%d}" % targetID, 1)
         # 添加自己连胜
         daily_win_count = int(self.pool.execute(
             "INCRBY", "daily_win_count_p{%d}" % p.entityID, 1) or 0)
         p.clear_daily_win_count()
         # 更新最大连胜次数
         if p.daily_win_count > p.daily_max_win_count:
             p.daily_max_win_count = p.daily_win_count
             count = update_daily_rank(
                 PlayerDailyRankRanking, p.entityID, p.daily_max_win_count)
             # PlayerDailyRankRanking.update_score(
             #     p.entityID, p.daily_max_win_count)
             # 连胜任务
             from task.manager import on_dailypvp_count
             on_dailypvp_count(p, p.daily_max_win_count)
             # 取全服最大次数
             top = PlayerDailyRankRanking.get_range_by_score(
                 "-inf", "+inf", withscores=True, count=1)
             if top:
                 max_win_count = top[1]
             rsp.max_win_count = max_win_count
         daily_win_config = get_config(DailyWinConfig).get(
             p.daily_win_count)
         if not daily_win_config and \
                 p.daily_win_count > max(get_config(DailyWinConfig)):
             daily_win_config = get_config(
                 DailyWinConfig)[max(get_config(DailyWinConfig))]
         if daily_win_config:
             if not daily_win_config.multiple or (
                     daily_win_config.multiple and count == 1):
                 self_message = daily_win_config.single_desc
                 full_message = daily_win_config.all_desc
                 horn = daily_win_config.horn
                 if daily_win_config.red_paper:
                     red_message = daily_win_config.red_paper_desc
                     red_count = daily_win_config.red_paper_count
                     red_drop = daily_win_config.red_paper
         daily_lose_config = get_config(DailyLoseConfig).get(
             target_win_count)
         if not daily_lose_config and \
                 target_win_count > max(get_config(DailyLoseConfig)):
             daily_lose_config = get_config(
                 DailyLoseConfig)[max(get_config(DailyLoseConfig))]
         if daily_lose_config:
             self_shutdown_message = daily_lose_config.single_win_desc
             peer_shutdown_message = daily_lose_config.single_lose_desc
             full_shutdown_message = daily_lose_config.all_desc
         # 增加胜利次数
         p.daily_kill_count += 1
         # 奖励加成系数
         multi = min(40, 2 * daily_win_count) + min(
             80, target_win_count * 4)
         shutdown = target_win_count > 2
         history = {
             "active": False, "name": p.name,
             "win": not fight.fightResult,
             "faction_name": p.faction_name,
             "daily_win_count": p.daily_win_count,
             "fight": raw.encode("base64"),
             "prototypeID": p.prototypeID,
             "borderID": p.borderID,
             "shutdown": shutdown}
         for each in fight.player_team:
             pet = p.pets[each.entityID]
             if each.restHP == 0:
                 pet.daily_dead = True
             else:
                 pet.daily_restHP = each.restHP
             pet.save()
             pet.sync()
     else:
         if not p.daily_rank:
             PlayerDailyRankRanking.update_score(
                 p.entityID, p.daily_max_win_count)
         # 自己连胜被终结
         daily_win_count = int(self.pool.execute(
             "GETSET", "daily_win_count_p{%d}" % p.entityID, 0) or 0)
         # 死亡
         self.pool.execute("SET", "daily_dead_p{%d}" % p.entityID, 1)
         p.clear_daily_win_count()
         # 奖励加成系数
         multi = 0
         daily_lose_config = get_config(DailyLoseConfig).get(
             daily_win_count)
         if not daily_lose_config and \
                 daily_win_count > max(get_config(DailyLoseConfig)):
             daily_lose_config = get_config(
                 DailyLoseConfig)[max(get_config(DailyLoseConfig))]
         if daily_lose_config:
             self_shutdown_message = daily_lose_config.single_lose_desc
             peer_shutdown_message = daily_lose_config.single_win_desc
             full_shutdown_message = daily_lose_config.all_desc
     # 取对手数据
     data = g_entityManager.get_players_info(
         [targetID], [
             "entityID", "name", "daily_win_count",
             "faction_name", "prototypeID", "borderID"])[0]
     # 终结连胜
     shutdown = target_win_count > 2
     data.update({
         "active": True, "shutdown": shutdown,
         "win": fight.fightResult,
         "fight": raw.encode("base64")
     })
     # 自己的战斗记录
     p.daily_histories.appendleft(data)
     p.daily_histories.ltrim(0, MAX_HIST_LEN - 1)
     # 更新排名
     p.daily_rank = PlayerDailyRankRanking.get_rank(p.entityID)
     rewards = {}
     reward = open_reward(
         RewardType.DailyPVP, get_cons_value("DailyPVPDrop"))
     rewards = reward.apply_after()
     # 奖励加成
     if multi:
         for k, v in rewards.items():
             if isinstance(v, int) and k != 'exp':
                 rewards[k] = int(v * (100 + multi) / float(100))
     # 记录累计奖励
     apply_reward(p, rewards, type=RewardType.DailyPVP)
     combine_reward(rewards, [], data=p.daily_rewards)
     p.daily_rewards = dict(p.daily_rewards)
     p.daily_count += 1
     p.daily_cache_targetID = 0
     p.save()
     p.sync()
     # 添加直播
     self.add_live({
         "self_name": p.name,
         "self_prototypeID": p.prototypeID,
         "self_borderID": p.borderID,
         "peer_name": data["name"],
         "peer_prototypeID": data["prototypeID"],
         "peer_borderID": data["borderID"],
         "is_win": fight.fightResult,
     }, top=p.daily_rank and p.daily_rank <= 5)
     rsp.daily_win_count = p.daily_win_count
     rsp.rewards = build_reward(rewards)
     if self_message:
         self_message = self_message.format(data["name"], p.daily_win_count)
         g_redManager.send_red_message(
             p, self_message, to_self=True, type=RedType.Normal)
     if full_message:
         full_message = full_message.format(
             p.name, data["name"], p.daily_win_count)
         _type = RedType.Horn if horn else RedType.Normal
         g_redManager.send_red_message(
             p, full_message, type=_type)
     if red_count and red_message:
         if daily_win_count == 1:
             red_message = red_message.format(
                 p.name, red_count)
         else:
             red_message = red_message.format(
                 p.name, daily_win_count, red_count)
         g_redManager.send_red_message(
             p, red_message, red_drop=red_drop,
             red_count=red_count, type=RedType.Red)
     if full_shutdown_message:
         if fight.fightResult:
             full_shutdown_message = full_shutdown_message.format(
                 p.name, data["name"], target_win_count)
         else:
             full_shutdown_message = full_shutdown_message.format(
                 data["name"], p.name, daily_win_count)
         _type = RedType.Horn if horn else RedType.Normal
         g_redManager.send_red_message(
             p, full_shutdown_message, type=_type)
     if fight.fightResult:
         if self_shutdown_message:
             self_shutdown_message = self_shutdown_message.format(
                 data["name"], target_win_count)
             g_redManager.send_red_message(
                 p.entityID, self_shutdown_message,
                 to_self=True, type=RedType.Normal)
         if peer_shutdown_message:
             peer_shutdown_message = peer_shutdown_message.format(
                 p.name, target_win_count)
             g_redManager.send_red_message(
                 data["entityID"], peer_shutdown_message,
                 to_self=True, type=RedType.Normal)
     else:
         if self_shutdown_message:
             self_shutdown_message = self_shutdown_message.format(
                 data["name"], daily_win_count)
             g_redManager.send_red_message(
                 p.entityID, self_shutdown_message,
                 to_self=True, type=RedType.Normal)
         if peer_shutdown_message:
             peer_shutdown_message = peer_shutdown_message.format(
                 p.name, daily_win_count)
             g_redManager.send_red_message(
                 data["entityID"], peer_shutdown_message,
                 to_self=True, type=RedType.Normal)
     proxy.sync_daily_rank(targetID, history)
     return rewards