示例#1
0
def fighter_data(context):
    """获取对手的竞技场数据

    Args:
        fighter_id  # 对手的uid

    """
    fighter_id = context.get_parameter("fighter_id")

    if fighter_id.startswith("robot_"):
        context.result['mc'] = MsgCode['UserNotExist']
        return

    player = User.get(fighter_id)
    if not isinstance(player, User):
        context.result['mc'] = MsgCode['UserNotExist']
        return
    else:
        fighter = {}
        fighter['level'] = player.game_info.role_level
        fighter['array'] = user_helper.build_arena_hero_euqip_skill(player)
        fighter['talents'] = player.talent.talents
        fighter['warship'] = user_helper.build_warship_data(
            player.warship.ships, player.warship.team)
        fighter['group_name'] = GroupService.get_name_by_id(
            player.sid, player.group.group_id)

        context.result["data"] = fighter
示例#2
0
def members_train(context):
    """获取社团成员数据
    """
    ki_user = context.user

    uid = context.get_parameter("uid")

    group_id = ki_user.group.group_id
    if not judge_open_train(ki_user.sid, group_id):
        context.result['mc'] = MsgCode['UserModuleNotOpen']
        return

    member_data = GroupService.get_member_info_by_uid(ki_user.sid, group_id,
                                                      uid)
    # 检测目标是否在公会
    if not member_data:
        context.result['mc'] = MsgCode['GroupMemberNotExist']
        return

    user = User.get(uid)
    if not isinstance(user, User):
        context.result['mc'] = MsgCode['UserNotExist']
        return
    else:
        data = {}
        data["state"] = user.group.train_list
        ids = [i for i in user.group.train_list if i not in [0, -1]]
        heros = {}
        group_data = GroupService.find(ki_user.sid, group_id)
        for hid in ids:
            heros[hid] = count_group_train_hero(hid, user, group_data["level"])

        data["heros"] = heros

        context.result["data"] = data
示例#3
0
def fighter_data(context):
    """获取对手的竞技场数据

    Args:
        fighter_id  # 对手的uid

    """
    fighter_id = context.get_parameter("fighter_id")

    if fighter_id.startswith("robot_"):
        context.result['mc'] = MsgCode['UserNotExist']
        return

    player = User.get(fighter_id)
    if not isinstance(player, User):
        context.result['mc'] = MsgCode['UserNotExist']
        return
    else:
        fighter = {}
        fighter['level'] = player.game_info.role_level
        fighter['array'] = user_helper.build_arena_hero_euqip_skill(player)
        fighter['talents'] = player.talent.talents
        fighter['warship'] = user_helper.build_warship_data(player.warship.ships, player.warship.team)
        fighter['group_name'] = GroupService.get_name_by_id(player.sid, player.group.group_id)

        context.result["data"] = fighter
示例#4
0
    def build_yesterday_rank(sid):
        """
        """
        rank_key = rediskey_config.WORLD_BOSS_DMG_DAILY_RANK_KEY % sid
        ranking_list = redis_client.zrevrange(rank_key, 0, 10, withscores=True)
        if not ranking_list:
            return

        user_ranking = []
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['uid'] = value[0]
            rank_data['score'] = int(value[1])
            user = User.get(rank_data['uid'])
            if isinstance(user, User):
                rank_data['name'] = user.name
                rank_data['level'] = user.game_info.role_level
                rank_data['avatar'] = user.avatar

            user_ranking.append(rank_data)

        a = 1
        for x in user_ranking:
            x['rank'] = a
            a += 1

        cache_rank_name = rediskey_config.WORLD_BOSS_DMG_YES_RANK_KEY % sid
        while redis_client.llen(cache_rank_name) != 0:
            redis_client.delete(cache_rank_name)
            time.sleep(1)

        for rank in user_ranking:
            redis_client.lpush(cache_rank_name, rank)
示例#5
0
    def admin_vitual_pay(cls, params):
        """模拟充值
        """
        uid = params.get("uid")
        money = params.get("money")

        from apps.models.user import User
        user = User.get(uid)
        if isinstance(user, User):
            amount = int(money)
            try:
                act_helper.update_after_charge(user, amount * 10, amount)
            except:
                return {"mc": 900009}

            try:
                user.vip.update_card_when_charge(amount)

                user.game_info.diamond += amount * 10
                user.game_info.add_vip_exp(amount * 10, instant_save=True)

                charge_service.add_uid_paid_set(str(uid))

                _handle_daily_task_after_vitual_pay(user)
            except Exception,e:
                raise e
                return {"mc": 900009}

            return {"mc": 900002}
示例#6
0
def get_user_info(context):
    """获取其他玩家的基本数据

    Args:
        uid = "110000001"

    Returns:
        user_data
    """
    uid = context.get_parameter("uid")

    from apps.models.user import User
    user = User.get(uid)
    if not isinstance(user, User):
        context.result['mc'] = MsgCode['UserNotExist']
        return
    else:
        user_data = {}
        user_data['name'] = user.name
        user_data['level'] = user.game_info.role_level
        user_data['avatar'] = user.avatar
        user_data['vip'] = user.game_info.vip_level
        user_data['group_name'] = GroupService.get_name_by_id(
            user.sid, user.group.group_id)
        user_data['heros'] = user_helper.build_array_hero_data(
            user.array.mission, user.hero.heros)

        context.result["data"] = {}
        context.result["data"]["user_data"] = user_data
示例#7
0
    def kick(cls, sid, group_id, uid):
        """踢人

        1、给被踢玩家公会资讯信箱投递消息
        2、从公会除名
        3、公会成员数量-1
        3、公会日志增加一条记录
        4、公会聊天频道发广播
        5、给被踢玩家发邮件

        Args:
            uid 被踢出公会者ID

        """
        # player_group_box = player_group_box_key % (sid, uid)
        main_key = rediskey_config.GROUP_MAIN_KEY % (sid, group_id)
        member_key = rediskey_config.GROUP_MEMBER_KEY % (sid, group_id)

        user = User.get(uid)

        try:
            # redis_client.lpush(player_group_box, {"from_group_id": group_id, "action": 0, "time": int(time.time())})
            redis_client.hdel(member_key, uid)
            redis_client.hincrby(main_key, "member_number", -1)
            user.group.quit()

            # 清楚训练场数据
            redis_client.hdel(
                rediskey_config.GROUP_TRAIN_KEY % (sid, group_id), uid)
            redis_client.hdel(
                rediskey_config.GROUP_TRAIN_LOG_KEY % (sid, group_id), uid)
        except Exception, e:
            raise e
示例#8
0
    def appoint(cls, sid, group_id, acter_uid, member_uid, position):
        """任命成员

        Args:
            acter_uid 操作者UID
            member_uid 目标UID
            position 职务

        """
        user = User.get(member_uid)
        if position != GROUP_POSITION_MASTER:
            cls.set_member_info_by_uid(sid, group_id, member_uid, "position",
                                       position)
        else:
            cls.set_member_info_by_uid(sid, group_id, acter_uid, "position",
                                       GROUP_POSITION_MEMBER)
            cls.set_member_info_by_uid(sid, group_id, member_uid, "position",
                                       position)

            # 转让会长
            main_key = rediskey_config.GROUP_MAIN_KEY % (sid, group_id)
            redis_client.hset(main_key, "master", user.uid)

        cls.create_group_log(sid, group_id, GROUP_LOG_TYPE_APPOINT, member_uid,
                             user.name, int(time.time()), position)
示例#9
0
    def build_yesterday_rank(sid):
        """
        """
        rank_key = rediskey_config.WORLD_BOSS_DMG_DAILY_RANK_KEY % sid
        ranking_list = redis_client.zrevrange(rank_key, 0, 10, withscores=True)
        if not ranking_list:
            return

        user_ranking = []
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['uid'] = value[0]
            rank_data['score'] = int(value[1])
            user = User.get(rank_data['uid'])
            if isinstance(user, User):
                rank_data['name'] = user.name
                rank_data['level'] = user.game_info.role_level
                rank_data['avatar'] = user.avatar

            user_ranking.append(rank_data)

        a = 1
        for x in user_ranking:
            x['rank'] = a
            a += 1

        cache_rank_name = rediskey_config.WORLD_BOSS_DMG_YES_RANK_KEY % sid
        while redis_client.llen(cache_rank_name) != 0:
            redis_client.delete(cache_rank_name)
            time.sleep(1)

        for rank in user_ranking:
            redis_client.lpush(cache_rank_name, rank)
示例#10
0
def members_train(context):
    """获取社团成员数据
    """
    ki_user = context.user

    uid = context.get_parameter("uid")

    group_id = ki_user.group.group_id
    if not judge_open_train(ki_user.sid, group_id):
        context.result['mc'] = MsgCode['UserModuleNotOpen']
        return

    member_data = GroupService.get_member_info_by_uid(ki_user.sid, group_id, uid)
    # 检测目标是否在公会
    if not member_data:
        context.result['mc'] = MsgCode['GroupMemberNotExist']
        return

    user = User.get(uid)
    if not isinstance(user, User):
        context.result['mc'] = MsgCode['UserNotExist']
        return
    else:
        data = {}
        data["state"] = user.group.train_list
        ids = [i for i in user.group.train_list if i not in [0,-1]]
        heros = {}
        group_data = GroupService.find(ki_user.sid, group_id)
        for hid in ids:
            heros[hid] = count_group_train_hero(hid, user, group_data["level"])

        data["heros"] = heros

        context.result["data"] = data
示例#11
0
    def members(cls, sid, group_id, start=1, end=999):
        """获取公会全体成员

        Args:
            sid,group_id

        Returns:

        """
        key = rediskey_config.GROUP_MEMBER_KEY % (sid, group_id)
        result = redis_client.hgetall(key)
        if not result:
            return []
        else:
            simple_members = [
                cls.build_group_member_data(member)
                for member in result.values()
            ]
            simple_members1 = sorted(simple_members,
                                     key=lambda x: x["position"])
            targets = []
            for m in simple_members1[start - 1:end]:
                user = User.get(m["uid"])
                extra_fields = {
                    "login": user.last_request,
                    "fight": user.game_info.fight,
                    "level": user.game_info.role_level,
                    "name": user.name,
                    "avatar": user.avatar,
                }
                m.update(extra_fields)
                targets.append(m)

            return targets
示例#12
0
def build_trial_fighter_data(sid, uid):
    """构造试炼对手数据
    """
    fighter = {}
    fighter["uid"] = uid

    # 判断是否是机器人
    if uid.startswith("robot_"):
        robot_data = ArenaService.get_robot_data(sid, uid)
        fighter["name"] = robot_data["name"]

        robot_index = int(uid[6:])
        cfg_key = min([
            index for index in game_config.arena_formation_index_cfg
            if index >= robot_index
        ])

        fighter["fight"] = game_config.arena_formation_fight_cfg[cfg_key]
    else:
        user = User.get(uid)
        if isinstance(user, User):
            fighter['name'] = user.name
            fighter['avatar'] = user.avatar
            fighter['array'] = user_helper.build_arena_hero_euqip_skill(user)
            fighter['talents'] = user.talent.talents
            fighter['warship'] = user_helper.build_warship_data(
                user.warship.ships, user.warship.team)
            fighter['fight'] = user.arena.fight

    return fighter
示例#13
0
def _act_add_awards_mail(sid, actid):
    """
    """
    receivers = rank_service.get_all_players(sid)
    for uid in receivers:
        user = User.get(uid)
        if not isinstance(user, User):
            print "uid: [ %s ] not exist." % uid
        else:
            if actid not in user.activity.acts:
                continue

            act_data = user.activity.acts[actid]
            index_list = game_config.act_sample_detail_cfg.get(actid)
            awards_indexes = [
                index for index in index_list
                if utils.bit_test(act_data["canget"], index)
            ]
            if not awards_indexes:
                print "[act:%s] act add mail awards: receiver: %s, count: %s, award_level: 0, awards: {}" % (
                    actid, uid, act_data["data"])
                continue

            award_index = max(awards_indexes)
            award_cfg = game_config.act_detail_cfg.get("%s-%s" %
                                                       (actid, award_index))
            MailService.send_game(uid, 3008, [act_data["data"]],
                                  award_cfg["awards"])

            print "[act:%s] act add mail awards: receiver: %s, count: %s, award_level: %s, awards: %s" % (
                actid, uid, act_data["data"], award_index, award_cfg["awards"])
示例#14
0
 def get_master_name_by_uid(cls, uid):
     """获取公会会长名称
     """
     user = User.get(uid)
     if isinstance(user, User):
         return user.name
     else:
         return ""
示例#15
0
def _run_update_cached_arena_rank(sid, tag):
    """更新竞技场排行榜
    """
    ranking_name = rediskey_config.RANK_KEY_PREFIX % (sid, tag)
    ranking_list = redis_client.zrangebyscore(ranking_name,
                                              0,
                                              50,
                                              withscores=True,
                                              score_cast_func=int)

    user_ranking = []

    if ranking_list:
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = 0
            rank_data['uid'] = value[0]
            if rank_data['uid'].startswith("robot_"):
                robot_data = redis_client.hget(
                    rediskey_config.ARENA_ROBOTS_KEY % sid, rank_data['uid'])
                robot_data = eval(robot_data)
                rank_data["name"] = robot_data["name"]
            else:
                rank_data['score'] = value[1]
                user = User.get(rank_data['uid'])
                if isinstance(user, User):
                    rank_data['name'] = user.name
                    rank_data['level'] = user.game_info.role_level
                    rank_data['avatar'] = user.avatar
                    rank_data['group_name'] = _fetch_group_name_by_id(
                        user.sid, user.group.group_id)
                    rank_data['fight'] = sum([
                        user.hero.get_by_hero_id(hero_id)["fight"]
                        for hero_id in user.array.arena if hero_id
                    ])

            user_ranking.append(rank_data)

        a = 1
        for x in user_ranking:
            x['rank'] = a
            a += 1

    # 放入排行缓存列表中
    user_ranking.reverse()

    cache_rank_name = rediskey_config.RANK_CACHE_KEY_PREFIX % (sid, tag)
    while redis_client.llen(cache_rank_name) != 0:
        redis_client.delete(cache_rank_name)
        time.sleep(1)

    for rank in user_ranking:
        redis_client.lpush(cache_rank_name, rank)

    print 'ranking_name:', ranking_name
    print 'ranking_list:', ranking_list
    print 'user_ranking:', [(r["uid"], r["rank"]) for r in user_ranking[::-1]]
    print '=' * 60
示例#16
0
    def check_player_has_group(sid, uid):
        """审核通过时,检查玩家是否有公会

        1.检查玩家当前的group_id
        # 【暂时取缔】 2.检查玩家的邮箱中是否有已经被加入其他公会或者踢出公会的消息

        """
        user = User.get(uid)
        return True if user.group.group_id else False
示例#17
0
def help(context):
    """帮助其它社员加速
    """
    ki_user = context.user

    uid = context.get_parameter("uid")
    hero_id = context.get_parameter("hero_id")

    if not judge_open_train(ki_user.sid, ki_user.group.group_id):
        context.result['mc'] = MsgCode['UserModuleNotOpen']
        return

    # 不能给自己加速啊!!!
    if ki_user.uid == uid:
        context.result['mc'] = MsgCode['ParamIllegal']
        return

    if ki_user.daily_info.group_train_express_times >= GROUP_TRAIN_HELP_TIMES:
        context.result['mc'] = MsgCode['GroupTrainTimesMax']
        return

    group_id = ki_user.group.group_id
    member_data = GroupService.get_member_info_by_uid(ki_user.sid, group_id,
                                                      uid)
    # 检测目标是否在公会
    if not member_data:
        context.result['mc'] = MsgCode['GroupMemberNotExist']
        return

    user = User.get(uid)
    if not isinstance(user, User):
        context.result['mc'] = MsgCode['UserNotExist']
        return
    else:
        helped_times = int(
            GroupService.get_train_pos_times(ki_user.sid, group_id, uid))
        if helped_times >= GROUP_TRAIN_HELP_TIMES1:
            context.result['mc'] = MsgCode['GroupTrainHisTimesMax']
            return

        if hero_id not in user.group.train_list:
            context.result['mc'] = MsgCode['GroupTrainHeroNotOn']
            return

        GroupService.update_train_express_times(ki_user.sid, group_id, uid,
                                                hero_id, ki_user.name)

        user_logic.add_game_values(ki_user, {1: GROUP_TRAIN_HELP_GOLD})

        ki_user.daily_info.group_train_express_times += 1
        ki_user.daily_info.put()

    context.result['mc'] = MsgCode['GroupTrainHelpOtherSucc']
示例#18
0
def help(context):
    """帮助其它社员加速
    """
    ki_user = context.user

    uid = context.get_parameter("uid")
    hero_id = context.get_parameter("hero_id")

    if not judge_open_train(ki_user.sid, ki_user.group.group_id):
        context.result['mc'] = MsgCode['UserModuleNotOpen']
        return

    # 不能给自己加速啊!!!
    if ki_user.uid == uid:
        context.result['mc'] = MsgCode['ParamIllegal']
        return

    if ki_user.daily_info.group_train_express_times >= GROUP_TRAIN_HELP_TIMES:
        context.result['mc'] = MsgCode['GroupTrainTimesMax']
        return

    group_id = ki_user.group.group_id
    member_data = GroupService.get_member_info_by_uid(ki_user.sid, group_id, uid)
    # 检测目标是否在公会
    if not member_data:
        context.result['mc'] = MsgCode['GroupMemberNotExist']
        return

    user = User.get(uid)
    if not isinstance(user, User):
        context.result['mc'] = MsgCode['UserNotExist']
        return
    else:
        helped_times = int(GroupService.get_train_pos_times(ki_user.sid, group_id, uid))
        if helped_times >= GROUP_TRAIN_HELP_TIMES1:
            context.result['mc'] = MsgCode['GroupTrainHisTimesMax']
            return

        if hero_id not in user.group.train_list:
            context.result['mc'] = MsgCode['GroupTrainHeroNotOn']
            return

        GroupService.update_train_express_times(ki_user.sid, group_id, uid, hero_id, ki_user.name)

        user_logic.add_game_values(ki_user, {1: GROUP_TRAIN_HELP_GOLD})

        ki_user.daily_info.group_train_express_times += 1
        ki_user.daily_info.put()

    context.result['mc'] = MsgCode['GroupTrainHelpOtherSucc']
def _run_update_cached_arena_rank(sid, tag):
    """更新竞技场排行榜
    """
    ranking_name = rediskey_config.RANK_KEY_PREFIX % (sid, tag)
    ranking_list = redis_client.zrangebyscore(ranking_name, 0, 50, withscores=True, score_cast_func=int)

    user_ranking = []

    if ranking_list:
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = 0
            rank_data['uid'] = value[0]
            if rank_data['uid'].startswith("robot_"):
                robot_data = redis_client.hget(rediskey_config.ARENA_ROBOTS_KEY % sid, rank_data['uid'])
                robot_data = eval(robot_data)
                rank_data["name"] = robot_data["name"]
            else:
                rank_data['score'] = value[1]
                user = User.get(rank_data['uid'])
                if isinstance(user, User):
                    rank_data['name'] = user.name
                    rank_data['level'] = user.game_info.role_level
                    rank_data['avatar'] = user.avatar
                    rank_data['group_name'] = _fetch_group_name_by_id(user.sid, user.group.group_id)
                    rank_data['fight'] = sum([user.hero.get_by_hero_id(hero_id)["fight"] for hero_id in user.array.arena if hero_id])

            user_ranking.append(rank_data)

        a = 1
        for x in user_ranking:
            x['rank'] = a
            a += 1

    # 放入排行缓存列表中
    user_ranking.reverse()

    cache_rank_name = rediskey_config.RANK_CACHE_KEY_PREFIX % (sid, tag)
    while redis_client.llen(cache_rank_name) != 0:
        redis_client.delete(cache_rank_name)
        time.sleep(1)

    for rank in user_ranking:
        redis_client.lpush(cache_rank_name, rank)

    print 'ranking_name:', ranking_name
    print 'ranking_list:', ranking_list
    print 'user_ranking:', [(r["uid"], r["rank"])for r in user_ranking[::-1]]
    print '=' * 60
示例#20
0
def _run_update_cached_act_mission_rank(sid, tag):
    """更新缓存里的活动【冰封,烈焰,幻想】排行榜数据

    按照参加的时间先后
    """
    ranking_name = rediskey_config.RANK_KEY_PREFIX % (sid, tag)
    ranking_list = redis_client.zrevrange(ranking_name,
                                          -50,
                                          -1,
                                          withscores=True)

    user_ranking = []

    if ranking_list:
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = 0
            rank_data['uid'] = value[0]
            rank_data['score'] = int(value[1])
            user = User.get(rank_data['uid'])
            if isinstance(user, User):
                rank_data['name'] = user.name
                rank_data['level'] = user.game_info.role_level
                rank_data['avatar'] = user.avatar
                rank_data['group_name'] = _fetch_group_name_by_id(
                    user.sid, user.group.group_id)

            user_ranking.append(rank_data)

    a = 50
    for x in user_ranking:
        x['rank'] = a
        a -= 1

    cache_rank_name = rediskey_config.RANK_CACHE_KEY_PREFIX % (sid, tag)
    while redis_client.llen(cache_rank_name) != 0:
        redis_client.delete(cache_rank_name)
        time.sleep(1)

    for rank in user_ranking:
        redis_client.lpush(cache_rank_name, rank)

    print 'total number: ', redis_client.llen(cache_rank_name)
    print 'ranking_name:', ranking_name
    print 'ranking_list:', ranking_list

    print 'user_ranking:', [(r["uid"], r["rank"], r["score"])
                            for r in user_ranking[::-1]]
    print '=' * 60
示例#21
0
    def settle_after_boss_fight(cls, sid):
        """9:20检查并结算boss数据
        """
        key = rediskey_config.WORLD_BOSS_MAIN_KEY % sid
        if not redis_client.exists(key):
            cls.initial(sid)
        else:
            cls.award_today_rank_players(sid)       # 发今日伤害榜奖励

            old_data = cls.get(sid)
            # 英雄圣殿对应数据更新
            if old_data["uid"]:
                redis_client.zincrby(rediskey_config.WORLD_BOSS_HEROS_KEY % sid, old_data["uid"], 1)

            # boss被打死,版本增加,boss名称改变,清除总榜,今日榜-》昨日榜,boss血量更新
            if old_data["left_hp"] <= 0 or old_data["days"] >= WORLD_BOSS_CYCLE:
                total_rank_key = rediskey_config.WORLD_BOSS_DMG_TOTAL_RANK_KEY % (sid, old_data["version"]) # 获取这个boss总榜的第一名玩家
                uids = redis_client.zrange(total_rank_key,0,1)
                new_boss = {"name": pickle.dumps(""), "uid": "", "level": WORLD_BOSS_DEFAULT_LEVEL}
                if uids:
                    user = User.get(uids[0])
                    if isinstance(user, User):
                        group_name = GroupService.get_name_by_id(user.sid, user.group.group_id)
                        new_boss["name"], new_boss["uid"], new_boss["level"] = pickle.dumps("%s(%s)" % (user.name, group_name)), uids[0], user.game_info.role_level

                boss_new_hp = max(min(old_data["lose_hp"] * 1.15 * (1 + 0.2 * (3 - (old_data["days"] + 1))), WORLD_BOSS_HP_MAX), WORLD_BOSS_HP_MIN)
                main_data = {
                    "id": WORLD_BOSS_MONSTER_ID,
                    "type": WORLD_BOSS_TYPE_NPC if not old_data["version"] else WORLD_BOSS_TYPE_PLAYER,
                    "hp": int(boss_new_hp),
                    "days": 1,
                    "update": time.strftime('%Y%m%d%H'),
                    "version": old_data["version"] + 1,
                    "ender": "",
                    "lose_hp": 0,
                }

                main_data.update(new_boss)
                redis_client.hmset(key, main_data)          # 更新boss数据
                cls.award_total_rank_players(sid, old_data["version"])          # 发总榜奖励
                cls.award_boss_ender(sid, old_data["ender"])        # 发boss终结者
            else:
                redis_client.hincrby(key, "days", 1)

            # 生成旧榜单
            cls.build_yesterday_rank(sid)

            print "BOSS STATUS:"
            print cls.get(sid)
示例#22
0
    def admin_ban_account(cls, params):
        """禁号
        """
        uid = params.get("uid")
        times = params.get("times")

        from apps.models.user import User
        user = User.get(uid)
        if isinstance(user, User):
            user.ext_info.ban_account = int(time.time()) + int(times)
            user.ext_info.put()

            return {"mc": 900002}
        else:
            return {"mc": 900007}
示例#23
0
    def join_request(cls, sid, group_id, applyer_uid):
        """申请加入公会

        Args:
            applyer_uid 申请者UID

        """
        main_key = rediskey_config.GROUP_MAIN_KEY % (sid, group_id)
        request_key = rediskey_config.GROUP_REQUEST_KEY % (sid, group_id)

        user = User.get(applyer_uid)
        applyer = user.get_user_group_info()

        seq = redis_client.hincrby(main_key, "join_request_sequence")
        # applyer.update({"request_uid": seq, "state": GROUP_JOIN_REQUEST_STATE_DOING})
        applyer.update({"request_id": seq})
        redis_client.lpush(request_key, applyer)
示例#24
0
    def train_members(cls, sid, group_id, myid, start=1, end=999):
        """获取公会全体成员训练所数据

        Args:
            sid,group_id

        Returns:

        """
        key = rediskey_config.GROUP_MEMBER_KEY % (sid, group_id)
        result = redis_client.hgetall(key)
        if not result:
            return []
        else:
            simple_members = [
                cls.build_group_member_data(member)
                for member in result.values()
            ]
            simple_members1 = sorted(simple_members,
                                     key=lambda x: x["position"])
            targets = []
            for m in simple_members1[start - 1:end]:
                if m["uid"] == myid:
                    continue

                user = User.get(m["uid"])
                train_heros = [
                    i for i in user.group.train_list if i not in [0, -1]
                ]
                helped_times = GroupService.get_train_pos_times(
                    sid, group_id, m["uid"])
                if not train_heros or int(helped_times) >= 6:
                    continue

                user_fields = {
                    "level": user.game_info.role_level,
                    "name": user.name,
                    "avatar": user.avatar,
                    "train_heros": train_heros,
                }

                m.update(user_fields)
                targets.append(m)

            return targets
示例#25
0
    def build_fighter_data(cls, sid, fighter_ranks):
        """组装竞技场玩家或者机器人数据

        Args:
            fighter_ranks = [('110000020', 260), ('110000017', 255)]
        """
        final_fighters = []
        for rank_data in fighter_ranks:
            fighter = {}
            fighter["uid"] = rank_data[0]
            fighter["rank"] = int(rank_data[1])
            # 判断是否是机器人
            if fighter["uid"].startswith("robot_"):
                key = rediskey_config.ARENA_ROBOTS_KEY % sid
                robot_data = redis_client.hget(key, rank_data[0])
                if robot_data:
                    robot_data = eval(robot_data)
                    fighter["name"] = robot_data["name"]
                else:
                    fighter["name"] = "Robot."
            else:
                from apps.models.user import User
                user = User.get(fighter['uid'])
                if isinstance(user, User):
                    fighter['name'] = user.name
                    fighter['avatar'] = user.avatar
                    fighter['fight'] = user.arena.fight

                    # fighter['level'] = user.game_info.role_level
                    # fighter['vip'] = user.game_info.vip_level
                    # try:
                    #     fighter['array'] = user_helper.build_arena_hero_euqip_skill(user)
                    # except:
                    #     fighter['array'] = static_const.DEFAULT_USER_ARRAY

                    # fighter['talents'] = user.talent.talents
                    # fighter['warship'] = user_helper.build_warship_data(user.warship.ships, user.warship.team)
                    # fighter['group_name'] = GroupService.get_name_by_id(user.sid, user.group.group_id)

            # 查找被膜拜的数量
            fighter["admired"] = cls.get_fighter_admired(sid, fighter["uid"]) or 0
            final_fighters.append(fighter)

        return final_fighters
def _run_update_cached_act_mission_rank(sid, tag):
    """更新缓存里的活动【冰封,烈焰,幻想】排行榜数据

    按照参加的时间先后
    """
    ranking_name = rediskey_config.RANK_KEY_PREFIX % (sid, tag)
    ranking_list = redis_client.zrevrange(ranking_name, -50, -1, withscores=True)

    user_ranking = []

    if ranking_list:
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = 0
            rank_data['uid'] = value[0]
            rank_data['score'] = int(value[1])
            user = User.get(rank_data['uid'])
            if isinstance(user, User):
                rank_data['name'] = user.name
                rank_data['level'] = user.game_info.role_level
                rank_data['avatar'] = user.avatar
                rank_data['group_name'] = _fetch_group_name_by_id(user.sid, user.group.group_id)

            user_ranking.append(rank_data)

    a = 50
    for x in user_ranking:
        x['rank'] = a
        a -= 1

    cache_rank_name = rediskey_config.RANK_CACHE_KEY_PREFIX % (sid, tag)
    while redis_client.llen(cache_rank_name) != 0:
        redis_client.delete(cache_rank_name)
        time.sleep(1)

    for rank in user_ranking:
        redis_client.lpush(cache_rank_name, rank)

    print 'total number: ', redis_client.llen(cache_rank_name)
    print 'ranking_name:', ranking_name
    print 'ranking_list:', ranking_list

    print 'user_ranking:', [(r["uid"], r["rank"], r["score"])for r in user_ranking[::-1]]
    print '=' * 60
示例#27
0
    def admin_fix_gamer(cls, params):
        sid = params.get("sid")
        uids = params.get("uids")
        items = params.get("items")

        if str(uids) == "@all":
            receivers = rank_service.get_all_players(int(sid))
        else:
            receivers = str(uids).split("/")

        from apps.models.user import User
        from apps.logics import package as pack_logic
        for uid in receivers:
            user = User.get(uid)
            if isinstance(user, User):
                pack_logic.add_items(user, eval(items))
                _handle_daily_task_after_vitual_pay(user)

        return {"mc": 900002}
示例#28
0
    def rank(cls, rtype, sid, start, end):
        """读取排行榜数据

        rtype:
            1 - 今日排名
            2 - 总排名
            3 - 英雄圣殿
            4 - 昨日榜单
        """
        if rtype == WORLD_BOSS_RANK_YES:
            cache_rank_name = rediskey_config.WORLD_BOSS_DMG_YES_RANK_KEY % sid
            return redis_client.lrange(cache_rank_name, start - 1, end - 1)

        if rtype == WORLD_BOSS_RANK_TODAY:
            key = rediskey_config.WORLD_BOSS_DMG_DAILY_RANK_KEY % sid
        elif rtype == WORLD_BOSS_RANK_TOTAL:
            key = rediskey_config.WORLD_BOSS_MAIN_KEY % sid
            version = redis_client.hget(key, "version")
            key = rediskey_config.WORLD_BOSS_DMG_TOTAL_RANK_KEY % (sid,
                                                                   version)
        else:
            key = rediskey_config.WORLD_BOSS_HEROS_KEY % sid

        ranking_list = redis_client.zrevrange(key,
                                              start - 1,
                                              end - 1,
                                              withscores=True)
        ranks = []
        for index, i in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = start + index + 1
            rank_data['data'] = int(i[1])
            user = User.get(i[0])
            if isinstance(user, User):
                rank_data['name'] = user.name
                rank_data['level'] = user.game_info.role_level
                rank_data['group_name'] = GroupService.find(
                    user.sid, user.group.group_id)

            ranks.append(rank_data)

        return ranks
示例#29
0
    def get_fighter_name_avatar_by_uid(sid, uid):
        """根据uid获取竞技场对手的名字

        Args:
            uid
        """
        fighter_name = ""
        fighter_avatar = 0
        # 判断是否是机器人
        if uid.startswith("robot_"):
            robot_data = redis_client.hget(rediskey_config.ARENA_ROBOTS_KEY % sid, uid)
            robot_data = eval(robot_data)
            fighter_name = robot_data["name"]
            fighter_avatar = 0
        else:
            from apps.models.user import User
            user = User.get(uid)
            if isinstance(user, User):
                fighter_name = user.name
                fighter_avatar = user.avatar

        return fighter_name, fighter_avatar
示例#30
0
def fetch_user_info(uid):
    """根据玩家uid获取基础信息

    使用场景:
    1. 聊天信息,私聊对象的名字

    Args:
        uid 玩家UID

    """
    user_data = {}
    from apps.models.user import User
    user = User.get(uid)
    if isinstance(user, User):
        user_data['name'] = user.name
        user_data['level'] = user.game_info.role_level
        user_data['avatar'] = user.avatar
        user_data['vip'] = user.game_info.vip_level
        user_data['group_name'] = GroupService.get_name_by_id(
            user.sid, user.group.group_id)

    return user_data
示例#31
0
    def agree(cls, sid, group_id, joiner_id, atype=1):
        """同意加人申请 & 直接加入

        atype 1-审核批准别人加入 2-直接加入

        # 1、给加入玩家公会资讯信箱投递消息
        2、公会成员列表增加记录
        3、公会成员数量+1
        3、公会日志增加一条记录
        4、公会聊天频道发广播

        Args:
            joiner_id 加入者UID

        """
        # player_group_box = player_group_box_key % (sid, joiner_id)
        main_key = rediskey_config.GROUP_MAIN_KEY % (sid, group_id)
        member_key = rediskey_config.GROUP_MEMBER_KEY % (sid, group_id)

        # 取加入者数据
        # {"uid": "110000001", "name": "test", "fight": 5521, "avatar": 10005, "level": 15, "login": 1451475957}
        user = User.get(joiner_id)

        try:
            # pipe.lpush(player_group_box, {"from_group_id": group_id, "action": 1, "time": int(time.time()), "time": int(time.time())})
            redis_client.hset(member_key, joiner_id, {
                "uid": joiner_id,
                "position": GROUP_POSITION_MEMBER,
                "donate": 0
            })
            redis_client.hincrby(main_key, "member_number")

            # 被别人审核通过加入才需要执行这步骤
            if atype == 1:
                user.group.join(group_id)

        except Exception, e:
            raise e
示例#32
0
    def bird_rank(cls, sid, group_id, start=0, end=0):
        """小鸟排行榜
        """
        ranking_name = rediskey_config.GROUP_GAME_BIRD_KEY % (sid, group_id)
        ranking_list = redis_client.zrevrange(ranking_name,
                                              start - 1,
                                              end - 1,
                                              withscores=True)

        ranks = []
        for index, i in enumerate(ranking_list):
            uid, process, rank = i[0], i[1], index + start
            user = User.get(uid)
            tmp = {
                "rank": rank,
                "uid": uid,
                "process": process,
                "avatar": user.avatar,
                "name": user.name
            }
            ranks.append(tmp)

        return ranks
示例#33
0
    def tiger_rank(cls, sid, group_id, start=0, end=0):
        """老虎机排行榜
        """
        ranking_name = rediskey_config.GROUP_GAME_TIGER_KEY % (sid, group_id)
        ranking_list = redis_client.zrevrange(ranking_name,
                                              start - 1,
                                              end - 1,
                                              withscores=True)

        ranks = []
        for index, i in enumerate(ranking_list):
            uid, process, rank = i[0], int(i[1]), index + start
            user = User.get(uid)
            tmp = {
                "rank": rank,
                "uid": uid,
                "process": "%s-%s" % (process / 1000, process % 1000),
                "avatar": user.avatar,
                "name": user.name
            }
            ranks.append(tmp)

        return ranks
示例#34
0
    def rank(cls, rtype, sid, start, end):
        """读取排行榜数据

        rtype:
            1 - 今日排名
            2 - 总排名
            3 - 英雄圣殿
            4 - 昨日榜单
        """
        if rtype == WORLD_BOSS_RANK_YES:
            cache_rank_name = rediskey_config.WORLD_BOSS_DMG_YES_RANK_KEY % sid
            return redis_client.lrange(cache_rank_name, start-1, end-1)

        if rtype == WORLD_BOSS_RANK_TODAY:
            key = rediskey_config.WORLD_BOSS_DMG_DAILY_RANK_KEY % sid
        elif rtype == WORLD_BOSS_RANK_TOTAL:
            key = rediskey_config.WORLD_BOSS_MAIN_KEY % sid
            version = redis_client.hget(key, "version")
            key = rediskey_config.WORLD_BOSS_DMG_TOTAL_RANK_KEY % (sid, version)
        else:
            key = rediskey_config.WORLD_BOSS_HEROS_KEY % sid

        ranking_list = redis_client.zrevrange(key, start-1, end-1, withscores=True)
        ranks = []
        for index,i in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = start + index + 1
            rank_data['data'] = int(i[1])
            user = User.get(i[0])
            if isinstance(user, User):
                rank_data['name'] = user.name
                rank_data['level'] = user.game_info.role_level
                rank_data['group_name'] = GroupService.find(user.sid, user.group.group_id)

            ranks.append(rank_data)

        return ranks
示例#35
0
def build_arena_hero_snapshot(uid):
    """竞技场replay 玩家当时快照
    """
    datas = []

    if uid.startswith("robot_"):
        pass
    else:
        user = User.get(uid)
        if isinstance(user, User):
            hero_datas = copy.deepcopy(user.hero.heros)
            if user.array.arena == [0]*6:
                array = user.array.mission
            else:
                array = user.array.arena

            for hero_id in array:
                if hero_id:
                    hero_data = copy.deepcopy(hero_datas.get(hero_id))
                    datas.append(hero_data)
                else:
                    datas.append(0)

    return datas
示例#36
0
def build_arena_hero_snapshot(uid):
    """竞技场replay 玩家当时快照
    """
    datas = []

    if uid.startswith("robot_"):
        pass
    else:
        user = User.get(uid)
        if isinstance(user, User):
            hero_datas = copy.deepcopy(user.hero.heros)
            if user.array.arena == [0] * 6:
                array = user.array.mission
            else:
                array = user.array.arena

            for hero_id in array:
                if hero_id:
                    hero_data = copy.deepcopy(hero_datas.get(hero_id))
                    datas.append(hero_data)
                else:
                    datas.append(0)

    return datas
示例#37
0
def trial_rank_send_mail_awards(sid):
    """每日凌晨五点结算终极试炼排行榜,给玩家发送排行奖励
    """
    all_players = get_all_players(sid)

    rank_name = rediskey_config.RANK_KEY_PREFIX % (sid, RANK_KEY_MAPPING[RANK_TRIAL])
    ranking_list = redis_client.zrevrange(rank_name, 0, -1, withscores=True)

    if not ranking_list:
        return

    user_ranking = []
    from apps.models.user import User
    for key, value in enumerate(ranking_list):
        rank_data = {'uid': value[0], 'score': int(value[1])}
        user = User.get(rank_data['uid'])
        if user:
            rank_data['score1'] = user.trial.daily_scores
        else:
            rank_data['score1'] = 0

        user_ranking.append(rank_data)

    def tsorted(x,y):
        if x["score"] == y["score"]:
           return y["score1"] - x["score1"]
        else:
           return y["score"] - x["score"]

    user_ranking = sorted(user_ranking, cmp=tsorted)

    a = 1
    for x in user_ranking:
        x['rank'] = a
        a += 1

    user_ranking1 = {}
    for i in user_ranking:
        user_ranking1[str(i['uid'])] = i['rank']

    for uid in all_players:
        user = User.get(uid)
        if not user or user.game_info.role_level <= game_config.user_func_cfg.get(4020, 999):
            continue

        player_rank = user_ranking1.get(uid, 0)
        if player_rank < 0:
            continue

        try:
            award_index = min([rank for rank in game_config.trial_mail_award_cfg if rank >= player_rank])
        except:
            award_index = -1

        if award_index < 0:
            continue

        cfg = game_config.trial_mail_award_cfg.get(award_index)
        MailService.send_game(uid, 1003, [player_rank], cfg["awards"])

        print "trial_rank_awards: receiver: %s, rank: %s, awards: %s" % (uid, player_rank, cfg["awards"])

    trial_delete_daily_rank(sid)
def _run_update_cached_group_rank(sid, tag):
    """更新公会排行榜

    抓取所有公会数据 - 按等级排 - 按总战力排 - 存放进cache里

    """
    ranking_name = rediskey_config.RANK_KEY_PREFIX % (sid, tag)
    ranking_list = redis_client.zrevrange(ranking_name, 0, -1, withscores=True)

    group_rank = []

    if ranking_list:
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = 0
            rank_data['group_id'] = int(value[0])
            rank_data['exp'] = int(value[1])

            group_data = GroupService.find(sid, value[0])
            if group_data:
                rank_data['name'] = group_data["name"]
                rank_data['icon'] = group_data["icon"]
                rank_data['level'] = group_data["level"]
                master = User.get(group_data["master"])
                rank_data['master'] = master.name if isinstance(master, User) else "会长"
                rank_data['member_number'] = group_data["member_number"]
                rank_data['join_level_limit'] = group_data["join_level_limit"]
                rank_data['join_state'] = group_data["join_state"]
                rank_data['notice'] = group_data["notice"]

                fight = 0
                for uid in [member["uid"] for member in GroupService.members(sid, int(value[0])) if isinstance(member, dict)]:
                    try:
                        user = User.get(uid)
                        fight += user.game_info.fight
                    except:
                        fight += 0

                rank_data['fight'] = fight

            group_rank.append(rank_data)

    def gsorted(x,y):
        if x["level"] == y["level"]:
           return y["fight"] - x["fight"]
        else:
           return y["level"] - x["level"]

    group_rank = sorted(group_rank, cmp=gsorted)

    a = 1
    for x in group_rank:
        x['rank'] = a
        a += 1
    # 放入排行缓存列表中
    group_rank.reverse()

    cache_rank_name = rediskey_config.RANK_CACHE_KEY_PREFIX % (sid, tag)
    while redis_client.llen(cache_rank_name) != 0:
        redis_client.delete(cache_rank_name)
        time.sleep(1)

    # 放入排行缓存列表中
    for rank in group_rank:
        redis_client.lpush(cache_rank_name, rank)

    print 'ranking_name:', cache_rank_name
    print 'ranking_list:', group_rank
    print '=' * 60
def _run_update_cached_rank(sid, tag):
    """更新缓存里的战力排行榜
    """
    ranking_name = rediskey_config.RANK_KEY_PREFIX % (sid, tag)
    ranking_list = redis_client.zrevrange(ranking_name, 0, 50, withscores=True)

    user_ranking = []

    if ranking_list:
        for key, value in enumerate(ranking_list):
            rank_data = {}
            rank_data['rank'] = 0
            # 机甲排行榜需要“机甲ID”这个特殊处理下
            if tag == "hero":
                info = value[0].split("_")
                rank_data['score'] = value[1]
                rank_data['uid'] = info[0]
                rank_data['hid'] = int(info[1])
                user = User.get(rank_data['uid'])
                if isinstance(user, User):
                    rank_data['name'] = user.name
                    rank_data['group_name'] = _fetch_group_name_by_id(user.sid, user.group.group_id)
                    rank_data['level'] = user.hero.heros.get(int(info[1]))["level"]
                    rank_data['quality'] = user.hero.heros.get(int(info[1]))["quality"]
                    rank_data['star'] = user.hero.heros.get(int(info[1]))["star"]

            else:
                rank_data['uid'] = value[0]
                rank_data['score'] = int(value[1])
                user = User.get(rank_data['uid'])
                if isinstance(user, User):
                    rank_data['name'] = user.name
                    rank_data['level'] = user.game_info.role_level
                    rank_data['avatar'] = user.avatar
                    if tag == "trial":
                        rank_data['score1'] = user.trial.daily_scores
                    else:
                        rank_data['group_name'] = _fetch_group_name_by_id(user.sid, user.group.group_id)

            user_ranking.append(rank_data)

    # 终极试炼排序潜规则:若层数相同 则按积分排序
    if tag == "trial":
        def tsorted(x,y):
            if x["score"] == y["score"]:
               return y["score1"] - x["score1"]
            else:
               return y["score"] - x["score"]

        user_ranking = sorted(user_ranking, cmp=tsorted)

    a = 1
    for x in user_ranking:
        x['rank'] = a
        a += 1

    # 放入排行缓存列表中
    user_ranking.reverse()

    cache_rank_name = rediskey_config.RANK_CACHE_KEY_PREFIX % (sid, tag)
    while redis_client.llen(cache_rank_name) != 0:
        redis_client.delete(cache_rank_name)
        time.sleep(1)

    for rank in user_ranking:
        redis_client.lpush(cache_rank_name, rank)

    print 'total number: ', redis_client.llen(cache_rank_name)
    print 'ranking_name:', ranking_name
    print 'ranking_list:', ranking_list

    if tag == "hero":
        print 'user_ranking:', [(r["uid"], r["hid"], r["rank"], r["score"])for r in user_ranking[::-1]]
    else:
        print 'user_ranking:', [(r["uid"], r["rank"], r["score"])for r in user_ranking[::-1]]

    print '=' * 60
BASE_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))

sys.path.insert(0, BASE_DIR)
sys.path.insert(0, BASE_DIR + '/apps')

import settings
os.environ.setdefault('KIMECH_APP_SETTINGS', 'settings.prod')

from libs.rklib.core import app
app.init(plat = "ios",
         storage_cfg_file = BASE_DIR + "/apps/configs/app_config/storage.conf",
         logic_cfg_file = BASE_DIR + "/apps/configs/app_config/logic.conf",
         model_cfg_file = BASE_DIR + "/apps/configs/app_config/model.conf")

from apps.models.user import User
from apps.services import rank as rank_service

receivers = rank_service.get_all_players(sid)
for i in receivers:
    user = User.get(i)
    if isinstance(user, User):
        print "%s not exist." % i
        continue

    actid = 3003
    if actid not in user.activity.acts:
        continue

    act_data = user.activity.acts[actid]
示例#41
0
    def settle_after_boss_fight(cls, sid):
        """9:20检查并结算boss数据
        """
        key = rediskey_config.WORLD_BOSS_MAIN_KEY % sid
        if not redis_client.exists(key):
            cls.initial(sid)
        else:
            cls.award_today_rank_players(sid)  # 发今日伤害榜奖励

            old_data = cls.get(sid)
            # 英雄圣殿对应数据更新
            if old_data["uid"]:
                redis_client.zincrby(
                    rediskey_config.WORLD_BOSS_HEROS_KEY % sid,
                    old_data["uid"], 1)

            # boss被打死,版本增加,boss名称改变,清除总榜,今日榜-》昨日榜,boss血量更新
            if old_data["left_hp"] <= 0 or old_data["days"] >= WORLD_BOSS_CYCLE:
                total_rank_key = rediskey_config.WORLD_BOSS_DMG_TOTAL_RANK_KEY % (
                    sid, old_data["version"])  # 获取这个boss总榜的第一名玩家
                uids = redis_client.zrange(total_rank_key, 0, 1)
                new_boss = {
                    "name": pickle.dumps(""),
                    "uid": "",
                    "level": WORLD_BOSS_DEFAULT_LEVEL
                }
                if uids:
                    user = User.get(uids[0])
                    if isinstance(user, User):
                        group_name = GroupService.get_name_by_id(
                            user.sid, user.group.group_id)
                        new_boss["name"], new_boss["uid"], new_boss[
                            "level"] = pickle.dumps(
                                "%s(%s)" % (user.name, group_name)
                            ), uids[0], user.game_info.role_level

                boss_new_hp = max(
                    min(
                        old_data["lose_hp"] * 1.15 *
                        (1 + 0.2 * (3 - (old_data["days"] + 1))),
                        WORLD_BOSS_HP_MAX), WORLD_BOSS_HP_MIN)
                main_data = {
                    "id": WORLD_BOSS_MONSTER_ID,
                    "type": WORLD_BOSS_TYPE_NPC
                    if not old_data["version"] else WORLD_BOSS_TYPE_PLAYER,
                    "hp": int(boss_new_hp),
                    "days": 1,
                    "update": time.strftime('%Y%m%d%H'),
                    "version": old_data["version"] + 1,
                    "ender": "",
                    "lose_hp": 0,
                }

                main_data.update(new_boss)
                redis_client.hmset(key, main_data)  # 更新boss数据
                cls.award_total_rank_players(sid, old_data["version"])  # 发总榜奖励
                cls.award_boss_ender(sid, old_data["ender"])  # 发boss终结者
            else:
                redis_client.hincrby(key, "days", 1)

            # 生成旧榜单
            cls.build_yesterday_rank(sid)

            print "BOSS STATUS:"
            print cls.get(sid)
示例#42
0
    def admin_query_player_info(cls, params):
        sid = params.get("sid")
        uid = params.get("uid", "")
        uname = params.get("uname", "")
        dtype = params.get("type", "user")

        from apps.models.user import User
        # uid为空 则根据uname查询玩家数据
        if uid:
            target_user = User.get(uid)
        elif uname:
            target_uid = name_service.get_uid_by_name(uname)
            target_user = User.get(target_uid)
        else:
            target_user = None

        if not target_user:
            return {"mc": 900007}

        data = {}
        if str(dtype) == "user":
            user_attrs = ["uid","name","update_name_times","avatar",
                           "user_sign","account_id","platform","sid",
                           "state","type","create_time","last_request",
                           "last_sign_time","total_login_days","login_history_dates",
                           "used_cdkey_tags", "game_info", "ext_info"]

        elif str(dtype) == "hero":
            user_attrs = ["hero", "equip", "skill", "spirit"]

        elif str(dtype) == "group":
            attr_obj = eval("target_user.group")
            data["group"] = {}
            for attr1 in attr_obj.all_def_attrs:
                if attr1 not in ["uid"]:
                    data["group"][attr1] = getattr(attr_obj, attr1)

            if not target_user.group.group_id:
                group = {}
            else:
                group = GroupService.find(target_user.sid, target_user.group.group_id)

            data["group_data"] = {}
            data["group_data"]["base"] = group

            data["uid"] = target_user.uid
            data["name"] = target_user.name

            data["mc"] = 900002
            data["info"] = pickle.dumps(data)

            return data

        else:
            user_attrs = [dtype]

        for attr in user_attrs:
            if type(eval("target_user.%s" % attr)) in [unicode, str, int, dict, list, set, tuple]:
                data[attr] = eval("target_user.%s" % attr)
            else:
                attr_obj = eval("target_user.%s" % attr)
                data[attr] = {}
                for attr1 in attr_obj.all_def_attrs:
                    if attr1 not in ["uid"]:
                        data[attr][attr1] = getattr(attr_obj, attr1)

            data["uid"] = target_user.uid
            data["name"] = target_user.name

        data["mc"] = 900002
        data["info"] = pickle.dumps(data)

        return data
示例#43
0
                "create_time", "last_request", "last_sign_time",
                "total_login_days", "login_history_dates", "used_cdkey_tags",
                "game_info", "vip", "daily_info", "task", "package", "hero",
                "equip", "skill", "spirit", "array", "mission", "talent",
                "warship", "mall", "group", "arena", "trial", "sign",
                "activity"
            ]

            helpstr1 += """            --args=%s,%s""" % ("1", user_attrs)
            tmp = sys.argv[5].split("--args=")
            args = tmp[1].split(",")
            if args[1] not in user_attrs:
                raise

            UID = "%s%s" % (SID, 10000000 + int("%07d" % int(args[0])))
            user = User.get(UID)
            if not isinstance(user, User):
                print "uid: [ %s ] not exist." % UID
            else:
                if type(eval("user.%s" % args[1])) in [
                        unicode, str, int, dict, list, set, tuple
                ]:
                    data = eval("user.%s" % args[1])
                    # 时间格式 特殊处理下 方便查看
                    if args[1] in [
                            "create_time", "last_request", "last_sign_time"
                    ]:
                        dtime = time.localtime(int(data))
                        data = time.strftime("%F %H:%M:%S", dtime)

                    print "[ %s ]: %s" % (args[1], data)
示例#44
0
def trial_rank_send_mail_awards(sid):
    """每日凌晨五点结算终极试炼排行榜,给玩家发送排行奖励
    """
    all_players = get_all_players(sid)

    rank_name = rediskey_config.RANK_KEY_PREFIX % (
        sid, RANK_KEY_MAPPING[RANK_TRIAL])
    ranking_list = redis_client.zrevrange(rank_name, 0, -1, withscores=True)

    if not ranking_list:
        return

    user_ranking = []
    from apps.models.user import User
    for key, value in enumerate(ranking_list):
        rank_data = {'uid': value[0], 'score': int(value[1])}
        user = User.get(rank_data['uid'])
        if user:
            rank_data['score1'] = user.trial.daily_scores
        else:
            rank_data['score1'] = 0

        user_ranking.append(rank_data)

    def tsorted(x, y):
        if x["score"] == y["score"]:
            return y["score1"] - x["score1"]
        else:
            return y["score"] - x["score"]

    user_ranking = sorted(user_ranking, cmp=tsorted)

    a = 1
    for x in user_ranking:
        x['rank'] = a
        a += 1

    user_ranking1 = {}
    for i in user_ranking:
        user_ranking1[str(i['uid'])] = i['rank']

    for uid in all_players:
        user = User.get(uid)
        if not user or user.game_info.role_level <= game_config.user_func_cfg.get(
                4020, 999):
            continue

        player_rank = user_ranking1.get(uid, 0)
        if player_rank < 0:
            continue

        try:
            award_index = min([
                rank for rank in game_config.trial_mail_award_cfg
                if rank >= player_rank
            ])
        except:
            award_index = -1

        if award_index < 0:
            continue

        cfg = game_config.trial_mail_award_cfg.get(award_index)
        MailService.send_game(uid, 1003, [player_rank], cfg["awards"])

        print "trial_rank_awards: receiver: %s, rank: %s, awards: %s" % (
            uid, player_rank, cfg["awards"])

    trial_delete_daily_rank(sid)