예제 #1
0
 def buy_group_package(self, buy_type):
     if buy_type not in get_group_buy_conf().keys():
         defer.returnValue(BUY_GROUP_TYPE_WRONG)
     _conf = get_group_buy_conf(buy_type)
     _stream = yield redis.hget(DICT_GROUP_BUY_PERSON_INFO, self.cid)
     _data = loads(_stream)
     #[[buy_count, [0,0,0,0]], ......]
     bought_count, _info = _data[buy_type - 1]
     if bought_count + 1 > _conf["LimitNum"]:
         defer.returnValue(GROUP_BUY_MAX_COUNT)
     if self.user.credits < _conf["CurrentPrice"]:
         defer.returnValue(CHAR_CREDIT_NOT_ENOUGH)
     yield self.user.consume_credits(_conf["CurrentPrice"], WAY_GROUP_BUY)
     bought_count += 1
     _st = yield redis.hget(DICT_GROUP_BUY_INFO, buy_type)
     _datas = loads(_st)
     #buy_type:buy_num
     _total_buy_count = _datas
     if bought_count == 1:
         _total_buy_count += 1
     _data[buy_type - 1] = [bought_count, _info]
     yield redis.hset(DICT_GROUP_BUY_PERSON_INFO, self.cid, dumps(_data))
     yield redis.hset(DICT_GROUP_BUY_INFO, buy_type,
                      dumps(_total_buy_count))
     _item_type, _item_id, _item_num = _conf['ItemType'], _conf[
         'ItemID'], _conf['ItemNum']
     _res = yield item_add(self.user,
                           ItemType=_item_type,
                           ItemID=_item_id,
                           ItemNum=_item_num,
                           AddType=WAY_GROUP_BUY)
     _result = (buy_type, _total_buy_count, bought_count, _res[1][0],
                self.user.credits)
     defer.returnValue(_result)
예제 #2
0
def login(p, req):
    log.warn("=======req: ", req)
    machine_code, = req
    if not machine_code:
        defer.returnValue((MACHINE_CODE_ERROR, {}))

    uid = yield redis.hget(HASH_MACHINE_CODE_REGISTERED, machine_code)
    p.uid = uid
    info = dict()
    # 创建新玩家
    if not uid:
        #TODO random nickname
        nickname = machine_code
        character_mgr = Character(0, machine_code, nickname)
        yield character_mgr.new(machine_code, nickname)

        uid = character_mgr.uid
        yield redis.hset(HASH_NICKNAME_REGISTERED, nickname, uid)
        yield redis.hset(HASH_MACHINE_CODE_REGISTERED, machine_code, uid)
        info = character_mgr.info()
    else:
        # 检查已登录时, 释放旧的连接 提示有重复登陆
        user = g_UserMgr.getUserLogined(uid, p)
        if not user:
            nickname = yield redis.hget(HASH_NICKNAME_REGISTERED, uid)
            character_mgr = Character(uid, machine_code, nickname)
            yield character_mgr.load()
            user = g_UserMgr.loginUser(p, uid, machine_code, nickname, character_mgr)
        if user:
            info = user.character_mgr.info()

    info['constants'] = constant_data()
    info['server_time'] = int(time()*1000)
    defer.returnValue((0, info))
예제 #3
0
 def get_group_buy_reward(self, buy_type, buy_count):
     if buy_type not in get_group_buy_conf().keys(
     ) or buy_count not in get_group_buy_count():
         defer.returnValue(BUY_GROUP_TYPE_WRONG)
     _wlist = list(set(get_group_buy_count()))
     _st = yield redis.hget(DICT_GROUP_BUY_INFO, buy_type)
     #buy_type:buy_num
     _data = loads(_st)
     _count = _data
     if _count < buy_count:
         defer.returnValue(BUY_NUM_NOT_ENOUGH)
     _stream = yield redis.hget(DICT_GROUP_BUY_PERSON_INFO, self.cid)
     _info = loads(_stream)
     #[[buy_count,[status,,,]],...]
     _buy_count, _get_info = _info[buy_type - 1]
     if _buy_count <= 0:
         defer.returnValue(BUY_STATUS_IS_WRONG)
     _index = _wlist.index(buy_count)
     if _get_info[_index] == 1:
         defer.returnValue(BUY_STATUS_IS_WRONG)
     _get_info[_index] = 1
     _info[buy_type - 1] = [_buy_count, _get_info]
     _reward = get_group_buy_reward_list_conf(buy_type, buy_count)
     _item_type, _item_id, _item_num = _reward.split(":")
     _res = yield item_add(self.user,
                           ItemType=int(_item_type),
                           ItemID=int(_item_id),
                           ItemNum=int(_item_num),
                           AddType=WAY_GROUP_BUY)
     yield redis.hset(DICT_GROUP_BUY_PERSON_INFO, self.cid, dumps(_info))
     defer.returnValue((buy_type, buy_count, _res[1][0]))
예제 #4
0
    def get_campcard_data(self):
        ''' 获取玩家的阵营抽卡信息 '''
        reset_flag = False
        curr_time  = int(time())
        comm_data  = yield redis.hget(HASH_CAMPRAND_COMMON, 'CAMPRAND')
        if comm_data:
            comm_data = loads(comm_data)
            if curr_time >= comm_data[0]:
                reset_flag = True
                comm_data[0] += CAMP_RAND_TIME
                comm_data[1] = 0 if len(CAMP_GROUP_IDS) <= comm_data[1]+1 else comm_data[1] + 1
                yield redis.hset(HASH_CAMPRAND_COMMON, 'CAMPRAND', dumps(comm_data))
            else:
                camp_data = yield redis.hget(HASH_CAMPRAND_COMMON, self.cid)
                if camp_data:
                    camp_data = loads(camp_data)
                    if 1 == timestamp_is_today(camp_data[0]):
                        curr_camp_data, next_camp_data = camp_data[1], camp_data[2]
                    else:
                        reset_flag = True
                else:
                    reset_flag = True
        else:
            reset_flag = True
            comm_data = [get_reset_timestamp() + CAMP_RAND_TIME, 0]
            yield redis.hset(HASH_CAMPRAND_COMMON, 'CAMPRAND', dumps(comm_data))

        if reset_flag:
            curr_camp_data = [[camp_id, 0] for camp_id in CAMP_GROUP_IDS[comm_data[1]]]
            next_group_id  = 0 if len(CAMP_GROUP_IDS) <= comm_data[1]+1 else comm_data[1] + 1
            next_camp_data = [[camp_id, 0] for camp_id in CAMP_GROUP_IDS[next_group_id]]
            yield redis.hset(HASH_CAMPRAND_COMMON, self.cid, dumps([curr_time, curr_camp_data, next_camp_data]))

        defer.returnValue( (comm_data[0], curr_camp_data, next_camp_data) )
예제 #5
0
def add_daily_pay_record(character_id, add_cost):
    ''' new pay record.
    '''
    pay_date = datetime.now().strftime("%Y-%m-%d")
    # old pay record
    _data = yield redis.hget(HASH_DAILY_PAY_RECORD, pay_date)
    if _data:
        _data = loads(_data)
    else:
        _data = []

    # 新增豪华签到时间点
    _pay_login_data = yield redis.hget(HASH_PAY_LOGIN_PACKAGE, character_id)
    if not _pay_login_data:
        yield redis.hset(HASH_PAY_LOGIN_PACKAGE, character_id,
                         dumps([int(time()), 1, 0]))

    _had_cost = add_cost
    for _record in _data:
        if _record[0] == character_id:
            _record[1] += add_cost
            _had_cost = _record[1]
            break
    else:
        _data.append([character_id, add_cost])

    # update pay record
    yield redis.hset(HASH_DAILY_PAY_RECORD, pay_date, dumps(_data))

    defer.returnValue(_had_cost)
예제 #6
0
 def buy_group_package(self, buy_type):
     if buy_type not in get_group_buy_conf().keys():
         defer.returnValue( BUY_GROUP_TYPE_WRONG )
     _conf = get_group_buy_conf(buy_type)
     _stream = yield redis.hget(DICT_GROUP_BUY_PERSON_INFO, self.cid)
     _data = loads(_stream)
     #[[buy_count, [0,0,0,0]], ......]
     bought_count, _info = _data[buy_type-1]
     if bought_count + 1 > _conf["LimitNum"]:
         defer.returnValue(GROUP_BUY_MAX_COUNT)
     if self.user.credits < _conf["CurrentPrice"]:
         defer.returnValue(CHAR_CREDIT_NOT_ENOUGH)
     yield self.user.consume_credits(_conf["CurrentPrice"], WAY_GROUP_BUY)
     bought_count +=1
     _st = yield redis.hget(DICT_GROUP_BUY_INFO, buy_type)
     _datas = loads(_st)
     #buy_type:buy_num
     _total_buy_count = _datas
     if bought_count == 1:
         _total_buy_count += 1
     _data[buy_type-1] = [bought_count, _info]
     yield redis.hset(DICT_GROUP_BUY_PERSON_INFO, self.cid, dumps(_data))
     yield redis.hset(DICT_GROUP_BUY_INFO, buy_type, dumps(_total_buy_count))
     _item_type, _item_id, _item_num = _conf['ItemType'], _conf['ItemID'], _conf['ItemNum']
     _res = yield item_add(self.user, ItemType=_item_type, ItemID=_item_id, ItemNum = _item_num, AddType=WAY_GROUP_BUY)
     _result = (buy_type, _total_buy_count, bought_count, _res[1][0], self.user.credits)
     defer.returnValue( _result )
예제 #7
0
def world_ranklist(p, req):
    if hasattr(p, "uid"):
        log.debug('uid:{0}'.format(p.uid))
        uid = p.uid
    else: # used to test
        log.error('client has not found uid.')
        defer.returnValue((CONNECTION_LOSE, None))

    user = g_UserMgr.getUserByUid(uid)
    if not user:
        defer.returnValue((CONNECTION_LOSE, None))

    data = list()
    other_data = list()
    weight_data = yield redis.zrange(SET_RANK_PVP_WEIGHT, 0, 10, True)
    for _rank, (_uid, _weight) in enumerate(weight_data):
        _machine_code = yield redis.hget(HASH_UID_MACHINE_CODE, _uid)
        other_data.append((_rank+1, _uid, _machine_code, _weight))

    self_rank = yield redis.zrank(SET_RANK_PVP_WEIGHT, uid)
    self_rank = 0 if self_rank is None else int(self_rank) + 1
    self_machine_code = yield redis.hget(HASH_UID_MACHINE_CODE, uid)
    self_weight = yield redis.zscore(SET_RANK_PVP_WEIGHT, uid)
    self_weight = 0 if self_weight is None else abs(self_weight)

    data = (other_data, (self_rank, uid, self_machine_code, self_weight))
    defer.returnValue((NO_ERROR, data))
예제 #8
0
 def get_group_buy_reward(self, buy_type, buy_count):
     if buy_type not in get_group_buy_conf().keys() or buy_count not in get_group_buy_count():
         defer.returnValue( BUY_GROUP_TYPE_WRONG )
     _wlist = list(set(get_group_buy_count()))
     _st = yield redis.hget(DICT_GROUP_BUY_INFO, buy_type)
     #buy_type:buy_num
     _data = loads(_st)
     _count = _data
     if _count < buy_count:
         defer.returnValue( BUY_NUM_NOT_ENOUGH )
     _stream = yield redis.hget(DICT_GROUP_BUY_PERSON_INFO, self.cid)
     _info = loads(_stream)
     #[[buy_count,[status,,,]],...]
     _buy_count, _get_info = _info[buy_type-1]
     if _buy_count <= 0:
         defer.returnValue( BUY_STATUS_IS_WRONG )
     _index = _wlist.index(buy_count)
     if _get_info[_index] == 1:
         defer.returnValue( BUY_STATUS_IS_WRONG)
     _get_info[_index] = 1
     _info[buy_type-1] = [_buy_count, _get_info]
     _reward = get_group_buy_reward_list_conf(buy_type, buy_count)      
     _item_type, _item_id, _item_num = _reward.split(":")
     _res = yield item_add(self.user, ItemType= int(_item_type), ItemID= int(_item_id), ItemNum = int(_item_num), AddType=WAY_GROUP_BUY)
     yield redis.hset(DICT_GROUP_BUY_PERSON_INFO, self.cid, dumps(_info))
     defer.returnValue((buy_type, buy_count, _res[1][0]))
예제 #9
0
def grant_limit_fellow_award(all_ranks, activity_id, timestamp):
    '''
    @param: timestamp-借用时间戳作为callLater的有效性验证
    '''
    log.warn('limit fellow award. activity_id: {0}, timestamp: {1}, ACTIVITY_AWARD_TIME: {2}.'.format( activity_id, timestamp, ACTIVITY_AWARD_TIME ))
    # 判断是否是正确的callLater
    if ACTIVITY_AWARD_TIME != timestamp:
        defer.returnValue( None )

    _max_rank = max(all_ranks)
    if _max_rank > 0:
        _rank = 1
        _name_scores = yield redis.zrevrange( SET_LIMIT_FELLOW_NAME_SCORE, 0, _max_rank, withscores=True )
        for _nick_name, _score in _name_scores:
            if _score <= 0:
                continue
            _cid = yield redis.hget(DICT_NICKNAME_REGISTERED, str(_nick_name))
            if _cid:
                yield g_AwardCenterMgr.new_award( _cid, AWARD_TYPE_LIMIT_FELLOW_RANK, [int(time()), activity_id, _rank] )
            _rank += 1

    if 0 in all_ranks:
        _names = yield redis.zrangebyscore( SET_LIMIT_FELLOW_NAME_SCORE, 60, '+inf' )
        for _name in _names:
            _cid = yield redis.hget(DICT_NICKNAME_REGISTERED, str(_name))
            if _cid:
                yield g_AwardCenterMgr.new_award( _cid, AWARD_TYPE_LIMIT_FELLOW_SCORE, [int(time()), activity_id, 0] )

    yield redis.delete( HASH_LIMIT_FELLOW_SHRINE, SET_LIMIT_FELLOW_NAME_SCORE )
예제 #10
0
def world_ranklist(p, req):
    if hasattr(p, "uid"):
        log.debug('uid:{0}'.format(p.uid))
        uid = p.uid
    else:  # used to test
        log.error('client has not found uid.')
        defer.returnValue((CONNECTION_LOSE, None))

    user = g_UserMgr.getUserByUid(uid)
    if not user:
        defer.returnValue((CONNECTION_LOSE, None))

    data = list()
    other_data = list()
    weight_data = yield redis.zrange(SET_RANK_PVP_WEIGHT, 0, 10, True)
    for _rank, (_uid, _weight) in enumerate(weight_data):
        _machine_code = yield redis.hget(HASH_UID_MACHINE_CODE, _uid)
        other_data.append((_rank + 1, _uid, _machine_code, _weight))

    self_rank = yield redis.zrank(SET_RANK_PVP_WEIGHT, uid)
    self_rank = 0 if self_rank is None else int(self_rank) + 1
    self_machine_code = yield redis.hget(HASH_UID_MACHINE_CODE, uid)
    self_weight = yield redis.zscore(SET_RANK_PVP_WEIGHT, uid)
    self_weight = 0 if self_weight is None else abs(self_weight)

    data = (other_data, (self_rank, uid, self_machine_code, self_weight))
    defer.returnValue((NO_ERROR, data))
예제 #11
0
def add_daily_pay_record(character_id, add_cost):
    ''' new pay record.
    '''
    pay_date = datetime.now().strftime("%Y-%m-%d")
    # old pay record
    _data = yield redis.hget(HASH_DAILY_PAY_RECORD, pay_date)
    if _data:
        _data = loads(_data)
    else:
        _data = []

    # 新增豪华签到时间点
    _pay_login_data = yield redis.hget(HASH_PAY_LOGIN_PACKAGE, character_id)
    if not _pay_login_data:
        yield redis.hset(HASH_PAY_LOGIN_PACKAGE, character_id, dumps([int(time()), 1, 0]))

    _had_cost = add_cost
    for _record in _data:
        if _record[0] == character_id:
            _record[1] += add_cost
            _had_cost = _record[1]
            break
    else:
        _data.append( [character_id, add_cost] )

    # update pay record
    yield redis.hset(HASH_DAILY_PAY_RECORD, pay_date, dumps(_data))

    defer.returnValue( _had_cost )
예제 #12
0
def login(p, req):
    log.warn("=======req: ", req)
    machine_code, = req
    if not machine_code:
        defer.returnValue((MACHINE_CODE_ERROR, {}))

    uid = yield redis.hget(HASH_MACHINE_CODE_REGISTERED, machine_code)
    p.uid = uid
    info = dict()
    # 创建新玩家
    if not uid:
        #TODO random nickname
        nickname = machine_code
        character_mgr = Character(0, machine_code, nickname)
        yield character_mgr.new(machine_code, nickname)

        uid = character_mgr.uid
        yield redis.hset(HASH_NICKNAME_REGISTERED, nickname, uid)
        yield redis.hset(HASH_MACHINE_CODE_REGISTERED, machine_code, uid)
        info = character_mgr.info()
    else:
        # 检查已登录时, 释放旧的连接 提示有重复登陆
        user = g_UserMgr.getUserLogined(uid, p)
        if not user:
            nickname = yield redis.hget(HASH_NICKNAME_REGISTERED, uid)
            character_mgr = Character(uid, machine_code, nickname)
            yield character_mgr.load()
            user = g_UserMgr.loginUser(p, uid, machine_code, nickname,
                                       character_mgr)
        if user:
            info = user.character_mgr.info()

    info['constants'] = constant_data()
    info['server_time'] = int(time() * 1000)
    defer.returnValue((0, info))
예제 #13
0
def friend_get_douzhan(p, req):
    ''' 领取斗战点 '''
    cid, [send_cids] = req

    if not isinstance(send_cids, (list, tuple)):
        defer.returnValue( CLIENT_DATA_ERROR )

    user = g_UserMgr.getUser(cid)
    if not user:
        log.error('Can not find user. cid: {0}.'.format( cid ))
        defer.returnValue( CONNECTION_LOSE )

    if user.douzhan >= 65535:
        log.error("User's douzhan had been max. cid: {0}.".format( cid ))
        defer.returnValue( DOUZHAN_MAX_ERROR )

    add_douzhan = yield user.goodwill_mgr.check_achieve()

    dt_now = datetime.now()
    _data  = yield redis.hget( HASH_FRIENDS_GIFT_DOUZHAN % cid, FRIENDS_DOUZHAN_GET )
    if _data:
        last_time, left_count = loads( _data )
        dt_last = datetime.fromtimestamp( last_time )
        if dt_last.date() != dt_now.date():
            left_count = GET_DOUZHAN_DAILY_LIMIT + add_douzhan
    else:
        left_count = GET_DOUZHAN_DAILY_LIMIT + add_douzhan

    if left_count < len(send_cids):
        log.error("User's gift douzhan count has used up today. left_count: {0}.".format( left_count ))
        defer.returnValue( DOUZHAN_DAILY_ERROR )

    for send_cid in send_cids:
        _data = yield redis.hget( HASH_FRIENDS_GIFT_DOUZHAN % cid, send_cid )
        if not _data:
            log.error('Can not find the gift douzhan. cid: {0}, send_cid: {1}.'.format( cid, send_cid ))
            continue
            #defer.returnValue( REQUEST_LIMIT_ERROR )

        yield redis.hdel( HASH_FRIENDS_GIFT_DOUZHAN % cid, send_cid )
        # 策划修改-好友赠送,每次改为2点
        user.add_douzhan( 2 )
        # 回赠
        yield gift_douzhan(cid, send_cid)
        # 更新今日可领次数
        left_count -= 1
        yield redis.hset( HASH_FRIENDS_GIFT_DOUZHAN % cid, FRIENDS_DOUZHAN_GET, dumps((int(time()), left_count)) )

    defer.returnValue( [user.douzhan] )
예제 #14
0
 def status(self, camp_flag=False):
     '''
     @summary: 获取抽卡的状态
     @camp_flag: 含阵营抽卡信息的标志位 True-需要返还阵营抽卡的信息 False-不需要
     @param: first_blue-第一次使用钻石抽卡的标志, 0-已使用, 1-未使用
     '''
     blue_data = yield redis.hget(HASH_SHRINE_TYPE % CARD_SHRINE_BLUE, self.cid)
     if blue_data:
         blue_data = loads( blue_data )
         if len(blue_data) == 4:
             _, blue_count, blue_last_free_time, _ = blue_data
             first_blue = 0
         else:
             _, blue_count, blue_last_free_time, _, first_blue, _ = blue_data
     else:
         blue_count, blue_last_free_time, first_blue = 0, 0, 1
     blue_conf = get_randcard_consume_conf( CARD_SHRINE_BLUE )
     blue_need_time = 0
     if blue_conf:
         blue_need_time = self.left_free_timestamp( blue_last_free_time, blue_conf['FreeTime'] )
     # 紫卡的状态
     purple_data = yield redis.hget(HASH_SHRINE_TYPE % CARD_SHRINE_PURPLE, self.cid)
     if purple_data:
         purple_data = loads( purple_data )
         if len(purple_data) == 4:
             purple_level, purple_count, purple_last_free_time, _ = purple_data
             first_purple = 0
         else:
             purple_level, purple_count, purple_last_free_time, _, _, first_purple = purple_data
     else:
         purple_level, purple_count, purple_last_free_time, first_purple = 0, 0, 0, 1
     purple_conf = get_randcard_consume_conf( CARD_SHRINE_PURPLE )
     purple_need_time = 0
     purple_ten_cost  = 0
     if purple_conf:
         purple_need_time = self.left_free_timestamp( purple_last_free_time, purple_conf['FreeTime'] )
         purple_ten_cost  = int((purple_conf['ItemNum'] * 10 * RANDCARD_TEN_RATIO + 99) / 100)
     if purple_need_time >= 0:
         left_purple_count = self.left_purple_count( CARD_SHRINE_PURPLE, purple_level, purple_count )
     else: # 首抽必得
         left_purple_count = 0
     total_num, _ = yield self.user.bag_item_mgr.get_items( ITEM_RANDCARD_GREEN )
     # 阵营抽卡的状态信息
     if camp_flag:
         camp_left_time, curr_camp_data, next_camp_data = yield self.get_campcard_data()
         defer.returnValue( (blue_need_time, purple_need_time, left_purple_count, total_num, purple_ten_cost, first_blue, first_purple, camp_left_time, curr_camp_data, next_camp_data) )
     else:
         defer.returnValue( (blue_need_time, purple_need_time, left_purple_count, total_num, purple_ten_cost, first_blue, first_purple) )
예제 #15
0
    def probability_of_robot(cid, shard_id, limit_rate):
        '''
        @summary: 获取玩家抢机器人时的概率
        @return : True-命中碎片 False-未命中
        '''
        _base_rate = 7500 # 机器人的基础概率

        _conf = get_treasureshard_rate_conf( shard_id )
        if _conf:
            _miss_rate = yield redis.hget( HASH_TREASURESHARD_ROBOT_RATE % shard_id, cid )
            if _miss_rate is None: # 新号第一次夺宝
                _miss_rate = _conf['MaxRate']
            else:
                _miss_rate = int(_miss_rate)

            _base_rate = _conf['Rate'] + _miss_rate
            if _base_rate >= _conf['MaxRate']:
                _base_rate = _conf['MaxRate']

            _miss_rate += _conf['AddRate']
        else:
            log.warn( 'No such conf in sysconfig:treasureshard_rate, shard_id:', shard_id )
            defer.returnValue( False )

        if limit_rate <= _base_rate: # 命中
            _miss_rate = 0
            yield redis.hset( HASH_TREASURESHARD_ROBOT_RATE % shard_id, cid, _miss_rate )
            defer.returnValue( True )
        else:
            yield redis.hset( HASH_TREASURESHARD_ROBOT_RATE % shard_id, cid, _miss_rate )
            defer.returnValue( False )
예제 #16
0
    def buy_cd_time(self):
        '''
        清除连战冷却时间 60s = 1 credits
        '''
        cur_time = int(time())
        old_data = yield redis.hget(HASH_SCENE_COOLDOWN_TIME, self.cid)
        end_cooldown_time = int(old_data or 0)
        if end_cooldown_time <= cur_time:
            defer.returnValue([self.user.base_att.credits])

        need_credits = (end_cooldown_time - cur_time)
        if (need_credits % COOLDOWN_TIME_COST):
            need_credits = (need_credits / COOLDOWN_TIME_COST) + 1
        else:
            need_credits = (need_credits / COOLDOWN_TIME_COST)

        if need_credits > self.user.base_att.credits:
            log.error('Credits not enough. need: {0}, cur: {1}.'.format(
                total_credits, self.user.base_att.credits))
            defer.returnValue(CHAR_CREDIT_NOT_ENOUGH)

        yield self.user.consume_credits(need_credits, WAY_SCENE_CD_TIME)
        # 删除redis冷却时间记录
        yield redis.hdel(HASH_SCENE_COOLDOWN_TIME, self.cid)

        defer.returnValue([self.user.base_att.credits])
예제 #17
0
def get_login_status(cid, redis_key, max_package_id):
    '''
    @summary: 连续登录天数,连续登录中断后从1开始记,连续登录天数超过配置条数则领取最后一条奖励
    '''
    _data = yield redis.hget(redis_key, cid)
    if _data:
        _data = loads(_data)
    else:
        _data = [0, 0]
    # 判断时间点
    _d_time = datetime.fromtimestamp(_data[0])
    _d_now = datetime.now()
    _delta = _d_now - _d_time
    if _delta.days < 2:
        # 同一天重复登录
        if _d_now.day == _d_time.day:
            defer.returnValue((_data[1], 0))
        # 连续登录
        elif (_d_now.day - _d_time.day == 1):
            if _data[1] >= max_package_id:
                defer.returnValue((_data[1], max_package_id))
            else:
                defer.returnValue((_data[1], _data[1] + 1))
    # 非连续登录
    defer.returnValue((0, 1))
예제 #18
0
 def load_star_rewarded(self):
     ''' 加载副本已领奖的星数 '''
     if self.star_rewarded is None:
         self.star_rewarded = {}
         rewarded_data = yield redis.hget( HASH_SCENE_STAR_REWARDED, self.cid )
         if rewarded_data:
             self.star_rewarded = loads( rewarded_data )
예제 #19
0
    def _load(self):
        if self.__gsattribs is None:
            if not self.__loading:
                self.__loading = True
                self.__gsattribs = yield GSAttribute.load(
                    self.cid, GSBagJadeMgr._table)
                for gsattrib in self.__gsattribs.itervalues():
                    # 获取阵容中的玉魄信息
                    if gsattrib.camp_id > 0:
                        # 异常数据
                        if gsattrib.position_id < 1:
                            gsattrib.camp_id = 0

                # 获取鉴玉当前等级
                _level = yield redis.hget(HASH_RANDOM_JADE_LEVEL, self.cid)
                self.random_jade_level = int(_level) if _level else 1

                for d in self.__defers:
                    d.callback(True)

                self.__loading = False
                self.__defers = []
            else:
                d = defer.Deferred()
                self.__defers.append(d)
                yield d
예제 #20
0
    def status(self):
        ''' 获取玩家的成就当前的状态, 含奖励和任务进度
        return [[_id, status, value],..]
        redis: actype:{_id:(status,value)}
        '''
        res_err = self.user.check_function_open(FUNCTION_ACHIEVEMENT)
        if res_err:
            defer.returnValue( res_err )

        data = yield redis.hget(HASH_ACHIEVEMENT_INFO, self.cid)
        res = []
        if not data:
            _all_conf = get_all_achievement_conf()
            _d = {}
            if _all_conf:
                for acType, _info in _all_conf.iteritems():
                    for _id, _v in _info.iteritems():
                        status = 0
                        if _d.has_key(acType):
                            _d[acType][_id] = [status, 0]
                        else:
                            _d[acType] = {_id:[status,0]}
                        res.append([_id, 0, 0])

                yield redis.hset(HASH_ACHIEVEMENT_INFO, self.cid, dumps(_d))
            defer.returnValue( res )
            
        _data = loads( data )
        res = yield self.sync_old_record(_data)

        defer.returnValue( res )
예제 #21
0
    def check_valid_messages(self, cid, flag=False):
        ''' 
        @param: flag-True:需要详细信息的标志位, False:不需要详情
        '''
        _all_messages = yield redis.hget(HASH_ALLIANCE_MESSAGES, self.__id)
        if _all_messages:
            _all_messages = loads(_all_messages)
        else:
            _all_messages = []

        _daily_count    = 0 # 今日已留言的次数
        _valid_messages = []
        _details = []
        for _message in _all_messages:
            _m = g_UserMgr.getUser( _message[1] )
            if not _m:
                continue
            # 检查时间是否过期, 7天
            if check_valid_time(_message[0], hour=MESSAGES_VALID_HOUR):
                continue
            if cid == _m.cid and timestamp_is_today(_message[0]):
                _daily_count += 1
            _valid_messages.append( _message )
            if flag:
                _details.append( (_message[0], _m.cid, _m.lead_id, _m.nick_name, _m.level, _m.position, _message[2]) )

        defer.returnValue( (_daily_count, _valid_messages, _details) )
예제 #22
0
    def sacrifice_info(self, member):
        ''' 公会女娲宫的信息 '''
        _data = yield redis.hget(HASH_ALLIANCE_SACRIFICE, self.__id)
        if _data:
            _data = loads( _data )
            # 判断是否需要更新0点更新
            _reset_timestamp = get_reset_timestamp()
            if _data[0] <= _reset_timestamp:
                _data = [int(time()), 0, []]
                yield redis.hset(HASH_ALLIANCE_SACRIFICE, self.__id, dumps(_data))
        else:
            _data = [int(time()), 0, []]
        # 获取玩家的拜祭信息
        for _cid, _contribution_count, _credits_count in _data[2]:
            if _cid == member.cid:
                break
        else:
            _contribution_count, _credits_count = 0, 0
 
        _a_level_conf = get_alliance_level_conf(self.__level)
        if not _a_level_conf:
            defer.returnValue( NOT_FOUND_CONF )
        _left_alliance_count = _a_level_conf['MembersCount'] - _data[1]
        _left_alliance_count = 0 if _left_alliance_count < 0 else _left_alliance_count

        _left_contribution_count = 0 if _contribution_count > 0 else 1
        _vip_level_conf = get_vip_conf(member.vip_level)
        if _vip_level_conf:
            _left_credits_count = _vip_level_conf['GuildSacrificeCount'] - _credits_count
            _left_credits_count = 0 if _left_credits_count < 0 else _left_credits_count
        else:
            _left_credits_count = 0

        defer.returnValue( (_left_alliance_count, _left_contribution_count, _left_credits_count, self.__level, self.__exp, _data) )
예제 #23
0
    def get_group_buy_info(self):
        _infos = yield redis.hgetall(DICT_GROUP_BUY_INFO)
        if not _infos:
            _group_buy_info = {1:0,2:0,3:0,4:0}  #buy_type:buy_num
            for buy_type in xrange(1,5):
                yield redis.hset(DICT_GROUP_BUY_INFO, buy_type, dumps(_group_buy_info[buy_type]))
        else:
            _group_buy_info = dict()
            for k, v in _infos.iteritems():
                _group_buy_info[k] = loads(v)

        _res = []
        _ret = []
        for _buy_type, _bought_num in _group_buy_info.iteritems():
           _res.append([_buy_type, _bought_num])

        _stream = yield redis.hget(DICT_GROUP_BUY_PERSON_INFO, self.cid)#[[buy_count, [status,2,3,4]],..]
        if _stream:
            try:
                _data = loads(_stream)
                if _data:
                    # [bought_count, [0,0,0,0]]
                    for _bought_count_info, _info in zip(_data, _res):
                        _info.append(_bought_count_info)
                        _ret.append(_info)
            except:
                log.exception()
        else:
            _value = [[0,[0,0,0,0]]] * 4
            yield redis.hset(DICT_GROUP_BUY_PERSON_INFO, self.cid, dumps(_value))
            for _info in _res:
                _info.append([0,[0,0,0,0]])
                _ret.append(_info)
        defer.returnValue( _ret )
예제 #24
0
    def buy_cd_time(self):
        '''
        清除连战冷却时间 60s = 1 credits
        '''
        cur_time = int(time())
        old_data = yield redis.hget(HASH_SCENE_COOLDOWN_TIME, self.cid)
        end_cooldown_time = int( old_data or 0 )
        if end_cooldown_time <= cur_time:
            defer.returnValue( [self.user.base_att.credits] )

        need_credits = (end_cooldown_time - cur_time)
        if (need_credits % COOLDOWN_TIME_COST):
            need_credits = (need_credits / COOLDOWN_TIME_COST) + 1
        else:
            need_credits = (need_credits / COOLDOWN_TIME_COST)

        if need_credits > self.user.base_att.credits:
            log.error('Credits not enough. need: {0}, cur: {1}.'.format( total_credits, self.user.base_att.credits ))
            defer.returnValue( CHAR_CREDIT_NOT_ENOUGH )

        yield self.user.consume_credits( need_credits, WAY_SCENE_CD_TIME )
        # 删除redis冷却时间记录
        yield redis.hdel( HASH_SCENE_COOLDOWN_TIME, self.cid )

        defer.returnValue( [self.user.base_att.credits] )
예제 #25
0
    def probability_of_robot(cid, shard_id, limit_rate):
        '''
        @summary: 获取玩家抢机器人时的概率
        @return : True-命中碎片 False-未命中
        '''
        _base_rate = 7500  # 机器人的基础概率

        _conf = get_treasureshard_rate_conf(shard_id)
        if _conf:
            _miss_rate = yield redis.hget(
                HASH_TREASURESHARD_ROBOT_RATE % shard_id, cid)
            if _miss_rate is None:  # 新号第一次夺宝
                _miss_rate = _conf['MaxRate']
            else:
                _miss_rate = int(_miss_rate)

            _base_rate = _conf['Rate'] + _miss_rate
            if _base_rate >= _conf['MaxRate']:
                _base_rate = _conf['MaxRate']

            _miss_rate += _conf['AddRate']
        else:
            log.warn('No such conf in sysconfig:treasureshard_rate, shard_id:',
                     shard_id)
            defer.returnValue(False)

        if limit_rate <= _base_rate:  # 命中
            _miss_rate = 0
            yield redis.hset(HASH_TREASURESHARD_ROBOT_RATE % shard_id, cid,
                             _miss_rate)
            defer.returnValue(True)
        else:
            yield redis.hset(HASH_TREASURESHARD_ROBOT_RATE % shard_id, cid,
                             _miss_rate)
            defer.returnValue(False)
예제 #26
0
def gift_douzhan(send_cid, rcv_cid):
    user = g_UserMgr.getUser( send_cid )
    if not user:
        log.error('Can not find user. send_cid: {0}.'.format( send_cid ))
        defer.returnValue( CONNECTION_LOSE )

    # 维护自己的已赠送好友斗战点的信息
    send_data = yield redis.hget(HASH_FRIENDS_SEND_DOUZHAN, send_cid)
    if send_data:
        send_data = loads(send_data)
    else:
        send_data = [int(time()), []]

    dt_now    = datetime.now()
    dt_last   = datetime.fromtimestamp( send_data[0] )
    if dt_last.date() == dt_now.date():
        if rcv_cid in send_data[1]:
            #log.error('Rcv user had gift douzhan. send_cid: {0}, rcv_cid: {1}.'.format( send_cid, rcv_cid ))
            defer.returnValue( NO_ERROR )
        else:
            send_data[1].append( rcv_cid )
            yield redis.hset(HASH_FRIENDS_SEND_DOUZHAN, send_cid, dumps(send_data))
    else:
        send_data = [int(time()), [rcv_cid]]
        yield redis.hset(HASH_FRIENDS_SEND_DOUZHAN, send_cid, dumps(send_data))
 
    # 每日任务计数
    yield user.daily_quest_mgr.update_daily_quest( DAILY_QUEST_ID_10, 1 )
    # 维护好友的可领取斗战点的信息
    gift_data = dumps( (send_cid, user.lead_id, user.nick_name, user.level, user.might) )
    yield redis.hset( HASH_FRIENDS_GIFT_DOUZHAN % rcv_cid, send_cid, gift_data )

    defer.returnValue( NO_ERROR )
예제 #27
0
def gm_get_broadcast_msgs(cmd, ts, args, sign):
    ''' OSS获取当前的活动公告配置 '''

    res_err = {'result': 1, 'args': []}

    all_messages = curr_broadcast_messages()
    if all_messages is not None:
        for _id, _content in enumerate(all_messages):
            res_err['args'].append( {'id': _id+1, 'content': _content} )
        defer.returnValue( res_err )
    else:
        all_messages = []

    _all_msgs = yield redis.hget( HASH_OSS_MESSAGES, FIELD_BROADCAST )
    if not _all_msgs:
        defer.returnValue( res_err )
    else:
        _all_msgs = marshal.loads(_all_msgs)

    _args_data = []
    for _id, _content in enumerate(_all_msgs):
        _args_data.append( {'id': _id+1, 'content': _content} )
        all_messages.append( _content )

    if _args_data:
        res_err['args'] = _args_data
    # 更新内存数据
    sync_broadcast_messages( all_messages )

    defer.returnValue( res_err )
예제 #28
0
    def atlaslist_award(self, category_id, second_type, quality):
        _award_data = yield redis.hget(HASH_ATLASLIST_AWARD, self.cid)
        if _award_data:
            _award_data = loads(_award_data)
        else:
            _award_data = []

        _new_award = (category_id, second_type, quality)
        if _new_award in _award_data:
            defer.returnValue( ATLASLIST_AWARD_HAD_ERROR )

        _category_conf = get_atlaslist_category_conf(category_id)
        _second_conf   = _category_conf.get(second_type, {})
        _quality_conf  = _second_conf.get(quality, {})
        if not _quality_conf or not _quality_conf['Awardlist']:
            defer.returnValue( NOT_FOUND_CONF )
 
        _award_data.append( _new_award )
        yield redis.hset(HASH_ATLASLIST_AWARD, self.cid, dumps( _award_data ))
        items_return = []
        for _type, _id, _num in _quality_conf['Awardlist']:
            model = ITEM_MODELs.get( _type, None )
            if not model:
                log.error('Unknown item type. cid: {0}, item_type: {1}, item_id: {2}, item_num: {3}.'.format( self.cid, _type, _id, _num ))
                continue
            res_err, value = yield model(self.user, ItemID=_id, ItemNum=_num, AddType=WAY_ATLASLIST_AWARD, CapacityFlag=False)
            if not res_err and value:
                for _v in value:
                    items_return = total_new_items( _v, items_return )

        defer.returnValue( items_return )
예제 #29
0
def get_login_status(cid, redis_key, max_package_id):
    '''
    @summary: 连续登录天数,连续登录中断后从1开始记,连续登录天数超过配置条数则领取最后一条奖励
    '''
    _data = yield redis.hget(redis_key, cid)
    if _data:
        _data = loads(_data)
    else:
        _data = [0, 0]
    # 判断时间点
    _d_time  = datetime.fromtimestamp( _data[0] )
    _d_now   = datetime.now()
    _delta   = _d_now - _d_time
    if _delta.days < 2:
        # 同一天重复登录
        if _d_now.day == _d_time.day:
            defer.returnValue( (_data[1], 0) )
        # 连续登录
        elif (_d_now.day - _d_time.day == 1):
            if _data[1] >= max_package_id:
                defer.returnValue( (_data[1], max_package_id) )
            else:
                defer.returnValue( (_data[1], _data[1] + 1) )
    # 非连续登录
    defer.returnValue( (0, 1) )
예제 #30
0
def reload_resource(request):
    ''' 加载新的资源 '''
    request.setHeader('Content-Type', 'application/json;charset=UTF-8')
    res_err = {'res_url':'', 'reward_status':0, 'total_size':0, 'folder_name':''}

    if len(request.args) < 3:
        log.error('Request args error. args: {0}.'.format( request.args ))
        defer.returnValue( json.dumps(res_err) )

    ver_res     = request.args['ver_res'][0]
    ver_game    = request.args['ver_game'][0]
    device_type = request.args['device_type'][0]
    accountname = request.args['accountname'][0]
    server_id   = request.args['server_id'][0]

    cid   = yield redis.hget(DICT_ACCOUNT_REGISTERED, '%s%s'%(accountname,server_id))
    if not cid:
        log.error('Unknown account. args: {0}.'.format( request.args ))
        defer.returnValue( json.dumps(res_err) )

    try:
        with open(DESC_FILE%ver_game) as desc_file:
            desc_info = json.loads(desc_file.read())
            desc_file.close()
    except Exception, e:
        log.error('Error. e: {0}.'.format( e ))
        defer.returnValue( json.dumps(res_err) )
예제 #31
0
    def get_dig_treasure_info(self):
        flag = 0
        _stream = yield redis.hget(DICT_DIG_TREASURE_INFO, self.cid)
        if _stream:
            try:
                _data = loads(_stream)
                if _data:
                    self.free_dig_count, self.dig_total_count, self.last_dig_time = _data
                    if not timestamp_is_today(self.last_dig_time):
                        self.free_dig_count = get_vip_conf(self.user.vip_level)["FreeDigCount"]
                        self.vipLevel = self.user.vip_level
                        self.last_dig_time = time()
                        _value = (self.free_dig_count, self.dig_total_count, self.last_dig_time)
                        yield redis.hset(DICT_DIG_TREASURE_INFO, self.cid, dumps(_value))
                    else:
                        if self.user.vip_level > self.vipLevel:
                            count = get_vip_conf(self.user.vip_level)["FreeDigCount"] - get_vip_conf(self.vipLevel)["FreeDigCount"]
                            self.free_dig_count += count
                            self.vipLevel = self.user.vip_level
                            _value = (self.free_dig_count, self.dig_total_count, self.last_dig_time)
                            yield redis.hset(DICT_DIG_TREASURE_INFO, self.cid, dumps(_value))

            except:
                log.exception()
        else:
            self.free_dig_count = get_vip_conf(self.user.vip_level)["FreeDigCount"]
            self.dig_total_count = 0
            self.last_dig_time = time()
            self.vipLevel = self.user.vip_level
            _value = (self.free_dig_count, self.dig_total_count, self.last_dig_time)
            yield redis.hset(DICT_DIG_TREASURE_INFO, self.cid, dumps(_value))
        if self.free_dig_count > 0:
            flag = 1
        defer.returnValue(flag)
예제 #32
0
def chat_private(p, req):
    ''' 私聊 '''
    cid, [rcv_nick_name, content] = req

    user = g_UserMgr.getUserByCid(cid)
    if not user:
        log.error('Can not find user. cid: {0}.'.format( cid ))
        defer.returnValue( CONNECTION_LOSE )

    _status = yield check_character_mute(int(cid))
    if _status:
        defer.returnValue( CHAR_IN_MUTE )

    rcv_cid = yield redis.hget(DICT_NICKNAME_REGISTERED, rcv_nick_name)
    if not rcv_cid:
        log.error('Can not find user. sender_id: {0}, rcv_cid: {1}, rcv_nick_name: {2}.'.format( cid, rcv_cid, rcv_nick_name ))
        defer.returnValue( UNKNOWN_CHAR )

    if rcv_cid == cid:
        defer.returnValue( UNKNOWN_ERROR )

    rcv_user = g_UserMgr.getUserByCid( rcv_cid )
    if not rcv_user:
        log.error('The user had not online. sender_id: {0}, rcv_cid: {1}.'.format( cid, rcv_cid ))
        defer.returnValue( CHAR_NOT_ONLINE )

    res_err = g_Private.new_msg( user, rcv_user, content )

    defer.returnValue( res_err )
예제 #33
0
def gm_get_broadcast_msgs(cmd, ts, args, sign):
    ''' OSS获取当前的活动公告配置 '''

    res_err = {'result': 1, 'args': []}

    all_messages = curr_broadcast_messages()
    if all_messages is not None:
        for _id, _content in enumerate(all_messages):
            res_err['args'].append({'id': _id + 1, 'content': _content})
        defer.returnValue(res_err)
    else:
        all_messages = []

    _all_msgs = yield redis.hget(HASH_OSS_MESSAGES, FIELD_BROADCAST)
    if not _all_msgs:
        defer.returnValue(res_err)
    else:
        _all_msgs = marshal.loads(_all_msgs)

    _args_data = []
    for _id, _content in enumerate(_all_msgs):
        _args_data.append({'id': _id + 1, 'content': _content})
        all_messages.append(_content)

    if _args_data:
        res_err['args'] = _args_data
    # 更新内存数据
    sync_broadcast_messages(all_messages)

    defer.returnValue(res_err)
예제 #34
0
    def dungeon_star_drop(self, dungeon_id, dungeon_star, flag=False):
        '''
        @summary: 怪物组不同难度掉落, 无conf则不用计算掉落
              2015-01-27 没有精力时,最终掉落概率=(基础概率+增加概率)* 1/3
        @param  : flag-True:无精力*1/3, False:有精力*1
        @param  : drop_items-[ [item_type, item_id, item_num], ... ]
        '''
        drop_items = []
        drop_conf = get_drop_conf(dungeon_id, dungeon_star)
        if not drop_conf:
            log.error(
                'No drop conf. dungeon_id: {0}, dungeon_star: {1}.'.format(
                    dungeon_id, dungeon_star))
            defer.returnValue(drop_items)

        # old_rate format: {dungeon_star: {drop_id: rate, ...}, ...}
        old_rate = {}
        data = yield redis.hget(HASH_DUNGEON_DROP_RATE % dungeon_id, self.cid)
        if data:
            old_rate = loads(data)
            if old_rate.has_key(dungeon_star):
                old_star_rate = old_rate[dungeon_star]
            else:
                old_star_rate = {}
                old_rate[dungeon_star] = old_star_rate
                for _id, _drop in drop_conf.iteritems():
                    old_star_rate[_id] = _drop['RateMax']
        else:  # 第一次按照最大概率来计算掉落
            old_star_rate = {}
            old_rate[dungeon_star] = old_star_rate
            for _id, _drop in drop_conf.iteritems():
                old_star_rate[_id] = _drop['RateMax']

        for _drop_id, _drop in drop_conf.iteritems():
            add_rate = old_star_rate.get(_drop_id,
                                         old_star_rate.setdefault(_drop_id, 0))
            _drop_rate = _drop['RateStart'] + add_rate
            # 单次增加的封顶概率
            if _drop_rate > _drop['RateMax']:
                _drop_rate = _drop['RateMax']
            # 有无精力
            if flag:
                _drop_rate = _drop_rate / 3
            # 掉落概率是万分比
            rand_int = random.randint(0, 10000)
            # _drop['QuestID'] 未处理
            # 当前随机值 不大于 配置的掉落概率值时掉落
            if rand_int <= _drop_rate:
                drop_items = add_new_items(
                    [_drop['ItemType'], _drop['ItemID'], _drop['ItemNum']],
                    drop_items)

                old_star_rate[_drop_id] = 0
            else:
                old_star_rate[_drop_id] += _drop['RateAdd']
        yield redis.hset(HASH_DUNGEON_DROP_RATE % dungeon_id, self.cid,
                         dumps(old_rate))

        defer.returnValue(drop_items)
예제 #35
0
    def exchange(self, user, exchange_id, exchange_count):
        '''
        @summary: 竞技场中 用声望兑换道具
        '''
        conf = get_arena_exchange( exchange_id )
        if not conf:
            log.error('Can not find conf. exchange_id: {0}.'.format( exchange_id ))
            defer.returnValue( NOT_FOUND_CONF )
        # 检查主角等级限制
        if user.base_att.level < conf['NeedLevel']:
            log.error('User level limit. NeedLevel: {0}, cur level: {1}.'.format( conf['NeedLevel'], user.base_att.level ))
            defer.returnValue( REQUEST_LIMIT_ERROR )

        cur_time = int(time())
        # read redis data
        data = yield redis.hget(HASH_ARENA_EXCHANGE, user.cid)
        if data:
            data = loads(data)
        else:
            data = {}

        old_excharge    = data.setdefault( exchange_id, [cur_time, exchange_id, 0, 0] )
        reset_timestamp = get_reset_timestamp()
        if old_excharge[0] <= reset_timestamp:
            old_excharge[0] = cur_time
            old_excharge[3] = 0
        # 检查可兑换次数限制
        if conf['MaxExchangeCount'] > 0:
            if (old_excharge[2] + exchange_count) > conf['MaxExchangeCount']:
                log.error('max count: {0}, used count: {1}, exchange_count: {2}.'.format( conf['MaxExchangeCount'], old_excharge[2], exchange_count ))
                defer.returnValue( ARENA_EXCHANGE_MAX_NUM )
        if conf['DailyExchangeCount'] > 0:
            if (old_excharge[3] + exchange_count) > conf['DailyExchangeCount']:
                log.error('daily_max_count: {0}, used count: {1}, exchange_count: {2}.'.format( conf['DailyExchangeCount'], old_excharge[3], exchange_count ))
                defer.returnValue( ARENA_EXCHANGE_MAX_NUM )
        # 检查声望值
        need_prestige = exchange_count * conf['NeedPrestige']
        if need_prestige > user.base_att.prestige:
            log.error('prestige. need: {0}, cur: {1}.'.format( need_prestige, user.base_att.prestige ))
            defer.returnValue( CHAR_PRESTIGE_NOT_ENOUGH )
        # 扣声望值
        user.consume_prestige( need_prestige, WAY_ARENA_EXCHANGE )
        # 向背包中新增道具
        model = ITEM_MODELs.get( conf['ItemType'], None )
        if not model:
            log.error('Can not find model. item type: {0}.'.format( conf['ItemType'] ))
            defer.returnValue( ITEM_TYPE_ERROR )
        res_err, add_items = yield model( user, ItemID=conf['ItemID'], ItemNum=exchange_count*conf['ItemNum'], AddType=WAY_ARENA_EXCHANGE, CapacityFlag=False )
        if res_err:
            defer.returnValue( res_err )

        # 更新已兑换记录
        if conf['MaxExchangeCount'] > 0:
            old_excharge[2] += exchange_count
        if conf['DailyExchangeCount'] > 0:
            old_excharge[3] += exchange_count
        yield redis.hset(HASH_ARENA_EXCHANGE, user.cid, dumps(data))

        defer.returnValue( (user.base_att.prestige, old_excharge[2], old_excharge[3], add_items) )
예제 #36
0
    def buyed_package(cid):
        data = yield redis.hget(HASH_VIP_PACKAGE_RECORD, cid)
        if data:
            data = loads(data)
        else:
            data = []

        defer.returnValue(data)
예제 #37
0
 def load_star_rewarded(self):
     ''' 加载副本已领奖的星数 '''
     if self.star_rewarded is None:
         self.star_rewarded = {}
         rewarded_data = yield redis.hget(HASH_SCENE_STAR_REWARDED,
                                          self.cid)
         if rewarded_data:
             self.star_rewarded = loads(rewarded_data)
예제 #38
0
    def buyed_package( cid ):
        data = yield redis.hget( HASH_VIP_PACKAGE_RECORD, cid )
        if data:
            data = loads( data )
        else:
            data = []
 
        defer.returnValue( data )
예제 #39
0
def friend_list(p, req):
    ''' 获取好友列表 '''
    cid, [index] = req

    user = g_UserMgr.getUser( cid )
    if not user:
        log.error('Can not find user. cid: {0}.'.format( cid ))
        defer.returnValue( CONNECTION_LOSE )

    add_douzhan = yield user.goodwill_mgr.check_achieve()

    totals = len(user.friends)
    #成就
    yield user.achievement_mgr.update_achievement_status( ACHIEVEMENT_QUEST_ID_20, totals )
    friend_cids = user.friends[:index+20]
    if (not friend_cids):
        defer.returnValue( [index, totals, [], 0, GET_DOUZHAN_DAILY_LIMIT + add_douzhan] )
 
    # 给好友赠送斗战点的信息
    gift_cids = []
    gift_data = yield redis.hget(HASH_FRIENDS_SEND_DOUZHAN, cid)
    if gift_data:
        gift_data = loads(gift_data)
        dt_now    = datetime.now()
        dt_last   = datetime.fromtimestamp( gift_data[0] )
        if dt_last.date() == dt_now.date():
            gift_cids = gift_data[1]
 
    friend_info  = []
    offline_cids = []
    for _cid in friend_cids:
        online_user = g_UserMgr.getUser( _cid )
        if online_user:
            _info = online_user.friend_info()
            _info.append(1) # 0-离线, 1-在线
            _info.append( 1 if _cid in gift_cids else 0 ) # 0-未赠送, 1-已赠送
            # 在线好友排序 ??
            friend_info.append( _info )
        else:
            offline_cids.append( _cid )
 
    # 查询db 获取offline_cids的基本信息
    try:
        if offline_cids:
            dataset = yield cs_call("cs_offline_friends", [cid, offline_cids])
            if dataset:
                for _info in dataset:
                    _info = list( _info )
                    _info.append(0) # 0-离线, 1-在线
                    _info.append( 1 if _info[0] in gift_cids else 0 ) # 0-未赠送, 1-已赠送
                    friend_info.append( _info )
    except Exception as e:
        log.error('cs_offline_friends error. e: {0}'.format( e ))

    left_count, gift_data = yield get_friend_douzhan_status(cid, add_douzhan)

    defer.returnValue( [index, totals, friend_info, len(gift_data), left_count] )
예제 #40
0
    def get_offline_user(self, cid):
        _m = self.__dict.get(cid, None)
        if not _m:
            # 离线的玩家
            _stream = yield redis.hget(HASH_ALLIANCE_MEMBER, cid)
            if _stream:
                _m = Member.load(_stream)

        returnValue(_m)
예제 #41
0
    def received_today(cid):
        _received = False

        _stream = yield redis.hget(DICT_NEWYEAR_PACKAGE, cid)
        if _stream:
            _last_recv_t = int(_stream)
            _received = timestamp_is_today(_last_recv_t)

        defer.returnValue(_received)
예제 #42
0
    def received_today(cid):
        _received = False

        _stream = yield redis.hget(DICT_NEWYEAR_PACKAGE, cid)
        if _stream:
            _last_recv_t = int(_stream)
            _received = timestamp_is_today(_last_recv_t)

        defer.returnValue(_received)
예제 #43
0
def time_limited_shop_desc(p, req):
    ''' 获取限时商店中的说明 '''
    desc_msgs = yield redis.hget( HASH_OSS_MESSAGES, FIELD_LIMIT_SHOP_DESC )
    if not desc_msgs:
        defer.returnValue( (NO_ERROR, []) )

    desc_msgs = loads(desc_msgs)

    defer.returnValue( (NO_ERROR, [desc_msgs['title'], desc_msgs['content']]) )
예제 #44
0
    def remain_avoid_war_time(cid):
        _remain = 0

        _t = yield redis.hget(HASH_AVOID_WAR_TIME, cid)

        if _t:
            _remain = int(_t) - int(time())
            _remain = _remain if _remain > 0 else 0

        defer.returnValue(_remain)
예제 #45
0
    def get_scene_reset_daily(self):
        ''' 获取玩家当天已全扫荡的次数、道具重置的次数、钻石重置的次数 '''
        reset_data = yield redis.hget(HASH_SCENE_RESET_DAILY, self.cid)
        if reset_data:
            reset_data = loads(reset_data)
            # 0-diff date, 1-same today
            if 1 == timestamp_is_today(reset_data[0]):
                defer.returnValue(reset_data)

        defer.returnValue([int(time()), 0, 0, 0])
예제 #46
0
    def get_scene_reset_daily(self):
        ''' 获取玩家当天已全扫荡的次数、道具重置的次数、钻石重置的次数 '''
        reset_data = yield redis.hget(HASH_SCENE_RESET_DAILY, self.cid)
        if reset_data:
            reset_data = loads(reset_data)
            # 0-diff date, 1-same today
            if 1 == timestamp_is_today(reset_data[0]):
                defer.returnValue( reset_data )

        defer.returnValue( [int(time()), 0, 0, 0] )
예제 #47
0
    def remain_avoid_war_time(cid):
        _remain = 0

        _t = yield redis.hget( HASH_AVOID_WAR_TIME, cid )

        if _t:
            _remain = int(_t) - int(time())
            _remain = _remain if _remain > 0 else 0

        defer.returnValue( _remain )
예제 #48
0
    def get_campcard_data(self):
        ''' 获取玩家的阵营抽卡信息 '''
        reset_flag = False
        curr_time = int(time())
        comm_data = yield redis.hget(HASH_CAMPRAND_COMMON, 'CAMPRAND')
        if comm_data:
            comm_data = loads(comm_data)
            if curr_time >= comm_data[0]:
                reset_flag = True
                comm_data[0] += CAMP_RAND_TIME
                comm_data[1] = 0 if len(
                    CAMP_GROUP_IDS) <= comm_data[1] + 1 else comm_data[1] + 1
                yield redis.hset(HASH_CAMPRAND_COMMON, 'CAMPRAND',
                                 dumps(comm_data))
            else:
                camp_data = yield redis.hget(HASH_CAMPRAND_COMMON, self.cid)
                if camp_data:
                    camp_data = loads(camp_data)
                    if 1 == timestamp_is_today(camp_data[0]):
                        curr_camp_data, next_camp_data = camp_data[
                            1], camp_data[2]
                    else:
                        reset_flag = True
                else:
                    reset_flag = True
        else:
            reset_flag = True
            comm_data = [get_reset_timestamp() + CAMP_RAND_TIME, 0]
            yield redis.hset(HASH_CAMPRAND_COMMON, 'CAMPRAND',
                             dumps(comm_data))

        if reset_flag:
            curr_camp_data = [[camp_id, 0]
                              for camp_id in CAMP_GROUP_IDS[comm_data[1]]]
            next_group_id = 0 if len(
                CAMP_GROUP_IDS) <= comm_data[1] + 1 else comm_data[1] + 1
            next_camp_data = [[camp_id, 0]
                              for camp_id in CAMP_GROUP_IDS[next_group_id]]
            yield redis.hset(
                HASH_CAMPRAND_COMMON, self.cid,
                dumps([curr_time, curr_camp_data, next_camp_data]))

        defer.returnValue((comm_data[0], curr_camp_data, next_camp_data))
예제 #49
0
    def dungeon_star_drop(self, dungeon_id, dungeon_star=1):
        '''
        @summary: 精英副本默认难度为1, 无conf则不用计算掉落
        @param  : drop_items-[ [item_type, item_id, item_num], ... ]
        '''
        drop_items = []

        drop_conf = get_drop_conf(dungeon_id, dungeon_star)
        if not drop_conf:
            log.error(
                'No drop conf. dungeon_id: {0}, dungeon_star: {1}.'.format(
                    dungeon_id, dungeon_star))
            defer.returnValue(drop_items)

        # old_rate format: {dungeon_star: {drop_id: rate, ...}, ...}
        old_rate = {}
        data = yield redis.hget(HASH_DUNGEON_DROP_RATE % dungeon_id, self.cid)
        if data:
            old_rate = loads(data)
            if old_rate.has_key(dungeon_star):
                old_star_rate = old_rate[dungeon_star]
            else:
                old_star_rate = {}
                old_rate[dungeon_star] = old_star_rate
                for _id, _drop in drop_conf.iteritems():
                    old_star_rate[_id] = _drop['RateMax']
        else:  # 第一次按照最大概率来计算掉落
            old_star_rate = {}
            old_rate[dungeon_star] = old_star_rate
            for _id, _drop in drop_conf.iteritems():
                old_star_rate[_id] = _drop['RateMax']

        for _drop_id, _drop in drop_conf.iteritems():
            add_rate = old_star_rate.setdefault(_drop_id, 0)
            _drop_rate = _drop['RateStart'] + add_rate
            # 单次增加的封顶概率
            if _drop_rate > _drop['RateMax']:
                _drop_rate = _drop['RateMax']
            # 掉落概率是万分比
            rand_int = random.randint(0, 10000)
            #log.info('For Test. rand_int: {0}, _drop_rate: {1}, _drop_id: {2}, _drop_num: {3}.'.format( rand_int, _drop_rate, _drop['ItemID'], _drop['ItemNum'] ))
            # _drop['QuestID'] 未处理
            # 当前随机值 不大于 配置的掉落概率值时掉落
            if rand_int <= _drop_rate:
                drop_items = add_new_items(
                    [_drop['ItemType'], _drop['ItemID'], _drop['ItemNum']],
                    drop_items)

                old_star_rate[_drop_id] = 0
            else:
                old_star_rate[_drop_id] += _drop['RateAdd']
        yield redis.hset(HASH_DUNGEON_DROP_RATE % dungeon_id, self.cid,
                         dumps(old_rate))

        defer.returnValue(drop_items)
예제 #50
0
파일: acl.py 프로젝트: anson-tang/3dkserver
def check_password( user, passwd ):
    res = False

    user   = user.strip()
    passwd = passwd.strip()

    _pass_in_redis = redis.hget( REDIS_PASSWORD_KEY, user )
    pprint('user: '******'passwd: ', passwd, '_pass_in_redis: ', _pass_in_redis)
    res = True # ( _pass_in_redis == passwd )

    return res
예제 #51
0
def get_level_status(cid):
    '''
    @summary: 礼包全部领取后ICON消失
    '''
    _data = yield redis.hget(HASH_LEVEL_PACKAGE, cid)
    if _data:
        _data = loads(_data)
    else:
        _data = []

    defer.returnValue( _data )
예제 #52
0
def get_current_server_count(package_id):
    _cnt = 0
    
    if not DICT_PACKAGE_SERVER_COUNTER.has_key(package_id):
        _cnt = yield redis.hget(HASH_PACKAGE_SERVER_COUNTER, package_id)
        _cnt = int(_cnt) if _cnt else 0
        DICT_PACKAGE_SERVER_COUNTER[package_id] = _cnt
    else:
        _cnt = DICT_PACKAGE_SERVER_COUNTER[package_id]

    returnValue(_cnt)
예제 #53
0
    def get_enemy_cids(self, cid):
        ''' '''
        _enemy_data = yield redis.hget(HASH_JOUST_ENEMY_INFO, cid)
        if _enemy_data:
            _enemy_data = loads(_enemy_data)
            if not timestamp_is_today(_enemy_data[0]):
                _enemy_data = [int(time()), []]
        else:
            _enemy_data = [int(time()), []]

        defer.returnValue(_enemy_data)
예제 #54
0
    def dungeon_star_drop(self, dungeon_id, dungeon_star, flag=False):
        '''
        @summary: 怪物组不同难度掉落, 无conf则不用计算掉落
              2015-01-27 没有精力时,最终掉落概率=(基础概率+增加概率)* 1/3
        @param  : flag-True:无精力*1/3, False:有精力*1
        @param  : drop_items-[ [item_type, item_id, item_num], ... ]
        '''
        drop_items=[]
        drop_conf = get_drop_conf( dungeon_id, dungeon_star )
        if not drop_conf:
            log.error('No drop conf. dungeon_id: {0}, dungeon_star: {1}.'.format( dungeon_id, dungeon_star ))
            defer.returnValue( drop_items )

        # old_rate format: {dungeon_star: {drop_id: rate, ...}, ...}
        old_rate  = {}
        data = yield redis.hget( HASH_DUNGEON_DROP_RATE % dungeon_id, self.cid )
        if data:
            old_rate = loads( data )
            if old_rate.has_key( dungeon_star ):
                old_star_rate = old_rate[dungeon_star]
            else:
                old_star_rate = {}
                old_rate[dungeon_star] = old_star_rate
                for _id, _drop in drop_conf.iteritems():
                    old_star_rate[_id] = _drop['RateMax']
        else: # 第一次按照最大概率来计算掉落
            old_star_rate = {}
            old_rate[dungeon_star] = old_star_rate
            for _id, _drop in drop_conf.iteritems():
                old_star_rate[_id] = _drop['RateMax']

        for _drop_id, _drop in drop_conf.iteritems():
            add_rate   = old_star_rate.get(_drop_id, old_star_rate.setdefault(_drop_id, 0))
            _drop_rate = _drop['RateStart'] + add_rate
            # 单次增加的封顶概率
            if _drop_rate > _drop['RateMax']:
                _drop_rate = _drop['RateMax']
            # 有无精力
            if flag:
                _drop_rate = _drop_rate / 3
            # 掉落概率是万分比
            rand_int = random.randint(0, 10000)
            # _drop['QuestID'] 未处理
            # 当前随机值 不大于 配置的掉落概率值时掉落
            if rand_int <= _drop_rate:
                drop_items = add_new_items( [_drop['ItemType'], _drop['ItemID'], _drop['ItemNum']] , drop_items )

                old_star_rate[_drop_id] = 0
            else:
                old_star_rate[_drop_id] += _drop['RateAdd']
        yield redis.hset( HASH_DUNGEON_DROP_RATE % dungeon_id, self.cid, dumps( old_rate ) )

        defer.returnValue( drop_items )
예제 #55
0
    def update_open_server_activity_quest(self, acType, count):
        ''' 更新开服狂欢任务的状态信息 
        '''
        ret = yield self.check_open_time()
        if not ret:
            defer.returnValue(OPEN_SERVER_IS_CLOSED)
        #获取任务状态
        data = yield redis.hget(HASH_OPEN_SERVER_INFO, self.cid)
        if not data:
            defer.returnValue( None )
        _data, _shop_data = loads( data )
    
        _all_conf = get_open_server_quest_conf()
        if not _all_conf:
            defer.returnValue( NOT_FOUND_CONF )
        #获取任务配置
        _value_data = _all_conf.get(acType, {})

        #修改任务完成进度和状态
        for _id, _v in _data.get(acType, {}).iteritems():
            if not _value_data.has_key(_id):
                continue
            if _v[0] == 1 or _v[0] == 2:
                continue
            _target_value = _value_data.get(_id, [0])[0]
            if acType in [OPEN_SERVER_QUEST_ID_3,OPEN_SERVER_QUEST_ID_10,OPEN_SERVER_QUEST_ID_2, OPEN_SERVER_QUEST_ID_4, OPEN_SERVER_QUEST_ID_11, OPEN_SERVER_QUEST_ID_12, OPEN_SERVER_QUEST_ID_14]:
                #玩家等级,混沌,战斗力,副本,精英, 天外天
                if int(count) >= _target_value and _v[0] == 0:
                    _v[0] = 1
                _v[1] = count
            elif acType in [OPEN_SERVER_QUEST_ID_5, OPEN_SERVER_QUEST_ID_6]:
                #穿戴装备品质, 强化装备
                if count[_target_value] >= 24 and _v[0] == 0:
                    _v[0] = 1
                _v[1] = count[_target_value]
            elif acType == OPEN_SERVER_QUEST_ID_7:
                #决斗场排名
                if int(count)!=0 and int(count) <= _target_value and _v[0] == 0:
                    _v[0] = 1
                _v[1] = count
            elif acType in [OPEN_SERVER_QUEST_ID_8, OPEN_SERVER_QUEST_ID_9,  
                            OPEN_SERVER_QUEST_ID_13, OPEN_SERVER_QUEST_ID_15, OPEN_SERVER_QUEST_ID_16]: 
                _v[1] += count
                if _target_value <= _v[1] and _v[0] == 0:
                    _v[0] = 1
            else:
                break
        
        # 更新任务状态
        yield redis.hset(HASH_OPEN_SERVER_INFO, self.cid, dumps([_data, _shop_data]))

        defer.returnValue( NO_ERROR )