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 )
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)
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 )
def sync(self): if not self.synced: try: redis.hset(DICT_LOVER_KISS, self.cid, dumps(self.value)) except: log.exception('cid:{0} status save failed. status:{1}.'.format( self.cid, self.value))
def set_session(cid): _session = uuid() redis.hset(REDIS_SESSION_KEY, cid, _session) response.set_cookie(COOKIE_KEY, '%s.%s' % (cid, _session), secret=COOKIE_SECRET, expires=(int(time()) + 14515200))
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)
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) )
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)
def get_dig_treasure_reward(self, t_type, count): if t_type == FREE_DIG: if self.free_dig_count >= 1: self.free_dig_count -= 1 self.dig_total_count += 1 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)) _item_rand = yield package_open(self.user, FREE_DIG_PACAKGE) if _item_rand: user_item_id = 0 _item_type, _item_id, _item_num, _notice = _item_rand _res = yield item_add(self.user, ItemType=_item_type, ItemID=_item_id, ItemNum=_item_num, AddType=WAY_DIG_TREASURE_FREE) defer.returnValue((_res[1], self.free_dig_count, self.dig_total_count, self.user.credits)) elif t_type == CREDITS_DIG: if self.user.credits >= 20 * count and self.dig_total_count <DIG_MAX_COUNT : _itemList = [] for i in xrange(count): _item_rand = yield package_open(self.user, CREDITS_DIG_PACAKGE) if _item_rand: user_item_id = 0 _item_type, _item_id, _item_num, _notice = _item_rand _res = yield item_add(self.user, ItemType=_item_type, ItemID=_item_id, ItemNum = _item_num, AddType=WAY_DIG_TREASURE_CREDITS) _itemList.append(_res[1][0]) self.dig_total_count += 1 yield self.user.consume_credits(20, WAY_DIG_TREASURE_CREDITS) 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)) if self.dig_total_count >= DIG_MAX_COUNT : break defer.returnValue((_itemList, self.free_dig_count, self.dig_total_count, self.user.credits)) else: defer.returnValue(HAD_DIG_MAX_COUNT)
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 )
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 )
def __migrate_accounts_registered(self): try: yield redis.delete(HASH_NICKNAME_REGISTERED, HASH_MACHINE_CODE_REGISTERED, HASH_UID_MACHINE_CODE, SET_RANK_PVP_WEIGHT) db_conf = {'host': setting.DB_CONF['host'], 'port' : setting.DB_CONF['port'], 'user' : setting.DB_CONF['user'], 'passwd' : setting.DB_CONF['pass'], 'db' : setting.DB_CONF['userdb'], 'charset' : 'utf8' } conn = MySQLdb.connect(**db_conf) cu = conn.cursor() cu.execute('SELECT `id`,`machine_code`,`nickname`,`max_weight` FROM tb_character') _dataset = cu.fetchall() for _id, _machine_code, _nickname, _max_weight in _dataset: yield redis.hset(HASH_NICKNAME_REGISTERED, _nickname, _id) yield redis.hset(HASH_MACHINE_CODE_REGISTERED, _machine_code, _id) yield redis.hset(HASH_UID_MACHINE_CODE, _id, _machine_code) yield redis.zadd(SET_RANK_PVP_WEIGHT, _id, -_max_weight) cu.close() conn.close() conn = None cu = None except Exception, e: reactor.callLater(1, self.__migrate_accounts_registered) print 'ERROR:', e print 'WARNING. Redis connection fail, callLater 1 second. redis:', redis
def __migrate_accounts_registered(self): try: yield redis.delete( DICT_ACCOUNT_REGISTERED ) yield redis.delete( DICT_NICKNAME_REGISTERED ) yield redis.delete( SET_CID_REGISTERED ) db_conf = {'host': DB['host'], 'port' : DB['port'], 'user' : DB['user'], 'passwd' : DB['pass'], 'db' : DB['db_userdb'], 'charset' : 'utf8' } conn = MySQLdb.connect(**db_conf) cu = conn.cursor() cu.execute('SELECT `account`,`nick_name`,`id`,`sid` FROM tb_character') _dataset = cu.fetchall() for _account_name, _nick_name, _id, _sid in _dataset: yield redis.hset(DICT_ACCOUNT_REGISTERED, '%s%s'%(_account_name,_sid), _id) yield redis.hset(DICT_NICKNAME_REGISTERED, _nick_name, _id) yield redis.sadd(SET_CID_REGISTERED, _id) cu.close() conn.close() conn = None cu = None except Exception, e: reactor.callLater(1, self.__migrate_accounts_registered) print 'ERROR:', e print 'WARNING. Redis connection fail, callLater 1 second. redis:', redis
def receive(self, user): cid = user.cid _recved = yield newYearPackage.received_today(cid) if _recved: defer.returnValue((NEWYEAR_PACKAGE_RECEIVED_ALREADY, None)) _item_rand = yield package_open(user, NEWYEAR_PACKAGE_ID) if _item_rand: user_item_id = 0 _item_type, _item_id, _item_num, _notice = _item_rand _res = yield item_add(user, ItemType=_item_type, ItemID=_item_id, ItemNum=_item_num, AddType=WAY_NEW_YEAR_PACKAGE) self.received_character_list.append( (user.lead_id, user.nick_name, _item_num)) redis.hset(DICT_NEWYEAR_PACKAGE, cid, int(time())) if _notice: message = RORATE_MESSAGE_ACHIEVE, ( ACHIEVE_TYPE_OPEN_NEWYEAR_PACKAGE, (user.nick_name, _item_num)) gw_broadcast('sync_broadcast', (message, )) defer.returnValue( (NO_ERROR, (user_item_id, _item_type, _item_id, _item_num))) else: defer.returnValue((UNKNOWN_ERROR, None))
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))
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)
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))
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 )
def sync(self): redis.hset( DICT_WORLDBOSS_ATTACKER_DATA, self._cid, dumps((self._attack_count, self._damage_total, self._attack_time, self._clear_count, self._gold_inspire_failed_count, self._credit_inspire_failed_count, self._gold_inspire_success_count, self._credit_inspire_success_count)))
def __rand_material(self, exchange_type, turn, add_cnt, except_material = None ): _all_turns = get_exchange_refresh_conf( exchange_type, turn ) _tmp_list_idx_and_rate = [] #暂存每个材料的index和计算出来的当前权重值 _material = None _rate_total = 0 #所有需要随机材料的总权重 _curr_rate = 0 _rand = 0 if _all_turns: _all_turn_cnt = yield redis.hmget( HASH_EXCHANGE_REFRESH_RATE, [ '{0}.{1}'.format( self.cid, _conf[0] ) for _conf in _all_turns ] ) _len_cnt = len( _all_turn_cnt ) for _idx, _turn_conf in enumerate( _all_turns ): if except_material == [ _turn_conf[3], _turn_conf[4], _turn_conf[5] ]: # 该材料不能参与随机,防止材料重复, DK-1663 continue _cnt = ( _all_turn_cnt[ _idx ] if _idx < _len_cnt else 0 ) or 0 _rate = _turn_conf[6] + ( ( _cnt * _turn_conf[7] ) if _cnt else 0 ) if _rate >= _turn_conf[8]: _rate = _turn_conf[8] _tmp_list_idx_and_rate.append( [ _idx, _rate, _cnt ] ) _rate_total += _rate _rand = rand_num( _rate_total ) for _c_idx, _c_rate, _c_cnt in _tmp_list_idx_and_rate: if _rand <= _curr_rate + _c_rate: #hitted _conf = _all_turns[ _c_idx ] #这里是material和target的数据结构了,找不到来这里找 if not _material: _material = [ _conf[3], _conf[4], _conf[5] ] if add_cnt: redis.hset( HASH_EXCHANGE_REFRESH_RATE, '{0}.{1}'.format( self.cid, _conf[0] ), 0 ) #命中后重置 else: if add_cnt: redis.hset( HASH_EXCHANGE_REFRESH_RATE, '{0}.{1}'.format( self.cid, _conf[0] ), _c_cnt + 1 ) #miss后累加 _curr_rate += _c_rate if not _material: log.warn( 'missing rand material. list_idx_and_rate as: {0}, exchange_type:{1}, turn:{2}, _all_turns:{3}, _curr_rate:{4}, _rate_total:{5}, _rand:{6}.'.format( _tmp_list_idx_and_rate, exchange_type, turn, _all_turns, _curr_rate, _rate_total, _rand ) ) #log.debug( 'list_idx_and_rate as: {0}, exchange_type:{1}, turn:{2}, _all_turns:{3}, _curr_rate:{4}, _rate_total:{5}, _rand:{6}, _material:{7}.'.format( # _tmp_list_idx_and_rate, exchange_type, turn, _all_turns, _curr_rate, _rate_total, _rand, _material ) ) defer.returnValue( _material )
def upgrade_random_level(self): ''' 将当前鉴玉等级提升到特定等级(暂定4级宝玉) ''' items_return = [] total_num, item_attribs = yield self.user.bag_item_mgr.get_items( ITEM_JADE_UPGRADE_ID) if total_num > 0: res_err, used_attribs = yield self.user.bag_item_mgr.use( ITEM_JADE_UPGRADE_ID, 1) if res_err: defer.returnValue(res_err) else: self.random_jade_level = JADE_UPGRADE_LEVEL yield redis.hset(HASH_RANDOM_JADE_LEVEL, self.cid, JADE_UPGRADE_LEVEL) # used_attribs-已使用的道具 for _a in used_attribs: items_return.append([ _a.attrib_id, ITEM_TYPE_ITEM, ITEM_JADE_UPGRADE_ID, _a.item_num ]) # add syslog syslogger(LOG_ITEM_LOSE, self.cid, self.user.level, self.user.vip_level, self.user.alliance_id, _a.attrib_id, ITEM_JADE_UPGRADE_ID, 1, WAY_JADE_UPGRADE_LEVEL) else: if JADE_UPGRADE_LEVEL_CREDITS > self.user.credits: defer.returnValue(CHAR_CREDIT_NOT_ENOUGH) else: self.random_jade_level = JADE_UPGRADE_LEVEL yield redis.hset(HASH_RANDOM_JADE_LEVEL, self.cid, JADE_UPGRADE_LEVEL) yield self.user.consume_credits(JADE_UPGRADE_LEVEL_CREDITS, WAY_JADE_UPGRADE_LEVEL) item_rand = yield package_open(self.user, JADE_UPGRADE_CHEST_ID) if not item_rand: defer.returnValue(NOT_FOUND_CONF) add_item = [] _model = ITEM_MODELs.get(item_rand[0], None) if _model: res_err, value = yield _model(self.user, ItemID=item_rand[1], ItemNum=item_rand[2], AddType=WAY_JADE_UPGRADE_LEVEL) if not res_err and value: add_item = value[0] if not add_item: defer.returnValue(UNKNOWN_ERROR) defer.returnValue((self.user.credits, self.random_jade_level, items_return, add_item))
def get_dig_treasure_reward(self, t_type, count): if t_type == FREE_DIG: if self.free_dig_count >= 1: self.free_dig_count -= 1 self.dig_total_count += 1 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)) _item_rand = yield package_open(self.user, FREE_DIG_PACAKGE) if _item_rand: user_item_id = 0 _item_type, _item_id, _item_num, _notice = _item_rand _res = yield item_add(self.user, ItemType=_item_type, ItemID=_item_id, ItemNum=_item_num, AddType=WAY_DIG_TREASURE_FREE) defer.returnValue( (_res[1], self.free_dig_count, self.dig_total_count, self.user.credits)) elif t_type == CREDITS_DIG: if self.user.credits >= 20 * count and self.dig_total_count < DIG_MAX_COUNT: _itemList = [] for i in xrange(count): _item_rand = yield package_open(self.user, CREDITS_DIG_PACAKGE) if _item_rand: user_item_id = 0 _item_type, _item_id, _item_num, _notice = _item_rand _res = yield item_add(self.user, ItemType=_item_type, ItemID=_item_id, ItemNum=_item_num, AddType=WAY_DIG_TREASURE_CREDITS) _itemList.append(_res[1][0]) self.dig_total_count += 1 yield self.user.consume_credits(20, WAY_DIG_TREASURE_CREDITS) 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)) if self.dig_total_count >= DIG_MAX_COUNT: break defer.returnValue((_itemList, self.free_dig_count, self.dig_total_count, self.user.credits)) else: defer.returnValue(HAD_DIG_MAX_COUNT)
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) )
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]))
def sync( self, force=False ): if self.__dirty or force: _info = self.__cid, self.__name, self.__lead_id, self.__level, self.__vip_level, \ self.__might, self.__rank, self.__logoff_time, self.__position, \ self.__contribution, self.__contribution_total, self.cd_time yield redis.hset( HASH_ALLIANCE_MEMBER, self.__cid, dumps( _info ) ) self.__dirty = False
def write_mail(p, req): ''' 保存新的邮件 page_type: 1:全部; 2:好友; 3:系统; 4:战斗 ''' try: rcv_cid, page_type, module_id, detail = req send_time = int(time()) except: rcv_cid, page_type, module_id, detail, send_time = req _key = HASH_MAIL_CONTENT % (page_type, rcv_cid) _primary = yield redis.hincrby(_key, MAIL_PRIMARY_INC, 1) content = dumps((_primary, send_time, page_type, module_id, detail)) yield redis.hset(_key, _primary, content) # 最多保存100条 _del_fields = [] _all_fields = yield redis.hkeys(_key) _all_fields = sorted(_all_fields, reverse=True) if len(_all_fields) > 101: _del_fields = _all_fields[101:] if MAIL_PRIMARY_INC in _del_fields: _del_fields.remove(MAIL_PRIMARY_INC) if _del_fields: yield redis.hdel(_key, *_del_fields) # 通知在线玩家有新邮件 rcv_user = g_UserMgr.getUserByCid(rcv_cid) if rcv_user and not rcv_user.notify_mail: rcv_user.notify_mail = True gw_send(rcv_cid, 'new_mail_notify', None)
def get_reward(self, reward_id): ''' 领取每日任务奖励 ''' _reward_conf = get_daily_quest_reward_conf(reward_id) if not _reward_conf: defer.returnValue( NOT_FOUND_CONF ) # 每日任务当前的状态 _status = yield self.status() # 重复领取 if reward_id in _status[1]: defer.returnValue( REPEAT_REWARD_ERROR ) # 总积分不足 if _reward_conf['Score'] > _status[3]: defer.returnValue( DAILY_QUEST_SCORE_NOT_ENOUGH ) # 给奖励 add_type = WAY_DAILY_QUEST add_items = [] # 新增的玩家道具信息 for _type, _id, _num in _reward_conf['Reward']: _model = ITEM_MODELs.get(_type, None) if not _model: log.error('Unknown item type. ItemType: {0}.'.format( _type )) continue res_err, value = yield _model(self.user, ItemID=_id, ItemNum=_num, CapacityFlag=False, AddType=add_type) if not res_err and value: for _v in value: add_items = total_new_items( _v, add_items ) else: log.error('User add items error. res_err: {0}, value: {1}.'.format( res_err, value )) # 更新领奖记录 _status[1].append( reward_id ) yield redis.hset( HASH_DAILY_QUEST, self.cid, dumps(_status) ) defer.returnValue( add_items )
def sync_old_record(self, data): _all_conf = get_all_achievement_conf() if not _all_conf: defer.returnValue( NOT_FOUND_CONF ) for quest_type, _info in data.iteritems(): _f = sorted(_info.items()) for _id, _v in _f: if not _all_conf.get(quest_type, {}).has_key(_id): continue _target_value, _pid, _ = _all_conf[quest_type][_id] if int(_pid) != 0 and int(_info.get(int(_pid), [0])[0]) == 0: continue if _v[0] == 1 or _v[0] == 2: continue if quest_type in (ACHIEVEMENT_TYPE_1 + ACHIEVEMENT_TYPE_2): if int(_v[1]) >= int(_target_value) and int(_v[0]) == 0: _info[_id][0] = 1 elif quest_type in [ACHIEVEMENT_QUEST_ID_7, ACHIEVEMENT_QUEST_ID_19]: #角斗场排名, 大乱斗 if int(_v[1]!=0) and int(_v[1]) <= int(_target_value) and _v[0] == 0: _info[_id][0] = 1 # elif quest_type in ACHIEVEMENT_TYPE_2: # if _v[1] >= int(_target_value) and int(_v[0]) == 0: # _v[0] = 1 yield redis.hset(HASH_ACHIEVEMENT_INFO, self.cid, dumps(data)) res = [] for _type, _info in data.iteritems(): for _id, value in _info.iteritems(): res.append([_id, value[0], value[1]]) defer.returnValue(res)
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 )
def update_lucky_ranklist(self): ''' @summary: 每晚22:00-22:15发放奖励时替换新旧幸运排名 ''' _lucky_data = yield self.lucky_ranklist() _old_data = [] _timestamp = int(time()) for _l in _lucky_data[1]: _detail = yield self.get_rank_detail( _l[0], flag=False ) if _detail: _old_data.append( [_l[0], _detail[2], _l[1], _detail[7]] ) if _detail[0] > 0: # 给离线玩家钻石 yield g_AwardCenterMgr.new_award( _detail[0], AWARD_TYPE_ARENA_LUCKY, [_timestamp, [[ITEM_TYPE_MONEY, ITEM_MONEY_CREDITS, _l[1]]]], False ) #_user_lucky = yield gs_offline_login( _detail[0] ) #if _user_lucky: # _user_lucky.get_credits( _l[1], WAY_ARENA_LUCK_RANK ) # reactor.callLater(SESSION_LOGOUT_REAL, gs_offline_logout, _detail[0]) #else: # log.warn('User login fail. lucky_cid: {0}.'.format( _detail[0] )) # 再次随机幸运排名 _new_data = [] _lucky_rank = random.sample(range(1, 501), 10) for _rank in _lucky_rank[0:3]: _new_data.append( [_rank, 50] ) for _rank in _lucky_rank[3:]: _new_data.append( [_rank, 25] ) # write redis _lucky_data = [_old_data, _new_data] yield redis.hset( HASH_ARENA_LUCKY_RANKLIST, LUCKY_RANKLIST, dumps( _lucky_data ) )
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 )
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]))
def reward_to_center(cid, pay_date, package_id): ''' 将未领的豪华签到奖励发放到领奖中心 @param: pay_date-查询当天的充值记录 @param: package_id-豪华签到的礼包ID ''' conf = get_pay_login_package_conf(package_id) if not conf: defer.returnValue(NOT_FOUND_CONF) # had total cost _date = pay_date.strftime("%Y-%m-%d") _had_cost = yield get_daily_pay_record(cid, _date) if conf['NeedCost'] > _had_cost: defer.returnValue(REQUEST_LIMIT_ERROR) # timestamp-豪华签到奖励的时间点 timestamp = datetime2time(pay_date) yield g_AwardCenterMgr.new_award(cid, AWARD_TYPE_PAY_LOGIN, [timestamp, package_id]) # 更新豪华签到记录 yield redis.hset(HASH_PAY_LOGIN_PACKAGE, cid, dumps([timestamp, package_id, 1])) defer.returnValue(NO_ERROR)
def write_mail(p, req): ''' 保存新的邮件 page_type: 1:全部; 2:好友; 3:系统; 4:战斗 ''' try: rcv_cid, page_type, module_id, detail = req send_time = int(time()) except: rcv_cid, page_type, module_id, detail, send_time = req _key = HASH_MAIL_CONTENT % (page_type, rcv_cid ) _primary = yield redis.hincrby( _key, MAIL_PRIMARY_INC, 1 ) content = dumps( (_primary, send_time, page_type, module_id, detail) ) yield redis.hset(_key, _primary, content) # 最多保存100条 _del_fields = [] _all_fields = yield redis.hkeys( _key ) _all_fields = sorted( _all_fields, reverse=True ) if len(_all_fields) > 101: _del_fields = _all_fields[101:] if MAIL_PRIMARY_INC in _del_fields: _del_fields.remove( MAIL_PRIMARY_INC ) if _del_fields: yield redis.hdel( _key, *_del_fields ) # 通知在线玩家有新邮件 rcv_user = g_UserMgr.getUserByCid(rcv_cid) if rcv_user and not rcv_user.notify_mail: rcv_user.notify_mail = True gw_send(rcv_cid, 'new_mail_notify', None)
def sync_record(self): if self.last_buyed_time and self.last_buyed_items: _buyed_items = [] for _id, _num in self.last_buyed_items.iteritems(): _buyed_items.append([_id, _num]) yield redis.hset(HASH_ITEM_SHOP_RECORD, self.cid, dumps((self.last_buyed_time, _buyed_items)))
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)
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) )
def update_avoid_cache(self, treasure_id): ''' @summary: 维护宝物碎片列表的同时, 维护redis中的玩家阵营数据 ''' if self.user.base_att.level <= AVOID_WAR_LEVEL: log.warn('User level <= 12 could not be plunder. cid: {0}.'.format( self.cid )) defer.returnValue( REQUEST_LIMIT_ERROR ) treasure_conf = get_item_by_itemid( treasure_id ) if not treasure_conf: log.error('Can not find conf. treasure_id: {0}.'.format( treasure_id )) defer.returnValue( NOT_FOUND_CONF ) _shard_list = [splited[1] for splited in treasure_conf['ChangeList'] ] # 只有同时拥有“一个宝物的2个或者2个以上,不同位置碎片”的玩家才会被加入被抢夺列表 _haved = 0 _plunder_list = [] # 可被抢夺的碎片 for _shard_id in _shard_list: for attrib in self.__gsattribs.itervalues(): if attrib.item_id == _shard_id: _haved += 1 _plunder_list.append( _shard_id ) break #_treasure_ids = yield redis.hget( HASH_TREASURE_CHARACTER_IDS, self.cid ) #if _treasure_ids: # _treasure_ids = loads(_treasure_ids) #else: # _treasure_ids = [] #log.info('For Test. _haved: {0}, cid: {1}, _shard_id: {2}, _shard_list: {3}, _plunder_list: {4}.'.format( _haved, self.cid, _shard_id, _shard_list, _plunder_list )) for _shard_id in _shard_list: yield redis.hdel( TPL_TREASURE_SHARD_GOT % _shard_id, self.cid ) #if treasure_id in _treasure_ids: # _treasure_ids.remove( treasure_id ) if _haved > 1: #_flag = True # 成功获取玩家有效阵容 #_exists = yield redis.hexists( HASH_TREASURE_CHARACTER_CAMP, self.cid ) #if (not _exists): # _all_camps = yield self.user.get_camp() # fellow_ids = [] # if _all_camps: # for camp_data in _all_camps[1]: # if not camp_data or not camp_data[1]: # continue # fellow_ids.append( camp_data[1][1] ) # # 有效的玩家阵容 # if fellow_ids: # yield redis.hset( HASH_TREASURE_CHARACTER_CAMP, self.cid, dumps(_all_camps) ) # #log.info('For Test. save treasure camp. cid: {0}.'.format( self.cid )) # else: # _flag = False # log.error('Save char treasure camp data fail. cid: {0}, _all_camps: {1}.'.format( self.cid, _all_camps )) for _shard_id in _plunder_list: yield redis.hset( TPL_TREASURE_SHARD_GOT % _shard_id, self.cid, dumps( (self.cid, self.user.level, self.user.base_att.nick_name) ) )
def gm_sync_time_limited_shop_desc(cmd, ts, args, sign): res_err = {'result': 1} if isinstance(args, dict): yield redis.hset( HASH_OSS_MESSAGES, FIELD_LIMIT_SHOP_DESC, marshal.dumps(args) ) else: res_err['result'] = GM_INVALID_ARGS defer.returnValue( res_err )
def update_star_rewarded(self, scene_id, star_count): ''' 更新已领奖的副本星数记录 ''' old_star_rewarded = yield self.get_star_rewarded(scene_id) if star_count not in old_star_rewarded: self.star_rewarded.setdefault(scene_id, []).append( star_count ) yield redis.hset( HASH_SCENE_STAR_REWARDED, self.cid, dumps( self.star_rewarded) ) else: log.error('scene star had been rewarded.')
def sync(self): if not self.synced: try: self.synced = True yield redis.hset( DICT_CONSTELLATION, self.cid, dumps( self.value_t ) ) #log.debug('cid:{0} status saved. status:{1}.'.format(self.cid, self.value_t)) except: log.exception('cid:{0} status save failed. status:{1}.'.format(self.cid, self.value_t))
def reset_dungeon_count(self, scene_id, dungeon_id, reset_way): dungeon = yield self.get_dungeon(scene_id, dungeon_id) if not dungeon: log.error('Unknown dungeon id. scene_id: {0}, dungeon_id: {1}.'.format( scene_id, dungeon_id )) defer.returnValue( REQUEST_LIMIT_ERROR ) # 判断是否还有剩余挑战次数 #if 1 > dungeon.dungeon_today_count: # defer.returnValue( REQUEST_LIMIT_ERROR ) daily_info = yield self.get_scene_reset_daily() had_reset = daily_info[2] + daily_info[3] # 检查当天最大可重置次数 vip_conf = get_vip_conf( self.user.vip_level ) if not vip_conf or (had_reset >= vip_conf['DungeonReset']): log.error('Dungeon reset count limit. cid:{0}, vip_level:{1}, max_count:{2}, item_reset:{3}, credit_reset:{4}.'.format( \ self.cid, self.user.vip_level, vip_conf['DungeonReset'] if vip_conf else 0, daily_info[2], daily_info[3])) defer.returnValue( CHAR_VIP_LEVEL_LIMIT ) items_return = [] # 检查reset_way if reset_way == SCENE_RESET_ITEM: daily_info[2] += 1 # 扣道具 total_item, item_attribs = yield self.user.bag_item_mgr.get_items( ITEM_SCENE_RESET_ID ) if 1 > total_item: defer.returnValue( CHAR_ITEM_NOT_ENOUGH ) res_err, used_attribs = yield self.user.bag_item_mgr.use(ITEM_SCENE_RESET_ID, 1) if res_err: defer.returnValue( res_err ) # used_attribs-已使用的道具 for _a in used_attribs: items_return.append( [_a.attrib_id, ITEM_TYPE_ITEM, ITEM_SCENE_RESET_ID, _a.item_num] ) # add syslog syslogger(LOG_ITEM_LOSE, self.cid, self.user.level, self.user.vip_level, \ self.user.alliance_id, _a.attrib_id, ITEM_SCENE_RESET_ID, 1, WAY_SCENE_RESET) elif reset_way == SCENE_RESET_CREDIT: daily_info[3] += 1 # 扣钻石 need_credits = get_scene_reset_conf(daily_info[3]) if 0 == need_credits: defer.returnValue( SCENE_RESET_ERROR ) if need_credits > self.user.credits: log.error('credits not enough. cid:{0}, need:{1}, curr:{2}, credit_reset:{3}.'.format( self.cid, need_credits, self.user.credits, daily_info[3] )) defer.returnValue( CHAR_CREDIT_NOT_ENOUGH ) yield self.user.consume_credits( need_credits, WAY_SCENE_RESET ) else: log.error('Unknown args. cid: {0}, reset_way: {1}.'.format( self.cid, reset_way )) defer.returnValue( REQUEST_LIMIT_ERROR ) dungeon.dungeon_today_count = 0 yield redis.hset(HASH_SCENE_RESET_DAILY, self.cid, dumps(daily_info)) # 删除redis冷却时间记录 yield redis.hdel( HASH_SCENE_COOLDOWN_TIME, self.cid ) defer.returnValue( (self.user.credits, items_return) )
def gm_sync_time_limited_shop_desc(cmd, ts, args, sign): res_err = {'result': 1} if isinstance(args, dict): yield redis.hset(HASH_OSS_MESSAGES, FIELD_LIMIT_SHOP_DESC, marshal.dumps(args)) else: res_err['result'] = GM_INVALID_ARGS defer.returnValue(res_err)
def get_battle_reward(self, status, elitescene_id): ''' @param : 战斗结果 status 0:fail, 1:success ''' self.revive_count = 0 self.old_elitescene_id = 0 ## 检查战斗条件是否满足 #errorno = yield self.check_battle_limit( elitescene_id ) #if errorno: # defer.returnValue( errorno ) # 战斗失败 if not status: defer.returnValue( (2, status, 0, 0, self.elitescene.free_fight + self.elitescene.buyed_fight, [], 0, 0, 0, self.user.base_att.energy) ) # 精英副本奖励金币、仙魂 golds_reward, soul_reward = 0, 0 # config conf = get_elitescene_conf( elitescene_id ) if conf: golds_reward, soul_reward = conf['Gold'], conf['Soul'] # 扣挑战次数 if self.elitescene.buyed_fight > 0: self.elitescene.buyed_fight -= 1 elif self.elitescene.free_fight > 0: self.elitescene.free_fight -= 1 else: log.error('No fight count. free_fight: {0}, buyed_fight: {1}.'.format( self.elitescene.free_fight, self.elitescene.buyed_fight )) defer.returnValue( SCENE_CHALLENGE_COUNT_LIMIT ) # 获取怪物组掉落, star默认为1 drop_items = yield self.dungeon_star_drop( elitescene_id, 1 ) # 新增掉落 way_others = str((FIGHT_TYPE_ELITE, elitescene_id, 1)) elitescene_drop_items = yield self.get_dungeon_drop( drop_items, way_others ) # 发放奖励 if golds_reward > 0: #self.user.base_att.golds += golds_reward self.user.get_golds( golds_reward, WAY_ELITESCENE_BATTLE ) if soul_reward > 0: self.user.base_att.soul += soul_reward # 更新已胜利的精英副本ID列表 if elitescene_id not in self.passed_elitescene_ids: self.passed_elitescene_ids.append( elitescene_id ) yield redis.hset( HASH_ELITESCENE_PASSED, self.cid, dumps(self.passed_elitescene_ids) ) # 每日任务计数 yield self.user.daily_quest_mgr.update_daily_quest( DAILY_QUEST_ID_2, 1 ) # 开服七天 self.passed_elitescene_ids.sort() yield self.user.open_server_mgr.update_open_server_activity_quest( OPEN_SERVER_QUEST_ID_12, self.passed_elitescene_ids[-1]) # add syslog #成就 yield self.user.achievement_mgr.update_achievement_status(ACHIEVEMENT_QUEST_ID_12, self.passed_elitescene_ids[-1]) str_drop_items = str(elitescene_drop_items).replace('[', '(') str_drop_items = str_drop_items.replace(']', ')') syslogger(LOG_SCENE_BATTLE, self.cid, self.user.level, self.user.vip_level, self.user.alliance_id, FIGHT_TYPE_ELITE, status, elitescene_id, 1, 0, soul_reward, golds_reward, str_drop_items) defer.returnValue( (2, status, 0, 0, self.elitescene.free_fight + self.elitescene.buyed_fight, elitescene_drop_items, golds_reward, soul_reward, 0, self.user.base_att.energy) )
def update_star_rewarded(self, scene_id, star_count): ''' 更新已领奖的副本星数记录 ''' old_star_rewarded = yield self.get_star_rewarded(scene_id) if star_count not in old_star_rewarded: self.star_rewarded.setdefault(scene_id, []).append(star_count) yield redis.hset(HASH_SCENE_STAR_REWARDED, self.cid, dumps(self.star_rewarded)) else: log.error('scene star had been rewarded.')
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)
def sync(self): if not self.synced: try: self.synced = True yield redis.hset(DICT_CONSTELLATION, self.cid, dumps(self.value_t)) #log.debug('cid:{0} status saved. status:{1}.'.format(self.cid, self.value_t)) except: log.exception('cid:{0} status save failed. status:{1}.'.format( self.cid, self.value_t))
def sync( self ): if not self.__dirty or self.deleted: defer.returnValue( NO_ERROR ) yield redis.hset( HASH_ALLIANCE_INFO, self.__id, self.stream ) # 同步在线公会成员的信息, 离线玩家已经在下线时同步了 for _cid in self.__members: _m = g_UserMgr.getUser( _cid ) if _m: yield _m.sync()
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))
def revise_leader(p, req): alliance_id, leader_name = req _a = server.get_alliance(alliance_id) if _a: _a.revise_leader_name(leader_name) yield redis.hset( HASH_ALLIANCE_INFO, _a.aid, _a.stream ) else: defer.returnValue (ALLIANCE_UNKNOWN_ERROR) defer.returnValue(0)
def arena_robot_data(): ''' modify 2014-10-28 @param: detail data format: {rank: [cid, level, name, rank, golds, prestige, [fellow_id, ...], lead_id], ...} ''' for _rank in range(1, 5001): _detail = dumps( [0, 0, '', _rank, 0, 0, [], 0] ) yield redis.hset( HASH_ARENA_RANK, _rank, _detail ) defer.returnValue( NO_ERROR )
def openservice_package_reward(p, req): ''' @summary: 礼包按照ID顺序领取, 全部领取后Icon消失。 ''' res_err = UNKNOWN_ERROR cid, [package_id] = req user = g_UserMgr.getUser(cid) if not user: log.error('Can not find user. cid: {0}.'.format(cid)) defer.returnValue(res_err) conf = get_openservice_package_conf(package_id) if not conf: log.error( 'No openservice package conf. cid: {0}, package_id: {1}.'.format( user.cid, package_id)) defer.returnValue(NOT_FOUND_CONF) login_timestamp, got_package_ids, max_can_get_id = yield get_openservice_status( cid) if package_id in got_package_ids: log.error('Had got the reward. cid: {0}, package_id: {1}.'.format( cid, package_id)) defer.returnValue(REPEAT_REWARD_ERROR) if package_id > max_can_get_id: log.error( 'Can not get the reward. cid: {0}, package_id: {1}, max_can_get_id: {2}.' .format(cid, package_id, max_can_get_id)) defer.returnValue(REQUEST_LIMIT_ERROR) # 保存已领取的玩家开服礼包记录 got_package_ids.append(package_id) items_return = [] yield redis.hset(HASH_OPENSERVICE_PACKAGE, user.cid, dumps([login_timestamp, got_package_ids, max_can_get_id])) syslogger(LOG_OPEN_SERVICE_PACKAGE, cid, user.level, user.vip_level, user.alliance_id, package_id) for _type, _id, _num in conf['RewardList']: model = ITEM_MODELs.get(_type, None) if not model: log.error('Unknown item type. cid: {0}, item: {1}.'.format( user.cid, (_type, _id, _num))) continue res_err, value = yield model(user, ItemID=_id, ItemNum=_num, AddType=WAY_OPENSERVICE_PACKAGE, CapacityFlag=False) if not res_err and value: for _v in value: items_return = total_new_items(_v, items_return) defer.returnValue(items_return)
def new_messages(self, member, content): ''' 新增留言 ''' _had_count, _all_messages, _ = yield self.check_valid_messages(member.cid) if _had_count >= MESSAGES_DAILY_MAX: defer.returnValue( ALLIANCE_MESSAGES_MAX_ERROR ) _all_messages.append( (int(time()), member.cid, content) ) _all_messages = _all_messages[-MESSAGES_COUNT_LIMIT:] yield redis.hset(HASH_ALLIANCE_MESSAGES, self.__id, dumps(_all_messages)) defer.returnValue( NO_ERROR )
def set_openservice_info(p, req): ''' used for test ''' cid, [package_id] = req #user = g_UserMgr.getUser(cid) #if not user: # log.error('Can not find user. cid: {0}.'.format( cid )) # defer.returnValue( CONNECTION_LOSE ) yield redis.hset(HASH_OPENSERVICE_PACKAGE, cid, dumps([0, [], package_id])) defer.returnValue( NO_ERROR )
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 )
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 )