def _getSessionDataRedis(userId, dataKey): values = daobase.executeUserCmd(userId, 'HMGET', dataKey, *UserSessionSchema.FIELD_GROUP_SESSION) if values[0] == None: # 补丁, 数据上线期间, 有些用户还没有建立session数据, 重主数据中获取 values = daobase.executeUserCmd(userId, 'HMGET', UserDataSchema.mkey(userId), *UserDataSchema.FIELD_GROUP_SESSION) datas = UserSessionSchema.checkDataDict(UserSessionSchema.FIELD_GROUP_SESSION, values, None) return datas
def _exchange(self, gameid, userid, actkey, exchangeid): info = self._exchanges.get(exchangeid) if not info: return {'result': 'fail', 'tip': "unknown productId"} buynum = self.get_exchange_buynum(userid, actkey, info) if buynum >= info['limitTimes']: return {'result': 'fail', 'tip': '兑换次数已满'} curtime = timestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(userid) try: userAssets.consumeContentItemList(gameid, info['costs'], False, curtime, "ACT_ITEM_EXCHANGE_COST", exchangeid) except: return {'result': 'fail', 'tip': '您的道具不足,快去获取道具吧'} daobase.executeUserCmd(userid, 'HINCRBY', actkey, self.FIELD_EXCHANGE_NUM.format(exchangeid), 1) assetList = userAssets.sendContent(gameid, info['content'], 1, True, timestamp.getCurrentTimestamp(), "ACT_ITEM_EXCHANGE_GAIN", exchangeid) response = self._query(userid, actkey) ftlog.info('TYActItemExchange._exchange gameId=', gameid, 'userId=', userid, 'activityId=', self.getid(), 'reward=', TYAssetUtils.buildContents(assetList), 'buynum=', buynum + 1, 'credit=', response['credit']) changeNames = TYAssetUtils.getChangeDataNames(assetList) datachangenotify.sendDataChangeNotify(gameid, userid, changeNames) response['result'] = 'ok' response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(assetList) return response
def check_reset(self, resettype, userid, actkey, data_field, time_field): oldtime = daobase.executeUserCmd(userid, 'HGET', actkey, time_field) curtime = timestamp.getCurrentTimestamp() if not oldtime or (resettype == 'day' and not timestamp.is_same_day(oldtime, curtime)): daobase.executeUserCmd(userid, 'HMSET', actkey, time_field, curtime, data_field, 0) return 0 return daobase.executeUserCmd(userid, 'HGET', actkey, data_field)
def _exchange(self, gameid, userid, actkey, exchangeid): info = self._exchanges.get(exchangeid) if not info: return {'result': 'fail', 'tip': "unknown productId"} buynum = self.get_exchange_buynum(userid, actkey, info) if buynum >= info['limitTimes']: return {'result': 'fail', 'tip': '兑换次数已满'} if not self.alter_user_credit(userid, actkey, -info['price']): return {'result': 'fail', 'tip': '您的积分不足'} daobase.executeUserCmd(userid, 'HINCRBY', actkey, self.FIELD_EXCHANGE_NUM.format(exchangeid), 1) userAssets = hallitem.itemSystem.loadUserAssets(userid) assetList = userAssets.sendContent(gameid, info['content'], 1, True, timestamp.getCurrentTimestamp(), "ACTIVITY_CREDIT_EXCHANGE", exchangeid) response = self._query(userid, actkey) ftlog.debug('TYActCreditExchange._exchange gameId=', gameid, 'userId=', userid, 'activityId=', self.getid(), 'reward=', TYAssetUtils.buildContents(assetList), 'buynum=', buynum + 1, 'credit=', response['credit']) changeNames = TYAssetUtils.getChangeDataNames(assetList) datachangenotify.sendDataChangeNotify(gameid, userid, changeNames) response['result'] = 'ok' response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(assetList) return response
def alter_user_credit(self, userid, actkey, delta): if not delta: return False cur = self.get_user_credit(userid, actkey) cur += delta if cur < 0: return False daobase.executeUserCmd(userid, 'HSET', actkey, self.FIELD_CREDIT_NUM, cur) return True
def saveUserMatchInfo(info): d = { 'st': info.state, 'instId': info.instId, 'crid': info.ctrlRoomId } if info.feeItem: d['fee'] = info.feeItem.toDict() jstr = strutil.dumps(d) key = buildKey(info.gameId, info.userId) daobase.executeUserCmd(info.userId, 'hset', key, info.bigRoomId, jstr)
def _add_credit(self, userid, credit, times): actkey = ACTIVITY_KEY.format(HALL_GAMEID, userid, self.act.getid()) if self.limit > 0: field_time = self.act.FIELD_SOURCE_TIME.format(self.index) field_data = self.act.FIELD_SOURCE_NUM.format(self.index) used = self.act.check_reset('day', userid, actkey, field_data, field_time) if used >= self.limit: return times = min(times, self.limit - used) daobase.executeUserCmd(userid, 'HINCRBY', actkey, field_data, times) delta = int(credit * times) if delta <= 0: return self.act.alter_user_credit(userid, actkey, delta)
def _setUserDatas(userId, datas): dataKey = UserDataSchema.mkey(userId) params = UserDataSchema.paramsDict2List(datas) ret = daobase.executeUserCmd(userId, 'HMSET', dataKey, *params) if _CACHE_USER_ENABLE: _cacheUser.update_group_dict_data(userId, dataKey, datas) return ret
def setGameAttr(uid, gameid, attrname, value): """ 设置用户游戏属性 """ assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int' assert (attrname not in daoconst.FILTER_MUST_FUNC_FIELDS) return daobase.executeUserCmd(uid, 'HSET', daoconst.HKEY_GAMEDATA + str(gameid) + ':' + str(uid), attrname, value)
def setStateAttr(uid, gameid, attrname, value): ''' 设置用户状态属性 ''' assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int' assert (attrname not in daoconst.FILTER_MUST_FUNC_FIELDS) return daobase.executeUserCmd(uid, 'HSET', daoconst.HKEY_STATEDATA + str(gameid) + ':' + str(uid), attrname, value)
def incrGameAttr(uid, gameid, attrname, value): ''' INCR用户游戏属性 ''' assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int' assert (attrname not in daoconst.FILTER_MUST_FUNC_FIELDS) return daobase.executeUserCmd(uid, 'HINCRBY', daoconst.HKEY_GAMEDATA + str(gameid) + ':' + str(uid), attrname, value)
def _delTaskData(userId, gameId, taskId): ''' 删除用户的一个道具的数据 ''' dataKey = GameTaskSchema.mkey(gameId, userId) data = daobase.executeUserCmd(userId, 'HDEL', dataKey, taskId) if _CACHE_TASK_ENABLE: _cacheTask.remove_group_dict_data(userId, dataKey, {int(taskId): 0}) return data
def _getGifts(self, userId, gameId, clientId, activityId): key = "TYActivity:%d:%d:%s" % (gameId, userId, activityId) ftlog.debug("getGifts key:", key) num = daobase.executeUserCmd(userId, 'hget', key, 'giftNum') ftlog.debug("getGifts key num1:", num) if not num: num = 0 ftlog.debug("getGifts key num:", num) return {"giftsNum": num}
def _delItemData(userId, gameId, itemId): ''' 删除用户的一个道具的数据 ''' dataKey = GameItemSchema.mkey(gameId, userId) data = daobase.executeUserCmd(userId, 'HDEL', dataKey, itemId) if _CACHE_ITEM_ENABLE: _cacheItem.remove_group_dict_data(userId, dataKey, {int(itemId): 0}) return data
def getStateAttr(uid, gameid, attrname, filterKeywords=False): ''' 获取用户状态属性 ''' assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int' value = daobase.executeUserCmd(uid, 'HGET', daoconst.HKEY_STATEDATA + str(gameid) + ':' + str(uid), attrname) if value and filterKeywords: return daobase.filterValue(attrname, value) return value
def _getItemDataRedis(userId, dataKey): itemDict = {} datas = daobase.executeUserCmd(userId, 'HGETALL', dataKey) if datas: x = 0 for i in xrange(len(datas) / 2): x = i * 2 itemDict[int(datas[x])] = base64.b64encode(datas[x + 1]) return itemDict
def getStateAttrs(uid, gameid, attrlist, filterKeywords=False): ''' 获取用户状态属性列表 ''' assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int' values = daobase.executeUserCmd(uid, 'HMGET', daoconst.HKEY_STATEDATA + str(gameid) + ':' + str(uid), *attrlist) if values and filterKeywords: return daobase.filterValues(attrlist, values) return values
def _get_click_cnt(self, userid, actkey, curtime=None): if not curtime: curtime = pktimestamp.getCurrentTimestamp() oldtime = daobase.executeUserCmd(userid, 'HGET', actkey, self.FIELD_TIME) if oldtime: if pktimestamp.is_same_day(oldtime, curtime): return daobase.executeUserCmd(userid, 'HGET', actkey, self.FIELD_WEEK_CNT), \ daobase.executeUserCmd(userid, 'HGET', actkey, self.FIELD_DAY_CNT) daobase.executeUserCmd(userid, 'HMSET', actkey, self.FIELD_TIME, curtime, self.FIELD_DAY_CNT, 0) if pktimestamp.is_same_week(oldtime, curtime): return daobase.executeUserCmd(userid, 'HGET', actkey, self.FIELD_WEEK_CNT), 0 daobase.executeUserCmd(userid, 'HSET', actkey, self.FIELD_WEEK_CNT, 0) return 0, 0 daobase.executeUserCmd(userid, 'HMSET', actkey, self.FIELD_TIME, curtime, self.FIELD_DAY_CNT, 0, self.FIELD_WEEK_CNT, 0) return 0, 0
def _getItemDataAll(userId, gameId): items = [] dataKey = GameItemSchema.mkey(gameId, userId) datas = daobase.executeUserCmd(userId, 'HGETALL', dataKey) if datas: x = 0 for i in xrange(len(datas) / 2): x = i * 2 items.append([int(datas[x]), datas[x + 1]]) return items
def _setItemData_(userId, gameId, itemId, itemDataB64): ''' 设置用户的一个道具的数据 ''' itemData = base64.b64decode(itemDataB64) dataKey = GameItemSchema.mkey(gameId, userId) data = daobase.executeUserCmd(userId, 'HSET', dataKey, itemId, itemData) if _CACHE_ITEM_ENABLE: _cacheItem.update_group_dict_data(userId, dataKey, {int(itemId): itemDataB64}) return data
def _setTaskData_(userId, gameId, taskId, taskDataB64): ''' 设置用户的一个道具的数据 ''' taskData = base64.b64decode(taskDataB64) dataKey = GameTaskSchema.mkey(gameId, userId) data = daobase.executeUserCmd(userId, 'HSET', dataKey, taskId, taskData) if _CACHE_TASK_ENABLE: _cacheTask.update_group_dict_data(userId, dataKey, {int(taskId): taskDataB64}) return data
def getTableChipsAll(uid): ''' 取得用户的table_chip 返回: 所有的tablechip ''' mkey = daoconst.HKEY_TABLECHIP + str(uid) value = daobase.executeUserCmd(uid, 'HGETALL', mkey) ftlog.debug('UserChip->getTableChipsAll', uid, 'result->', value) return value
def setStateAttrs(uid, gameid, attrlist, valuelist): ''' 设置用户状态属性列表 ''' assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int' gdkv = [] for k, v in zip(attrlist, valuelist): gdkv.append(k) gdkv.append(v) assert (k not in daoconst.FILTER_MUST_FUNC_FIELDS) return daobase.executeUserCmd(uid, 'HMSET', daoconst.HKEY_STATEDATA + str(gameid) + ':' + str(uid), *gdkv)
def loadUserMatchInfo(gameId, userId, bigRoomId): try: key = buildKey(gameId, userId) jstr = daobase.executeUserCmd(userId, 'hget', key, bigRoomId) if jstr: return decodeUserMatchInfo(gameId, userId, bigRoomId, jstr) return None except: ftlog.error('match_remote.loadUserMatchInfo gameId=', gameId, 'userId=', userId, 'bigRoomId=', bigRoomId) return None
def saveToGameData(cls, userId, gameDataKey, replayKey, gameId): """ 往gamedata下添加数据 """ replayDBKey = 'replay:%s' % (gameId) ftlog.debug("MJCreateTableRecord_saveToGameData userId", userId , "gameDataKey", gameDataKey , "replayKey", replayKey , "replayDBKey", replayDBKey) if daobase.executeUserCmd(userId, 'HEXISTS', gameDataKey, 'game_record'): ftlog.debug("MJCreateTableRecord_saveToGameData1") recordData = daobase.executeUserCmd(userId, 'HGET', gameDataKey, 'game_record') ftlog.debug("MJCreateTableRecord_saveToGameData2,recordData type = ", type(recordData), "content =", recordData) recordList = json.loads(str(recordData)) ftlog.debug("MJCreateTableRecord_saveToGameData2,recordList type = ", type(recordList), "content =", recordList) if recordList and isinstance(recordList, dict): while len(recordList['recordIndex']) >= 20: wastedReplayKey = recordList['recordIndex'].pop(0) hasKey = daobase.executeRePlayCmd('HEXISTS', replayDBKey, wastedReplayKey) if hasKey: daobase.executeRePlayCmd('HDEL', replayDBKey, wastedReplayKey) recordList['recordIndex'].append(replayKey) ftlog.debug("MJCreateTableRecord_saveToGameData3") daobase.executeUserCmd(userId, 'HSET', gameDataKey, 'game_record', json.dumps(recordList)) else: recordData = {"recordIndex": []} recordData['recordIndex'].append(replayKey) daobase.executeUserCmd(userId, 'HSET', gameDataKey, 'game_record', json.dumps(recordData))
def getTableChip(uid, gameid, tableId): ''' 取得用户的table_chip 返回: 否则返回gamedata中的tablechip ''' mkey = daoconst.HKEY_TABLECHIP + str(uid) mfield = str(tableId) value = daobase.executeUserCmd(uid, 'HGET', mkey, mfield) ftlog.debug('UserChip->get_table_chip', uid, gameid, tableId, 'result->', value) if not isinstance(value, (int, float)): return 0 return int(value)
def _buy(self, userId, gameId, clientId, activityId, buyId): buyConfig = self._getBuyConfig(buyId) if not buyConfig: return {"errorInfo": "config not exist", "errorCode": 2} consumeItemId = buyConfig["consume"] consumeName = buyConfig["consumeName"] consumeCount = buyConfig["count"] getCount = buyConfig["get"] unit = buyConfig["unit"] from hall.entity.hallitem import itemSystem userAssets = itemSystem.loadUserAssets(userId) _, count, _ = userAssets.consumeAsset(gameId, consumeItemId, consumeCount, int(time.time()), "ACTIVITY_BUY", 0) if count != consumeCount: info = u"您的%s不足!" % consumeName return {"reason": info} else: key = "TYActivity:%d:%d:%s" % (gameId, userId, activityId) daobase.executeUserCmd(userId, "hincrby", key, "giftNum", getCount) info = u"您获得了%d%s" % (getCount, unit) return {"reason": info}
def delTableChips(uid, tableIdList): ''' 取得用户的table_chip 返回: 所有的tablechip ''' value = 0 if tableIdList: for tid in tableIdList: moveAllTableChipToChip(uid, 9999, 'TABLE_TCHIP_TO_CHIP', 0, None, int(tid)) mkey = daoconst.HKEY_TABLECHIP + str(uid) value = daobase.executeUserCmd(uid, 'HDEL', mkey, *tableIdList) return value
def getUserChipAll(uid): ''' 取得用户的所有金币, 包含被带入的金币 ''' uchip = userdata.getAttr(uid, daoconst.ATT_CHIP) gchip1 = gamedata.getGameAttrInt(uid, 1, daoconst.ATT_TABLE_CHIP) # TODO 就代码数据兼容, 可删除 gchip8 = gamedata.getGameAttrInt(uid, 8, daoconst.ATT_TABLE_CHIP) # TODO 就代码数据兼容, 可删除 tchips = daobase.executeUserCmd(uid, 'HVALS', daoconst.HKEY_TABLECHIP + str(uid)) allchip = uchip + gchip1 + gchip8 if tchips: for x in tchips: if isinstance(x, (int, float)): allchip += int(x) return allchip
def getConfigForClient(self, gameId, userId, clientId): client = copy.deepcopy(self._clientConf) shareid = self._serverConf['share'] share = hallshare.findShare(shareid) if share: winrate = gamedata.getGameAttr(userId, 6, 'winrate') winrate = strutil.loads(winrate, ignoreException=True, execptionValue={}) todotask = share.buildTodotask(HALL_GAMEID, userId, 'share_click', {'userId': userId, 'actName': client['id'], 'dizhuPlayNum': winrate.get('pt', 0)}) client['config']["share"] = todotask.toDict() actkey = ACTIVITY_KEY.format(HALL_GAMEID, userId, client['id']) total = daobase.executeUserCmd(userId, 'HGET', actkey, self.FIELD_TOTAL_CNT) client['config']['total'] = total if total else 0 client['config']['today'] = self._get_click_cnt(userId, actkey)[1] return client
def checkUserQuitLoc(gameId, userId, roomId, clientId): gid = strutil.getBigRoomIdFromInstanceRoomId(roomId) ret = daobase.executeUserCmd( userId, 'HGET', 'quitol' + ':' + str(gameId) + ':' + str(userId), str(gid)) retDict = strutil.loads(ret) if ret else None if retDict: rid = retDict.get('roomId') tid = retDict.get('tableId') sid = retDict.get('seatId') gid = strutil.getGameIdFromInstanceRoomId(rid) if gid > 0 and rid > 0 and tid > 0: # 到具体的房间或桌子的服务上去查询, 是否是真的在桌子上 if tid == rid * 10000: # 玩家在队列房间或者比赛房间的等待队列中, 此处不做一致性检查,玩家发起quick_start时检查。 return 1 else: try: seatId, isObserving = roommgr.doCheckUserLoc( userId, gid, rid, tid, clientId) except: ftlog.error() return -1 ftlog.debug('_checkUserLoc->userId=', userId, 'seatId=', seatId, 'isObserving=', isObserving) if seatId > 0 or isObserving == 1: # 还在桌子上游戏 return 1 else: # 已经不再桌子上了, 清理所有的桌子带入金币 if sid > 0: from poker.entity.dao import userchip userchip.moveAllTableChipToChip( userId, gid, 'TABLE_TCHIP_TO_CHIP', 0, clientId, tid) # 清理当前的在线数据 _removeUserQuitLoc(gameId, userId, rid) return 0 else: # 到这儿, 数据是错误的, 删除处理 _removeUserQuitLoc(gameId, userId, rid) return 0
def _getAllSkills(userId): """ 获得所有技能数据 """ assert isinstance(userId, int) and userId > 0 value = daobase.executeUserCmd(userId, "HGETALL", _getUserSkillKey(userId)) if value: skillIds = value[0::2] infos = [ strutil.loads(info, False, True) for info in value[1::2] if info ] skillDict = dict(zip(skillIds, infos)) allSkillIdsConf = config.getAllSkillId() popSkillIds = [ skillId for skillId in skillIds if str(skillId) not in allSkillIdsConf ] for _skillId in popSkillIds: del skillDict[_skillId] return skillDict return {}
def _setSessionDatas(userId, datas): # TODO 补充user表中的几个数据至用户的session中sessionAppId, sessionDevId,city_code atts = [ UserDataSchema.SESSION_APPID, UserDataSchema.SESSION_DEVID, UserDataSchema.SESSION_CITY_CODE, UserDataSchema.SESSION_IP ] values = daobase.executeUserCmd(userId, 'HMGET', UserDataSchema.mkey(userId), *atts) values = UserDataSchema.checkDataList(atts, values, None) if not UserSessionSchema.APPID in datas: datas[UserSessionSchema.APPID] = values[0] if not UserSessionSchema.DEVICEID in datas: datas[UserSessionSchema.DEVICEID] = values[1] if not UserSessionSchema.CITYCODE in datas: datas[UserSessionSchema.CITYCODE] = values[2] datas[UserSessionSchema.IPADDRESS] = values[ 3] # TODO 加了阿里云代理后,CO服务的带的IP都是阿里的IP地址,只能在重SDK的数据中再取一次 dataKey = UserSessionSchema.mkey(userId) params = UserSessionSchema.paramsDict2List(datas) ret = daobase.sendUserCmd(userId, 'HMSET', dataKey, *params) return ret
def updateAchievementModuleTips(userId, isRefresh=False): """更新成就小红点""" module_tip.resetModuleTipEvent(userId, "achievement") taskConfigs = getAchievementAllTask(userId) if not taskConfigs: return achLevel = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.achievementLevel) receiveLevelState = daobase.executeUserCmd( userId, "HGET", fish_achievement_task.getTaskKey(userId), "levelReceived") if not receiveLevelState: if achLevel > 1: module_tip.addModuleTipEvent(userId, "achievement", 1) else: receiveLevelState = json.loads(receiveLevelState) maxLevel = max(set(receiveLevelState)) if achLevel > maxLevel: module_tip.addModuleTipEvent(userId, "achievement", 1) levelMap, starMap = {}, {} if isRefresh: levelMap, starMap = fish_achievement_task.getSkillMaxLevel(userId) honorIds = [] for honorId, configs in taskConfigs.iteritems(): for _, taskConf in configs.iteritems(): taskClass = FishAchievementTask(userId, taskConf) if isRefresh: if taskConf["type"] == AchieveType.SkillUp: # 技能最高级 targetInfo = taskConf["target"] if "star" in targetInfo: taskClass.updateProgress(starMap[int( targetInfo["star"])]) elif "condition" in targetInfo: taskClass.updateProgress(levelMap[int( targetInfo["condition"])]) if taskClass.isComplete(): honorIds.append(int(honorId)) if honorIds: module_tip.addModuleTipEvent(userId, "achievement", honorIds)
def loadAllUserMatchInfo(gameId, userId): ret = {} key = buildKey(gameId, userId) datas = daobase.executeUserCmd(userId, "hgetall", key) if ftlog.is_debug(): ftlog.debug("match_remote.loadAllUserMatchInfo gameId=", gameId, "userId=", userId, "key=", key, "datas=", datas) if datas: i = 0 while i + 1 < len(datas): try: bigRoomId = datas[i] userMatchInfo = decodeUserMatchInfo(gameId, userId, bigRoomId, datas[i + 1]) if userMatchInfo: ret[bigRoomId] = userMatchInfo except: ftlog.error("match_remote.loadAllUserMatchInfo gameId=", gameId, "bigRoomId=", datas[i], "userMatchInfo=", datas[i + 1]) i += 2 return ret
def _getData(self, fishPool, fpMultiple): """ 获取渔场转盘数据 """ fishPool = str(fishPool) if fishPool not in self.pwData: val = daobase.executeUserCmd(self.userId, "HGET", self.rdKey, fishPool) val = json.loads(val) if val else deepcopy(self.default_val) self.pwData[fishPool] = val # 处理新增数据. isUpdate = False for _idx, _value in enumerate(deepcopy(self.default_val)): if _idx + 1 > len(val): # 有新增的数据 isUpdate = True if _idx == PWValueSlot.BETCOUNT: _value = 1 # 老用户多倍竞猜次数为1 elif _idx == PWValueSlot.SPINTIMES: self.pwData[fishPool].insert(_idx, 0) idx = len( self.pwData[fishPool][PWValueSlot.TAKEN]) % len( self.pwConf["energy"]) total = self.pwConf["energy"][idx][fishPool]["cost"] if self.pwData[fishPool][ PWValueSlot. ENERGY] >= total and self.pwData[fishPool][ PWValueSlot.STATE] == PWState.NOT_SPIN: self.pwData[fishPool][PWValueSlot.ENERGY] = 0 self.pwData[fishPool][PWValueSlot.SPINTIMES] = 1 continue self.pwData[fishPool].insert(_idx, _value) if self.pwData[fishPool][ PWValueSlot.SPINTIMES] > self.maxSpinTimes: self.pwData[fishPool][ PWValueSlot.SPINTIMES] = self.maxSpinTimes isUpdate = True if isUpdate: self._setData(fishPool, fpMultiple) return self.pwData[fishPool]
def loadUserStatus(userId, clientId, timestamp=None): coupon = userchip.getCoupon(userId) jstr = daobase.executeUserCmd(userId, 'hget', 'rpexchange:%s:%s' % (HALL_GAMEID, userId), 'status') if ftlog.is_debug(): ftlog.debug('hall_red_packet_exchange.loadUserStatus', 'userId=', userId, 'clientId=', clientId, 'jstr=', jstr) if jstr: try: d = strutil.loads(jstr) status = UserStatus(userId, coupon) for ritem in d.get('ritems', []): status.addReceivedItem(ritem['count'], ritem['source'], ritem['time']) for eitem in d.get('eitems', []): eid, state = eitem[0], eitem[1] exchange = findExchange(eid) if not exchange: ftlog.warn( 'hall_red_packet_exchange.loadUserStatus UnknownExchange', 'userId=', userId, 'clientId=', clientId, 'exchangId=', eid) continue if state not in EXCHANGE_STATES: ftlog.warn( 'hall_red_packet_exchange.loadUserStatus BadState', 'userId=', userId, 'clientId=', clientId, 'exchangId=', eid, 'state=', state) continue status.addExchangeItem(exchange, state) return status except: ftlog.warn('hall_red_packet_exchange.loadUserStatus BadData', 'userId=', userId, 'clientId=', clientId, 'jstr=', jstr) return initUserStatus(UserStatus(userId, coupon), clientId)
def getConfigForClient(self, gameId, userId, clientId): client = copy.deepcopy(self._clientConf) shareid = self._serverConf['share'] share = hallshare.findShare(shareid) if share: winrate = gamedata.getGameAttr(userId, 6, 'winrate') winrate = strutil.loads(winrate, ignoreException=True, execptionValue={}) todotask = share.buildTodotask( HALL_GAMEID, userId, 'share_click', { 'userId': userId, 'actName': client['id'], 'dizhuPlayNum': winrate.get('pt', 0) }) client['config']["share"] = todotask.toDict() actkey = ACTIVITY_KEY.format(HALL_GAMEID, userId, client['id']) total = daobase.executeUserCmd(userId, 'HGET', actkey, self.FIELD_TOTAL_CNT) client['config']['total'] = total if total else 0 client['config']['today'] = self._get_click_cnt(userId, actkey)[1] return client
def _sendHonorCompensate(userId): """ 称号补偿 """ from newfish.entity import mail_system from newfish.entity.mail_system import MailRewardType oldKey = "honor2:%d:%d" % (FISH_GAMEID, userId) value = daobase.executeUserCmd(userId, "HGETALL", oldKey) if not value: return if gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.compensateOldHonor): return honorIds = value[0::2] infos = [strutil.loads(info, False, True) for info in value[1::2] if info] honorData = dict(zip(honorIds, infos)) compensateRewards = {} compensateConf = config.getAchievementConf().get("compensate", {}) compensateKeys = compensateConf.keys() for key_, value_ in honorData.iteritems(): key_ = str(key_) if key_ in compensateKeys and value_[INDEX_STATE] > 0: _reward = compensateConf.get(key_, {}) compensateRewards.setdefault(_reward.get("name"), 0) compensateRewards[_reward.get("name")] += _reward.get("count") rewards = [] for k, v in compensateRewards.iteritems(): rewards.append({"name": int(k), "count": int(v)}) msg = config.getMultiLangTextConf("ID_HONOR_TASK_CHANGE_REWARD_MSG", lang=util.getLanguage(userId)) if rewards: mail_system.sendSystemMail(userId, MailRewardType.SystemCompensate, rewards, msg) # daobase.executeUserCmd(userId, "del", oldKey) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.compensateOldHonor, 1)
def sportlotteryRewardList(userId): # 对我的竞猜记录进行处理 doMySportlottery(userId) rewardList = [] noWinList = daobase.executeUserCmd(userId, 'lrange', noWinKey % userId, 0, -1) if len(noWinList) > 0: for nowin in noWinList: d = strutil.loads(nowin) rewardList.append(d) winList = daobase.executeUserCmd(userId, 'lrange', winkey % userId, 0, -1) if len(winList) > 0: for win in winList: d = strutil.loads(win) rewardList.append(d) for noOpenKey in [noOpenHomeKey, noOpenAveKey, noOpenAwayKey]: dateMatchIdList = daobase.executeUserCmd(userId, 'hkeys', noOpenKey % userId) if len(dateMatchIdList) > 0: for dateMatchIdStr in dateMatchIdList: jstr = daobase.executeUserCmd(userId, 'hget', noOpenKey % userId, dateMatchIdStr) if jstr: j = strutil.loads(jstr) rewardList.append(j) dateMatchIdList = daobase.executeUserCmd(userId, 'hkeys', waitRewardKey % userId) if len(dateMatchIdList) > 0: for dateMatchIdStr in dateMatchIdList: jstr = daobase.executeUserCmd(userId, 'hget', waitRewardKey % userId, dateMatchIdStr) if jstr: j = strutil.loads(jstr) rewardList.append(j) return rewardList[-30:]
def refreshDailyQuestGroupLv(userId): """ 刷新每日任务难度等级 """ gunLevel_m = util.getGunLevelVal(userId, config.MULTIPLE_MODE) curDayStartTs = util.getDayStartTimestamp(int(time.time())) initLv = getInitQuestLv(userId) dailyQuestConf = config.getDailyQuestConf() key = _getUserDailyQuestGroupLvKey(userId) groupLvData = gamedata.getGameAttrJson(userId, FISH_GAMEID, key, {}) questInfo = getUserQuestInfoData(userId) for taskId, state in questInfo.iteritems(): state = state[-1] if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, taskId, state, dailyQuestConf.get(str(taskId), {})) groupId = dailyQuestConf.get(str(taskId), {}).get("groupId", 0) if groupId: groupId = str(groupId) if groupId in groupLvData.keys(): # 玩家没有连续登陆, 清零难度经验进度 ts = 0 if len(groupLvData[groupId]) > 2: ts = groupLvData[groupId][2] dayStartTs = util.getDayStartTimestamp(ts) if dayStartTs + 86400 < curDayStartTs: groupLvData[groupId][1] = 0 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "reset exp !") else: if state >= QuestTaskState.Complete: # 完成任务增加难度经验 if groupLvData[groupId][1] < 2: groupLvData[groupId][1] += 1 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "increase exp !") else: # 未完成任务, 且前一天游戏时长超过20分钟则削减难度经验 _key = GameData.playGameTime % (FISH_GAMEID, userId, dayStartTs) playGameTime = daobase.executeUserCmd(userId, "GET", _key) or 0 if playGameTime >= 20: # 降级变更为1天不完成并且游戏时长大于20分钟就降级,即满足要求+1,不满足-2 if groupLvData[groupId][1] > -2 and groupLvData[groupId][0] > 1: groupLvData[groupId][1] -= 2 # 1 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "decrease exp !") # if groupLvData[groupId][1] >= 2: # groupLvData[groupId][0] += 1 # groupLvData[groupId][1] = 0 # ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "increase lv !") if groupLvData[groupId][1] <= -2 and groupLvData[groupId][0] > 1: groupLvData[groupId][0] -= 1 groupLvData[groupId][1] = 0 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "decrease lv !") groupLvData[groupId][2] = curDayStartTs else: _, lv = getQuestTaskId(groupId, initLv, gunLevel_m, userId) groupLvData[groupId] = [lv, 0, curDayStartTs] # groupLvData[groupId][0] = min(10, max(1, groupLvData[groupId][0])) if len(groupLvData) == 0: groupIdList = config.getDailyQuestGroupOrder() for groupId in groupIdList: _, lv = getQuestTaskId(groupId, initLv, gunLevel_m, userId) groupLvData[groupId] = [lv, 0, curDayStartTs] else: for k in groupLvData.keys(): groupLvData[k][2] = curDayStartTs gamedata.setGameAttr(userId, FISH_GAMEID, key, json.dumps(groupLvData)) if ftlog.is_debug(): ftlog.debug("daily_quest, user ="******"groupLvData =", groupLvData)
def saveModel(self, userId, key): jstr = strutil.dumps(self.toDict()) daobase.executeUserCmd(userId, 'hset', 'act:%s:%s' % (DIZHU_GAMEID, userId), key, jstr)
def loadModel(self, userId, key): jstr = daobase.executeUserCmd(userId, 'hget', 'act:%s:%s' % (DIZHU_GAMEID, userId), key) if jstr: return self.fromDict(strutil.loads(jstr)) return None
def save(cls, userId, key, data): rpath = 'erdayi:6:' + str(userId) daobase.executeUserCmd(userId, 'hset', rpath, key, strutil.dumps(data))
def saveMoneyToPiggyBank(userId, clientId): """ 向存钱罐存钱 """ vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) conf = config.getPiggyBankConf(clientId, vipLevel) key = UserData.piggyBankData % (FISH_GAMEID, userId) ts = int(time.time()) / 60 * 60 curDayStartTS = util.getDayStartTimestamp(ts) # 初始化存档. _initSaveLoad(userId, clientId) for k, v in conf.iteritems(): piggyBankData = daobase.executeUserCmd(userId, "HGET", key, k) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} # ftlog.debug("piggy_bank, userId =", userId, piggyBankData) lastTS = piggyBankData.get(GameData.pb_saveMoneyTS, 0) if lastTS == 0: continue endcoolingTs = piggyBankData.get(GameData.pb_endcoolingTS, 0) unitCount = v.get("outroom", 0) resetTime = _getResetTime(v.get("resetTime", -1)) # 处理跨天逻辑. while lastTS < curDayStartTS: if resetTime != -1: resetTS = util.getDayStartTimestamp(lastTS) + resetTime * 3600 if lastTS < endcoolingTs < resetTS: lastTS = endcoolingTs elif resetTS < endcoolingTs: lastTS = resetTS if lastTS < resetTS: interval = (resetTS - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(resetTS)) addMoneyToPiggyBank(userId, clientId, k, addCount, resetTS - 1) lastTS = resetTS nextStartDayTS = util.getDayStartTimestamp(lastTS) + 86400 if lastTS < endcoolingTs < nextStartDayTS: lastTS = endcoolingTs elif nextStartDayTS < endcoolingTs: lastTS = nextStartDayTS interval = (nextStartDayTS - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(nextStartDayTS)) addMoneyToPiggyBank(userId, clientId, k, addCount, nextStartDayTS - 1) lastTS = nextStartDayTS if resetTime != -1: resetTS = util.getDayStartTimestamp(lastTS) + resetTime * 3600 if lastTS < resetTS < ts: if lastTS < endcoolingTs < resetTS: lastTS = endcoolingTs elif resetTS < endcoolingTs: lastTS = resetTS interval = (resetTS - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(resetTS)) addMoneyToPiggyBank(userId, clientId, k, addCount, resetTS - 1) lastTS = resetTS if lastTS < endcoolingTs < ts: lastTS = endcoolingTs elif ts < endcoolingTs: lastTS = ts interval = (ts - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(ts)) addMoneyToPiggyBank(userId, clientId, k, addCount, ts) # 清理过期的每日积累上线key for k, v in conf.iteritems(): piggyBankData = daobase.executeUserCmd(userId, "HGET", key, k) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} isChanged = False resetTime = _getResetTime(v.get("resetTime", -1)) _resetTS = int(_getDataKey(int(time.time()), resetTime)) ts_keys = piggyBankData[GameData.pb_savedMoneyCount].keys() for ts in ts_keys: if int(ts) < _resetTS: ftlog.debug( "piggy_bank, delete pb_savedMoneyCount expired ts key, userId =", userId, "type =", k, "ts =", util.timestampToStr(int(ts)), "val =", piggyBankData[GameData.pb_savedMoneyCount][ts]) del piggyBankData[GameData.pb_savedMoneyCount][ts] isChanged = True if resetTime != -1: ts_keys = piggyBankData.get(GameData.pb_moneyCountDict, {}).keys() for ts in ts_keys: if int(ts) < _resetTS: ftlog.debug( "piggy_bank, delete pb_moneyCountDict expired ts key, userId =", userId, "type =", k, "ts =", util.timestampToStr(int(ts)), "val =", piggyBankData[GameData.pb_moneyCountDict][ts]) del piggyBankData[GameData.pb_moneyCountDict][ts] isChanged = True if isChanged: # ftlog.debug("piggy_bank, piggyBankData changed, userId =", userId, piggyBankData) daobase.executeUserCmd(userId, "HSET", key, k, json.dumps(piggyBankData))
def setRewardAsync(uid, gameid, value): assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int' return daobase.executeUserCmd( uid, 'SET', HKEY_REWARD_ASYNC + str(gameid) + ':' + str(uid), value)
def getCollectTimes(cls, userId): return daobase.executeUserCmd(userId, 'HGET', 'act:christmas:6:' + str(userId), 'reward')
def buyPiggyBank(userId, clientId, productId, buyType=None, itemId=0): """ 购买存钱罐 """ code = 3 rewards = [] product = config.getPiggyBankProduct(clientId, productId) if product is None: mo = MsgPack() mo.setCmd("piggyBankBuy") mo.setResult("gameId", config.FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("productId", productId) mo.setResult("code", code) router.sendToUser(mo, userId) ftlog.warn("piggy_bank, userId =", userId, "productId =", productId, "buyType =", buyType, "code =", code) return # if buyType: # if buyType not in product.get("otherBuyType", {}): # return # else: # buyType = product.get("buyType") type = product.get("type") key = UserData.piggyBankData % (FISH_GAMEID, userId) piggyBankData = daobase.executeUserCmd(userId, "HGET", key, type) dailyMaxTimes = product.get("dailyTimes", 0) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} ts = int(time.time()) / 60 * 60 if piggyBankData.get(GameData.pb_enable, 0) == 0 and weakdata.getDayFishData( userId, "pb_buyTimes", 0) < dailyMaxTimes: isSucc = False if buyType in product.get("otherBuyType", {}): price = product["otherBuyType"].get(buyType, 0) if buyType == config.BT_VOUCHER and price > 0: _consume = [{ "name": config.VOUCHER_KINDID, "count": abs(price) }] _ret = util.consumeItems( userId, _consume, "BI_NFISH_BUY_ITEM_CONSUME", pokerconf.productIdToNumber(productId), param01=productId) vip_system.addUserVipExp( config.FISH_GAMEID, userId, abs(price) * 10, "BUY_PRODUCT", pokerconf.productIdToNumber(productId), productId, rmbs=abs(price)) if _ret: isSucc = True else: code = 2 else: isSucc = True elif buyType == config.BT_DIRECT or config.isThirdBuyType(buyType): isSucc = True elif buyType == config.BT_DIAMOND: price = product.get("price_diamond", 0) price, _ret = store.getUseRebateItemPrice(userId, itemId, price, buyType, productId, clientId) # 满减券之后的钻石 满减券 if price > 0: consumeCount = 0 if _ret: store.autoConvertVoucherToDiamond(userId, price) # 代购券 consumeCount, final = userchip.incrDiamond( userId, FISH_GAMEID, -abs(price), 0, "BI_NFISH_BUY_ITEM_CONSUME", int(config.DIAMOND_KINDID), util.getClientId(userId), param01=productId) if not _ret or abs(consumeCount) != price: code = 2 else: isSucc = True if isSucc: piggyBankData[GameData.pb_enable] = 1 # piggyBankData[GameData.pb_saveMoneyTS] = ts piggyBankData[GameData.pb_getMoneyTS] = 0 # piggyBankData[GameData.pb_moneyCount] = conf.get("initVal", 0) pb_buyTimes = weakdata.incrDayFishData(userId, "pb_buyTimes", 1) # piggyBankData[GameData.pb_buyTimes] = piggyBankData.get(GameData.pb_buyTimes, 0) + 1 daobase.executeUserCmd(userId, "HSET", key, type, json.dumps(piggyBankData)) code, rewards = getMoney(userId, clientId, productId) mo = MsgPack() mo.setCmd("piggyBankBuy") mo.setResult("gameId", config.FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("productId", productId) mo.setResult("code", code) if code == 0: util.addProductBuyEvent(userId, productId, clientId) mo.setResult("reward", rewards) router.sendToUser(mo, userId) vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) ftlog.debug("piggy_bank, userId =", userId, "vip =", vipLevel, "type =", type, "code =", code, "piggyBankData =", piggyBankData, util.timestampToStr(ts), product) getPiggyBankInfo(userId, clientId)
def save(self): ''' 保存用户数据 ''' jstr = strutil.dumps(self.toDict()) rpath = self.getRedisStoragePath(self.activityGameId, self.userId) daobase.executeUserCmd(self.userId, 'hset', rpath, self.activityId, jstr)
def _initSaveLoad(userId, clientId): """ 初始化存档 """ _ts = int(time.time()) / 60 * 60 vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) piggyBankconf = config.getPiggyBankConf(clientId, vipLevel) key = UserData.piggyBankData % (FISH_GAMEID, userId) if not daobase.executeUserCmd(userId, "EXISTS", key): curDayStartTS = util.getDayStartTimestamp(_ts) freeData = { GameData.pb_enable: 1, GameData.pb_saveMoneyTS: _ts, GameData.pb_moneyCount: piggyBankconf.get("free", {}).get("initVal", 0), GameData.pb_getMoneyTS: 0., GameData.pb_savedMoneyCount: { str(curDayStartTS): 0. } } paidData = { GameData.pb_enable: 0, GameData.pb_saveMoneyTS: _ts, GameData.pb_moneyCount: piggyBankconf.get("paid", {}).get("initVal", 0), GameData.pb_getMoneyTS: 0., GameData.pb_savedMoneyCount: { str(curDayStartTS): 0. } } daobase.executeUserCmd(userId, "HSET", key, "free", json.dumps(freeData)) daobase.executeUserCmd(userId, "HSET", key, "paid", json.dumps(paidData)) if True: freeData = daobase.executeUserCmd(userId, "HGET", key, "free") freeData = json.loads(freeData or "{}") resetTime = _getResetTime( piggyBankconf.get("free", {}).get("resetTime", -1)) if resetTime != -1: resetKey = _getDataKey(_ts, resetTime) freeData.setdefault(GameData.pb_moneyCountDict, {}) freeData[GameData.pb_moneyCountDict].setdefault( resetKey, piggyBankconf.get("free", {}).get("initVal", 0)) freeData[GameData.pb_moneyCount] = freeData[ GameData.pb_moneyCountDict][resetKey] daobase.executeUserCmd(userId, "HSET", key, "free", json.dumps(freeData)) ftlog.debug("piggy_bank, userId =", userId, "free", freeData) else: # 之前是重置的存钱罐,使用最近一次的存档存档. ts_keys = freeData.get(GameData.pb_moneyCountDict, {}).keys() if isinstance(ts_keys, list) and len(ts_keys) > 0: ts_keys = [int(_t) for _t in ts_keys] ts_keys.sort() freeData[GameData.pb_moneyCount] = freeData[ GameData.pb_moneyCountDict][str(ts_keys[-1])] del freeData[GameData.pb_moneyCountDict] daobase.executeUserCmd(userId, "HSET", key, "free", json.dumps(freeData)) ftlog.debug("piggy_bank, use old saveload, userId =", userId, "free =", freeData) paidData = daobase.executeUserCmd(userId, "HGET", key, "paid") paidData = json.loads(paidData or "{}") resetTime = _getResetTime( piggyBankconf.get("paid", {}).get("resetTime", -1)) if resetTime != -1: resetKey = _getDataKey(_ts, resetTime) paidData.setdefault(GameData.pb_moneyCountDict, {}) paidData[GameData.pb_moneyCountDict].setdefault( resetKey, piggyBankconf.get("paid", {}).get("initVal", 0)) paidData[GameData.pb_moneyCount] = paidData[ GameData.pb_moneyCountDict][resetKey] daobase.executeUserCmd(userId, "HSET", key, "paid", json.dumps(paidData)) ftlog.debug("piggy_bank, userId =", userId, "paid", paidData) else: # 之前是重置的存钱罐,使用最近一次的存档存档. ts_keys = paidData.get(GameData.pb_moneyCountDict, {}).keys() if isinstance(ts_keys, list) and len(ts_keys) > 0: ts_keys = [int(_t) for _t in ts_keys] ts_keys.sort() paidData[GameData.pb_moneyCount] = paidData[ GameData.pb_moneyCountDict][str(ts_keys[-1])] del paidData[GameData.pb_moneyCountDict] daobase.executeUserCmd(userId, "HSET", key, "paid", json.dumps(paidData)) ftlog.debug("piggy_bank, use old saveload, userId =", userId, "paid =", paidData)
def getPiggyBankInfo(userId, clientId): """ 获取存钱罐数据 """ saveMoneyToPiggyBank(userId, clientId) vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) key = UserData.piggyBankData % (FISH_GAMEID, userId) conf = config.getPiggyBankConf(clientId, vipLevel) info = {} ts = int(time.time()) lang = util.getLanguage(userId) for k, v in conf.iteritems(): piggyBankData = daobase.executeUserCmd(userId, "HGET", key, k) piggyBankData = json.loads(piggyBankData) info[k] = {} resetTime = _getResetTime(v.get("resetTime", -1)) _resetKey = _getDataKey( ts, resetTime) # str(util.getDayStartTimestamp(ts)) info[k]["productId"] = v.get("productId", "") info[k]["productName"] = v.get("productName", "") info[k]["maxDailyCount"] = v.get("maxDailyCount", 0) info[k]["maxCount"] = v.get("maxCount", 0) info[k]["price"] = v.get("price", 0) info[k]["price_direct"] = v.get("price_direct", 0) info[k]["price_diamond"] = v.get("price_diamond", 0) info[k]["rule"] = 0 ruleId = v.get("rule", 0) if ruleId: info[k]["rule"] = config.getMultiLangTextConf(str(ruleId), lang=lang) #info[k]["rule"] = v.get("rule", 0) info[k]["enable"] = piggyBankData.get(GameData.pb_enable, 0) if resetTime == -1: curCount = int(piggyBankData.get(GameData.pb_moneyCount, 0)) else: curCount = int( piggyBankData.get(GameData.pb_moneyCountDict, {}).get(_resetKey, 0)) info[k]["curCount"] = min(v.get("maxCount", 0), curCount) info[k]["dailyCount"] = int( piggyBankData[GameData.pb_savedMoneyCount].setdefault( _resetKey, 0)) dailyMaxTimes = v.get("dailyTimes", 0) if weakdata.getDayFishData(userId, "pb_buyTimes", 0) < dailyMaxTimes: info[k]["leftTime"] = 0 else: info[k]["leftTime"] = max( piggyBankData.get(GameData.pb_getMoneyTS, 0) - ts, 0) info[k]["buyType"] = v.get("buyType") info[k]["other_buy_type"] = v.get("otherBuyType", {}) info[k]["otherProductInfo"] = store.getOtherBuyProduct( v.get("otherBuyType", {}), v.get("buyType")) if resetTime != -1: info[k]["resetTime"] = resetTime mo = MsgPack() mo.setCmd("piggyBankInfo") mo.setResult("gameId", config.FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("bankInfo", info) router.sendToUser(mo, userId) ftlog.debug("piggy_bank, userId =", userId, "vip =", vipLevel, "info =", info)
def getMoney(userId, clientId, productId): """ 取钱 """ key = UserData.piggyBankData % (FISH_GAMEID, userId) vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) conf = config.getPiggyBankProduct(clientId, productId) type = conf.get("type") iscooling = conf.get("iscooling", 0) ts = int(time.time()) / 60 * 60 endcoolingTS = 0 if iscooling: endcoolingTime = conf.get("endcoolingTime", 0) endcoolingTS = util.getDayStartTimestamp(ts) + endcoolingTime * 60 * 60 if ts >= endcoolingTS: endcoolingTS += 86400 piggyBankData = daobase.executeUserCmd(userId, "HGET", key, type) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} code = 4 totalMoney = 0 getMoneyCount = 0 rewards = [] if piggyBankData.get( GameData.pb_enable, 0) == 1 and piggyBankData.get(GameData.pb_getMoneyTS, 0) <= ts: code = 0 resetTime = _getResetTime(conf.get("resetTime", -1)) _resetKey = _getDataKey( ts, resetTime) # str(util.getDayStartTimestamp(ts)) if resetTime == -1: totalMoney = int(piggyBankData.get(GameData.pb_moneyCount, 0)) else: totalMoney = int( piggyBankData.get(GameData.pb_moneyCountDict, {}).get(_resetKey, 0)) getMoneyCount = min(totalMoney, conf.get("maxCount", 0)) if getMoneyCount > 0: piggyBankData[GameData.pb_savedMoneyCount].setdefault(_resetKey, 0) piggyBankData[GameData.pb_savedMoneyCount][_resetKey] = 0 # piggyBankData[GameData.pb_moneyCount] -= getMoneyCount if type == "free": piggyBankData[ GameData. pb_getMoneyTS] = ts + FREE_PIGGY_BANK_COOLDOWN_INTERVAL else: if iscooling: piggyBankData[GameData.pb_endcoolingTS] = endcoolingTS piggyBankData[GameData.pb_getMoneyTS] = piggyBankData[ GameData.pb_endcoolingTS] else: piggyBankData[GameData.pb_getMoneyTS] = 0 piggyBankData[GameData.pb_enable] = 0 piggyBankData[GameData.pb_saveMoneyTS] = ts conf = config.getPiggyBankConf(clientId, vipLevel).get(type, {}) if resetTime == -1: piggyBankData[GameData.pb_moneyCount] = conf.get("initVal", 0) else: piggyBankData.setdefault(GameData.pb_moneyCountDict, {}) piggyBankData[ GameData.pb_moneyCountDict][_resetKey] = conf.get( "initVal", 0) piggyBankData[GameData.pb_moneyCount] = piggyBankData[ GameData.pb_moneyCountDict][_resetKey] daobase.executeUserCmd(userId, "HSET", key, type, json.dumps(piggyBankData)) rewards = [{"name": config.CHIP_KINDID, "count": getMoneyCount}] util.addRewards(userId, rewards, "BI_NFISH_GET_PIGGY_BANK", vipLevel) ftlog.debug("piggy_bank, userId =", userId, "type =", type, "totalMoney =", totalMoney, "getMoneyCount =", getMoneyCount, "code =", code, "piggyBankData =", piggyBankData, util.timestampToStr(ts)) return code, rewards
def executeUserCmdWrapper(*cmds): daobase.executeUserCmd(int(userId), *cmds)
def saveStatusData(gameId, userId, actId, data): daobase.executeUserCmd(userId, 'hset', 'act:%s:%s' % (gameId, userId), actId, data)
def sendAllRecordToUser(cls, userId, gameId): """全量下发 """ gameDataKey = cls._getUserRecordKey(userId, gameId) replayDBKey = 'replay:%s' % (gameId) if daobase.executeUserCmd(userId, 'HEXISTS', gameDataKey, 'game_record'): gameRecord = daobase.executeUserCmd(userId, 'HGET', gameDataKey, 'game_record') ftlog.debug("sendAllRecordToUser.gameRecord = ", gameRecord) recordData = json.loads(gameRecord) if len(recordData['recordIndex']) > 0: records = [] for temp in recordData['recordIndex']: record = daobase.executeRePlayCmd('HGET', replayDBKey, temp) if record: records.append(record) ftlog.debug("sendAllRecordToUser.records = ", records) if isinstance(records, list) and len(records) > 0: msg = MsgPack() msg.setCmd('create_table') msg.setResult('action', 'record') msg.setResult('type', 'update') msg.setResult('gameId', gameId) retList = [] for recordStr in records: if not recordStr: continue try: ftlog.debug("sendAllRecordToUsersetRetData1") record = json.loads(recordStr) defaultScore = record.get('defaultScore', 0) urls = record.get('recordUrls', []) retData = {} retData['recordTime'] = record.get('time', 0) retData['createTableNo'] = record['tableNo'] # 客户端牌局回放key retData['tableRecordKey'] = '%s.%s' % (record.get( 'createTime', 0), retData['createTableNo']) retData['record_download_info'] = [] retData['users'] = [] ftlog.debug("sendAllRecordToUsersetRetData2") for uid, info in record['budget'].items(): deltaScoreList = info.get('deltaScoreList', 0) score = info.get('score', []) if isinstance(score, int): score = [] retData['users'].append({ 'name': info['name'], 'score': score, 'userId': info['uid'], 'deltaScore': deltaScoreList }) # 胜负结果字段 if int(uid) == userId: if deltaScoreList > 0: retData['winScore'] = 1 elif deltaScoreList == 0: retData['winScore'] = 0 elif deltaScoreList < 0: retData['winScore'] = -1 else: retData['winScore'] = 0 if int(uid) == userId: retData['deltaScore'] = 0 - defaultScore for i in range(len(urls)): record_download_info_obj = {} record_download_info_obj['url'] = '%s' % ( urls[i]) record_download_info_obj['fileType'] = '' record_download_info_obj[ 'MD5'] = md5digest( record_download_info_obj['url'] ).upper() retData['record_download_info'].append( record_download_info_obj) ftlog.debug("sendAllRecordToUsersetRetData3", retData) retList.append(retData) except: ftlog.error('==sendAllRecordToUser ===', records, ' keys:', recordData['recordIndex']) msg.setResult('list', retList) router.sendToUser(msg, userId) else: return
def loadStatusData(gameId, userId, actId): return daobase.executeUserCmd(userId, 'hget', 'act:%s:%s' % (gameId, userId), actId)
def exchange(self, userId): if not self.checkActivityActive(): if ftlog.is_debug(): ftlog.debug('christmas.exchange.checkActive.failed. userId=', userId) return u"不在活动时间内" assetList = None collectList = self.getUserCollectList(userId) timestamp = pktimestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(userId) collectCountList = [] for items in collectList: if items[1] and items[2]: collectCountList.append(int(items[1] / items[2])) else: collectCountList.append(0) collectCount = min(collectCountList) if collectCount: for item in collectList: itemId = item[0] consumeSockCount = item[2] * collectCount _, consumeCount, final = userAssets.consumeAsset(DIZHU_GAMEID, itemId, consumeSockCount, timestamp, 'DIZHU_ACT_CHRISTMAS_EXCHANGE', 0) if ftlog.is_debug(): ftlog.debug('christmas.exchange.warning userId=', userId, 'consumeCount=', consumeCount, 'collectCount=', collectCount, 'finalCount=', final, 'collectList=', collectList) collectTimes = daobase.executeUserCmd(userId, 'HINCRBY', 'act:christmas:6:' + str(userId), 'reward', collectCount) # 根据VIP等级发奖励 userRewards = self.getUserRewardByVip(userId) if not userRewards: ftlog.warn('christmas.exchange.warning.rewardError', 'userId=', userId, 'reward=', userRewards) return u"" if ftlog.is_debug(): ftlog.debug('christmas.exchange', 'userId=', userId, 'userRewards=', userRewards, 'userRewardsId=', id(userRewards)) contentItems = [] for rewardItem in userRewards: contentItems.append(TYContentItem(rewardItem['itemId'], int(rewardItem['count'] * collectCount))) assetList = dizhu_util.sendRewardItems(userId, contentItems, self._mail, 'DIZHU_ACT_CHRISTMAS_REWARD', 0) ftlog.info('gainChristmasFinalReward userId=', userId, 'collectTimes=', collectTimes, 'rewards=', [(atp[0].kindId, atp[1]) for atp in assetList]) if ftlog.is_debug(): ftlog.debug('christmas.exchange.info userId=', userId, 'collectCount=', collectCount, 'collectList=', collectList, 'assetList=', [(atp[0].kindId, atp[1]) for atp in assetList] if assetList else None) return u""
def load(cls, userId, key): rpath = 'erdayi:6:' + str(userId) d = daobase.executeUserCmd(userId, 'hget', rpath, key) if d: return strutil.loads(d) return d
def hasReward(userId): return daobase.executeUserCmd(userId, 'hget', 'rpmain:%s:%s' % (HALL_GAMEID, userId), 'gainReward') is None
def addMoneyToPiggyBank(userId, clientId, type, addCount, ts=None): """ 向存钱罐加钱 """ isFire = (ts is None) vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) piggyBankconf = config.getPiggyBankConf(clientId, vipLevel) conf = piggyBankconf.get(type, {}) curtime = int(time.time()) key = UserData.piggyBankData % (FISH_GAMEID, userId) # 初始化存档. _initSaveLoad(userId, clientId) piggyBankData = daobase.executeUserCmd(userId, "HGET", key, type) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} # if piggyBankData.get(GameData.pb_enable, 0) and conf: if conf: resetTime = _getResetTime(conf.get("resetTime", -1)) if ts: piggyBankData[GameData.pb_saveMoneyTS] = ts else: ts = int(time.time()) resetKey = _getDataKey(ts, resetTime) # str(util.getDayStartTimestamp(ts)) if resetTime != -1: piggyBankData.setdefault(GameData.pb_moneyCountDict, {}) piggyBankData[GameData.pb_moneyCountDict].setdefault( resetKey, conf.get("initVal", 0)) piggyBankData[GameData.pb_moneyCount] = piggyBankData[ GameData.pb_moneyCountDict][resetKey] # 开火消耗等在冷却开启时未达到冷却结束时不累积存钱罐.时间累积在计算的地方处理. if isFire and conf.get("iscooling", 0) and curtime <= piggyBankData.get( GameData.pb_endcoolingTS, 0): daobase.executeUserCmd(userId, "HSET", key, type, json.dumps(piggyBankData)) ftlog.debug("piggy_bank, userId =", userId, "is cooling !") return if addCount > 0: if resetTime == -1: totalMoney = int(piggyBankData.get(GameData.pb_moneyCount, 0)) else: totalMoney = int( piggyBankData.get(GameData.pb_moneyCountDict, {}).get(resetKey, 0)) dailyMoney = piggyBankData[GameData.pb_savedMoneyCount].setdefault( resetKey, 0) if totalMoney < conf.get("maxCount", 0): if conf.get("maxDailyCount", 0) > 0: if dailyMoney < conf["maxDailyCount"]: realAddMoney = min(addCount, conf["maxDailyCount"] - dailyMoney) else: realAddMoney = 0 else: realAddMoney = addCount realAddMoney = min(realAddMoney, conf["maxCount"] - totalMoney) if realAddMoney > 0: if resetTime == -1: piggyBankData[GameData.pb_moneyCount] += realAddMoney else: piggyBankData[GameData.pb_moneyCountDict][ resetKey] += realAddMoney piggyBankData[GameData.pb_moneyCount] = piggyBankData[ GameData.pb_moneyCountDict][resetKey] piggyBankData[ GameData.pb_savedMoneyCount][resetKey] += realAddMoney ftlog.debug("piggy_bank, userId =", userId, "type =", type, "vip =", vipLevel, "realAddMoney =", realAddMoney, "addCount =", addCount, "piggyBankData =", piggyBankData) daobase.executeUserCmd(userId, "HSET", key, type, json.dumps(piggyBankData))