def getPlayGameInfoByKey(self, userId, clientId, keyName): if keyName == TYGame.PLAY_COUNT: countStr = gamedata.getGameAttr(userId, GAMEID, 'play_game_count') if not countStr: return 0 return int(countStr) elif keyName == TYGame.WIN_COUNT: winStr = gamedata.getGameAttr(userId, GAMEID, 'win_game_count') if not winStr: return 0 return int(winStr) return None
def saveTableRecord(cls, tableRecordInfo, gameId): #add by taoxc ftlog.debug('createTableRecord.saveTableRecord tableRecordInfo:', tableRecordInfo, 'gameId:', gameId) #保存用户数据 for userId, playerRecordInfo in tableRecordInfo.items(): recordKey = cls._getTableRecordKey(gameId, userId) ftlog.debug('createTableRecord.saveTableRecord recordKey:', recordKey) #通过recordKey获取当前玩家的战绩记录数据,如果超过最大存储则进行删除处理(同时删除对应的内容) userRecordKeys = gamedata.getGameAttr(userId, gameId, recordKey) if not userRecordKeys: userRecordKeys = [] ftlog.debug('createTableRecord.saveTableRecord recordKey content is null') else: userRecordKeys = json.loads(userRecordKeys) ftlog.debug('createTableRecord.saveTableRecord recordKey content:', userRecordKeys) if len(userRecordKeys) >= cls._user_record_count: #删除最早的记录(附带删除内容) lastestKey = userRecordKeys.pop(0) daobase.executeRePlayCmd('DEL', lastestKey) ftlog.debug('createTableRecord.saveTableRecord recordKey len > ', cls._user_record_count, ' delete key:', lastestKey) recordContentKey = cls._getTableRecordContentKey(gameId, userId) userRecordKeys.append(recordContentKey) #保存KEY gamedata.setGameAttr(userId, gameId, recordKey, json.dumps(userRecordKeys)) #保存内容 daobase.executeRePlayCmd('SET', recordContentKey, json.dumps(playerRecordInfo)) ftlog.debug('createTableRecord.saveTableRecord save keys:', userRecordKeys, ' save content:', playerRecordInfo)
def getFriendList(cls, gameId, userId, clientId, prize): result = [] friendlist = gamedata.getGameAttr(userId, gameId, cls.attrname_invitedfriendlist) or "[]" friendlist = json.loads(friendlist) for i in range(len(friendlist)): result.append(cls.friendInfo(friendlist[i], prize, i, clientId)) return result
def addfriend(cls, userId, friendId, gameId, prize, numlimit): ''' rpc ''' if not cls.friendNumLimit(userId, gameId, numlimit): return -1 friend = {'userId': friendId, 'state': 0} friendlist = gamedata.getGameAttr(userId, gameId, cls.attrname_invitedfriendlist) if not friendlist: friendlist = [] else: friendlist = json.loads(friendlist) existed = False for f in friendlist: if f['userId'] == friendId: existed = True break if existed: return -1 else: friendlist.append(friend) gamedata.setGameAttr(userId, gameId, cls.attrname_invitedfriendlist, json.dumps(friendlist)) gamedata.incrGameAttr(userId, gameId, cls.attrname_failchip, prize["CHIP"]) gamedata.incrGameAttr(userId, gameId, cls.attrname_invitedfriendnum, 1) friendnum = len(friendlist) if friendnum % 5 == 0: gamedata.incrGameAttr(userId, gameId, cls.attrname_failcoupon, prize["COUPON"]) return friendnum
def getFriendListPrize(cls, userId, friendId, gameId): ''' rpc ''' friendlist = gamedata.getGameAttr(userId, gameId, cls.attrname_invitedfriendlist) if not friendlist: return [0, 0] friendlist = json.loads(friendlist) chipget = 0 couponget = 0 index = 0 if friendId == -1: for i in friendlist: index += 1 if i['state'] == 0: chipget += 1 i['state'] = 1 if index % 5 == 0: couponget += 1 else: for i in friendlist: index += 1 if i['userId'] == friendId and i['state'] == 0: chipget += 1 i['state'] = 1 if index % 5 == 0: couponget += 1 gamedata.setGameAttr(userId, gameId, cls.attrname_invitedfriendlist, json.dumps(friendlist)) return [chipget, couponget]
def doOldUserGetPrize(cls, gameId, userId, friendId, clientId, action): ''' 老用户领奖接口 ''' conf = hallconf.getNeiTuiGuangConf(clientId) if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo = MsgPack() mpush = None userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state) bindmobile = userdata.getAttr(userId, 'bindMobile') if userstate == 2: if cls.bindOk(bindmobile): prizeGet = cls.sendOldUserPrize(userId, friendId, gameId, conf) NeiTuiGuangProtocolBuilder.buildOldUserPrize(0, action, cls.getprize(gameId, 0, prizeGet), friendId, mo) ##### 推一条用户奖励信息 mpush = cls.doQueryPrize(gameId, userId, clientId, action) else: NeiTuiGuangProtocolBuilder.buildBindPrize(1, action, cls.getprize(gameId, 2), friendId, mo) else: NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, 'user state error: not support', mo) return mo, mpush
def doPromoteCodeCheck(cls, gameId, userId, clientId, action, promoteCode): ''' 验证兑换码ID,有效则获取用户手机绑定信息,若绑定手机,则发送奖励,并更新用户状态。若未绑定手机,则更新用户状态,返回未绑定手机code ''' conf = hallconf.getNeiTuiGuangConf(clientId) if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo = MsgPack() userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state) if userstate == 2: NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '已经领奖成功', mo) else: promoteCode = cls.intPromoteCode(promoteCode) if promoteCode == -1 or userId == promoteCode: NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo) else: userdata.checkUserData(promoteCode) createTime = userdata.getAttr(promoteCode, 'createTime') if createTime == None: NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo) else: olduser = cls.isOldUser(promoteCode, gameId, createTime, conf) if not olduser: NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo) else: gamedata.setGameAttr(userId, gameId, cls.attrname_promotecode, promoteCode) # 记录兑换码 gamedata.setGameAttr(userId, gameId, cls.attrname_state, 1) # 已输入兑换码 bindmobile = userdata.getAttr(userId, 'bindMobile') if cls.bindOk(bindmobile): NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '验证成功', mo) else: NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, cls.getprize(gameId, 2, conf), mo) return mo
def on_get_friends_rank(cls, gameid, mo): friend_list = mo.getResult('data') for friend in friend_list: # 填充历史获赞次数 uid = int(friend['uid']) num = gamedata.getGameAttr(uid, gameid, 'history_praised_num') friend['history_praised_num'] = num if num else 0
def sendBenefits(self, gameId, userId, timestamp=None): ''' 发放救济金 @return: isSend(True/False), TYUserBenefits ''' if timestamp is None: timestamp = pktimestamp.getCurrentTimestamp() chip = pkuserchip.getUserChipAll(userId) if chip < self._minChip: # 用户金币低于指定数目时,发放救济金 userBenefits = self.loadUserBenefits(gameId, userId, timestamp) if not userBenefits.hasLeftTimes(): # 没有剩余次数,弹分享引导 oldtime = gamedata.getGameAttr(userId, HALL_GAMEID, 'relief_share_date') if not oldtime or datetime.fromtimestamp(oldtime).date() < datetime.fromtimestamp(timestamp).date(): # 每天最多弹一次 gamedata.setGameAttr(userId, HALL_GAMEID, 'relief_share_date', timestamp) shareId = hallshare.getShareId('Relieffund', userId, gameId) share = hallshare.findShare(shareId) if share: task = share.buildTodotask(gameId, userId, 'Relieffund') TodoTaskHelper.sendTodoTask(gameId, userId, task) return False, userBenefits # 发放救济金 userBenefits.times += 1 self._benefitsDao.saveUserBenefitsData(userId, TYUserBenefitsData(userBenefits.times, timestamp)) self._sendBenefits(gameId, userBenefits) # 通知用户金币刷新 datachangenotify.sendDataChangeNotify(gameId, userId, ['udata']) return True, userBenefits return False, self.loadUserBenefits(gameId, userId, timestamp)
def getUData(self, userId): if userId not in self.udatas: udata = userdata.getAttrs(userId, ['name', 'purl']) photo = gamedata.getGameAttr(userId, self.gameId, 'photo') udata.append(photo) self.udatas[userId] = udata return udata return self.udatas[userId]
def countGame(self): for player in DiFangPlayersHelper.getPlayingPlayers(self): userId = player.userId # play_game_count playGameCount = gamedata.getGameAttr(userId, self.gameId, 'play_game_count') if not playGameCount: playGameCount = 0 playGameCount += 1 gamedata.setGameAttr(userId, self.gameId, 'play_game_count', playGameCount) ftlog.info("countGame userId=", userId, "play_game_count=", playGameCount) # win_game_count if self.gamePlay.pot.allwinchips[player.seatIndex] > 0: winGameCount = gamedata.getGameAttr(userId, self.gameId, 'win_game_count') if not winGameCount: winGameCount = 0 winGameCount += 1 gamedata.setGameAttr(userId, self.gameId, 'win_game_count', winGameCount) ftlog.info("countGame userId=", userId, "win_game_count=", winGameCount)
def _loadFiveStarRate(userId, channel): try: field = 'fivestar.%s' % (channel['name']) jstr = gamedata.getGameAttr(userId, HALL_GAMEID, field) if jstr: d = json.loads(jstr) return FiveStarRate(channel, d.get('ver', 0), d.get('rateTime'), d.get('popTime')) except: ftlog.error() return FiveStarRate(channel, 0, -1, -1)
def _checkUserLastSelectedCustomRoomConfVer(self, userId, gameId): confVer = difangConf.getCustomRoomConf(gameId, 'ver') userLastSelectedCustomRoomConfVer = gamedata.getGameAttr(userId, gameId, "customConfVer") if ftlog.is_debug(): ftlog.debug("|userId, gameId, confVer, userLastSelectedCustomRoomConfVer:", userId, gameId, confVer, userLastSelectedCustomRoomConfVer, caller=self) if userLastSelectedCustomRoomConfVer and confVer != userLastSelectedCustomRoomConfVer: return False return True
def isNewUser(userId, gameId): # 区别新老玩家 isToday = False createTime = gamedata.getGameAttr(userId, gameId, 'createTime') if not createTime: return isToday else: isToday = date.fromtimestamp(int(createTime)) == date.today() return isToday
def _doExchange(self, userId, gameId, clientId, activityId, excode): if len(excode) != 16 and len(excode) != 5 and len(excode) != 18: self.sendTodoTask(gameId, userId, "兑换码错误!") return {"exchangeInfo": "兑换码错误!"} if len(excode) == 5: rdskey = activityId else: excode = excode.upper() rdskey = excode[0:6] ftlog.debug('this exchange rdskey = ', rdskey, 'this exchange clientId = ', clientId) result_, errdes_, unique_ = self.__commonCheck(rdskey, clientId) if result_ != 0: self.sendTodoTask(gameId, userId, errdes_) return {"exchangeInfo": errdes_} result_, errdes_ = self.__exchange(rdskey, userId, excode, unique_) if result_ != 0: self.sendTodoTask(gameId, userId, errdes_) return {"exchangeInfo": errdes_} _rewards = self.__getReward(rdskey, userId, gameId, activityId, excode) if len(excode) == 18: # 将用户Id和推广人Id进行绑定 common_ = daobase.executeMixCmd('HGET', 'excodeinfo:' + rdskey, 'common') try: common_ = json.loads(common_) except: return {} nowPromoteId = pkgamedata.getGameAttr(userId, gameId, 'promoteId') or 0 ftlog.debug('__getReward.userId=', userId, 'gameId=', gameId, 'common_=', common_, 'nowPromoteId=', nowPromoteId) if int(nowPromoteId) <= 0 and int(userId) != int(common_.get('promoteId', 0)): pkgamedata.setGameAttr(userId, gameId, 'promoteId', common_.get('promoteId', 0)) resultInfo = '恭喜您兑换成功,获得:' + _rewards self.sendTodoTask(gameId, userId, resultInfo) # 兑换码使用成功,记录在用户里 messageUser = daobase.executeMixCmd('HGET', 'userID:' + str(userId), 'common') if isinstance(messageUser, (str, unicode)): messageUser = json.loads(messageUser) else: messageUser = {} if 'excode' not in messageUser: messageUser = { 'userId': userId, 'excode': [excode], 'time': [datetime.now().strftime('%Y-%m-%d %H:%M:%S')] } else: messageUser['excode'].append(excode) messageUser['time'].append(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) daobase.executeMixCmd('HSET', 'userID:' + str(userId), 'common', json.dumps(messageUser)) return {"exchangeInfo": resultInfo}
def sendBothUserPrize(cls, gameId, userId, userstate, conf): # 用户状态是否正确 => 是否绑定手机状态 => 发奖 result = cls.userStateRoute(gameId, userId, userstate, cls.attrname_state) if result != 0: return result else: friendId = gamedata.getGameAttr(userId, gameId, cls.attrname_promotecode) numlimit = conf.get('friendNum', 20) if cls.friendNumLimit(friendId, gameId, numlimit): return cls.sendBothUserPrize2(gameId, userId, friendId, conf) else: return cls.sendSingleUserPrize2(gameId, userId)
def createGameData(userId, clientId, gameId): """ 创建玩家的游戏数据 """ ftlog.debug('userId =', userId, 'clientId =', clientId) inviteState = gamedata.getGameAttr(userId, gameId, 'invite_state') bFilterInvite = False if inviteState > 0: bFilterInvite = True gdkeys = getInitDataKeys(bFilterInvite) ftlog.debug('createGameData userId =', userId, 'gdkeys =', gdkeys) gvals = getInitDataValues(bFilterInvite) gamedata.setGameAttrs(userId, gameId, gdkeys, gvals) return gdkeys, gvals
def saveCustomTableRecordInfos(self, table): '''将房间所有牌局记录索引存入redis ''' if table.gamePlay.gameSeq == 0: return playerInfos = [] for player in DiFangPlayersHelper.getSitPlayers(table): playerInfo = {} playerInfo['userId'] = player.userId playerInfo['name'] = player.name playerInfo['tableChips'] = player.tableChips playerInfos.append(playerInfo) if ftlog.is_debug(): ftlog.debug("playerInfos:", playerInfos, caller=self) record = {} record["ftId"] = table.ftId record["gameSeq"] = table.gamePlay.gameSeq record['tableRecordInfos'] = table.tableRecordInfos record['playerInfos'] = playerInfos # timestamp = pktimestamp.getCurrentTimestamp() # record['time'] = pktimestamp.timestamp2timeStr(timestamp) # 使用的UTC时区 record['time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") for player in DiFangPlayersHelper.getSitPlayers(table): if player.tableChips > 0: record["res"] = "win" elif player.tableChips == 0: record["res"] = "drawn" else: record["res"] = "lose" if ftlog.is_debug(): ftlog.debug("|tableId, userId, record:", table.tableId, player.userId, record, caller=self) records = gamedata.getGameAttr(player.userId, table.gameId, "customTableRecords") if records: records = json.loads(records) else: records = [] records.insert(0, record) if len(records) > 10: del records[-1] if ftlog.is_debug(): ftlog.debug("|tableId, userId, records:", table.tableId, player.userId, records, caller=self) gamedata.setGameAttr(player.userId, table.gameId, "customTableRecords", json.dumps(records))
def GetData(user_id, key, defaultValue=None, initWithDefaultValue=True): """ 获取指定的用户数据 """ ret = gamedata.getGameAttr(user_id, __GAME_ID, key) if ret is None: if defaultValue is None: return None else: if initWithDefaultValue: SetData(user_id, key, defaultValue) return defaultValue else: return ret
def loadRecord(cls, gameId, userId, matchId): try: jstr = gamedata.getGameAttr(userId, gameId, cls.__buildField(matchId)) if ftlog.is_debug(): ftlog.debug('MatchRecord.loadRecord gameId=', gameId, 'userId=', userId, 'matchId=', matchId, 'data=', jstr, caller=cls) if jstr: return MatchRecord.Record.fromDict(json.loads(jstr)) except: ftlog.exception() return None
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 doGetUserState(cls, gameId, userId, clientId, action): ''' 获取用户信息,不存在则,验证用户状态,写入用户活动状态表,并返回用户状态 ''' conf = hallconf.getNeiTuiGuangConf(clientId) mo = MsgPack() if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo state = gamedata.getGameAttr(userId, gameId, cls.attrname_state) createTime = userdata.getAttr(userId, 'createTime') if state == None: state = cls.initUserState(userId, gameId, createTime, conf) userdata.setAttr(userId, cls.attrname_state, state) inviteetip = cls.inviteeTip(userId, gameId, createTime, conf) else: if cls.isOldUser(userId, gameId, createTime, conf): state = 2 userdata.setAttr(userId, cls.attrname_state, state) # 老用户状态 if state == 0: NeiTuiGuangProtocolBuilder.buildNewUserState(gameId, userId, action, state, inviteetip, mo) elif state == 1: bindmobile = userdata.getAttr(userId, 'bindMobile') bindok = cls.bindOk(bindmobile) NeiTuiGuangProtocolBuilder.buildBindUserState(gameId, userId, action, state, bindok, mo) elif state == 2: bindmobile = userdata.getAttr(userId, 'bindMobile') bindok = cls.bindOk(bindmobile) shareId = conf.get('shareId', -1) prizeinfo = conf.get('prize_info', []) weixintip = cls.getWeiXinTip(userId, conf) url = cls.getDownUrl(userId, conf) smstip = cls.getSMSTip(gameId, userId, conf) rules = conf.get('rules', []) NeiTuiGuangProtocolBuilder.buildOldUserState(gameId, userId, action, state, bindok, shareId, prizeinfo, weixintip, url, smstip, rules, mo) else: pass return mo
def dosendChipToUser(self, userId, gameId, clientId): # 添加绑定 nowBindPone = gamedata.getGameAttr(userId, gameId, 'bindReward1') if not nowBindPone or nowBindPone < 1: gamedata.setGameAttr(userId, gameId, 'bindReward1', 1) else: from poker.entity.biz.exceptions import TYBizException raise TYBizException(-1, '重复绑定') # 发金币 ftlog.info('cmd game action bindPhone userId =', userId) from poker.entity.dao import userchip, daoconst userchip.incrChip(userId, gameId, 10000, daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO, 'BIND_PHONE', 0, clientId) datachangenotify.sendDataChangeNotify(gameId, userId, 'chip') # 消息推送 from poker.entity.biz.message import message msg = '恭喜您绑定手机成功,赠送您10000金币' message.send(gameId, message.MESSAGE_TYPE_PRIVATE, userId, msg) # 更新小红点 datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) TGHall.getEventBus().publishEvent(UserBindPhoneEvent(userId, gameId))
def loadStatus(userId): ''' 加载用户推广状态 ''' status = None dStr = None try: dStr = gamedata.getGameAttr(userId, DIZHU_GAMEID, 'simple_invite') if ftlog.is_debug(): ftlog.debug('dizhu_invite.loadStatus userId=', userId, 'dStr=', dStr) if dStr: d = json.loads(dStr) status = SimpleInviteStatus(userId).fromDict(d) except: ftlog.error('dizhu_invite.loadStatus userId=', userId, 'dStr=', dStr) if not status: status = SimpleInviteStatus(userId) return status
def getSimpleInviteBigReward(userId): ''' 获取大奖 ''' conf = getSimpleInviteConf() if conf.get('switch'): conditon = conf.get('condition') cond = UserConditionRegister.decodeFromDict(conditon) retCheck = cond.check(DIZHU_GAMEID, userId, None, None) ftlog.debug('dizhu_invite.getSimpleInviteBigReward userId=', userId, 'retCheck=', retCheck, 'isInterventionUser='******'firstBigRewards') if not firstBigRewards: return conf.get('firstBigRewards') if conf.get('firstBigRewards') else {} if isInterventionUser(userId): return conf.get('interventionBigRewards') if conf.get('interventionBigRewards') else {} return dizhu_util.getItemByWeight(conf.get('bigRewards')) if conf.get('bigRewards') else {}
def getCustomRecords(self, gameId, msg): '''获取战绩 ''' if ftlog.is_debug(): ftlog.debug("<< |msg", msg, caller=self) userId = msg.getParam("userId") records = gamedata.getGameAttr(userId, gameId, "customTableRecords") if records: records = json.loads(records) else: records = [] for record_item in records: if not record_item.get("totalPlayNum"): record_item['totalPlayNum'] = "-" msgRes = MsgPack() msgRes.setCmd("game") msgRes.updateResult({"action": "get_custom_records"}) msgRes.setResult("records", records) router.sendToUser(msgRes, userId)
def loadStatus(userId): ''' 加载用户推广状态 麻将先于大厅做过邀请有礼,从麻将merge数据 ''' d = None status = None try: # 优先迁移跑胡子的配置 ftlog.debug('hall_simple_invite.loadStatus...') dStr = gamedata.getGameAttr(userId, HALL_GAMEID, 'simple_invite') if dStr: d = json.loads(dStr) status = NeituiguangSimpleStatus(userId).decodeFromDict(d) except: ftlog.error('invite.loadStatus userId=', userId, 'd=', d) if not status: status = NeituiguangSimpleStatus(userId) return status
def sendExpiredGunMsg(userId, mode): """ 返回火炮皮肤过期提示 """ ownGunSkinsKey = GameData.ownGunSkins # 最近一次已拥有的皮肤炮列表 gunSkinIdKey = GameData.gunSkinId if mode == CLASSIC_MODE else GameData.gunSkinId_m # 用户当前皮肤炮ID promptedGunSkinsKey = GameData.promptedGunSkins # 已发送了过期提示弹窗的皮肤炮 ownGuns = gamedata.getGameAttrJson(userId, FISH_GAMEID, ownGunSkinsKey, []) currentGunIds = getGunIds(userId, mode)[1:] # 玩家当前拥有的火炮ID clientId = util.getClientId(userId) allGunIds = config.getAllGunIds(clientId, mode) for idx in range(len(ownGuns) - 1, -1, -1): if ownGuns[idx] not in allGunIds: ownGuns.pop(idx) # 当前已过期的皮肤 = 最近一次已拥有皮肤炮 - 当前已拥有皮肤炮 expiredGuns = list(set(ownGuns) - set(currentGunIds)) if expiredGuns: gunId = gamedata.getGameAttr(userId, FISH_GAMEID, gunSkinIdKey) if gunId in expiredGuns: expiredGun = gunId else: expiredGun = expiredGuns[-1] gunIds1 = getGunIds(userId, CLASSIC_MODE)[1:] gunIds2 = getGunIds(userId, MULTIPLE_MODE)[1:] gunIds1.extend(gunIds2) gamedata.setGameAttr(userId, FISH_GAMEID, ownGunSkinsKey, json.dumps(list(set(gunIds1)))) promptedGuns = gamedata.getGameAttrJson(userId, FISH_GAMEID, promptedGunSkinsKey, []) if expiredGun not in promptedGuns: promptedGuns.append(expiredGun) gamedata.setGameAttr(userId, FISH_GAMEID, promptedGunSkinsKey, json.dumps(promptedGuns)) mo = MsgPack() mo.setCmd("expired_gun") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("gunId", expiredGun) mo.setResult("gameMode", mode) router.sendToUser(mo, userId)
def saveTableRecord(cls, tableRecordInfo, gameId): #add by taoxc ftlog.debug('createTableRecord.saveTableRecord tableRecordInfo:', tableRecordInfo, 'gameId:', gameId) #保存用户数据 for userId, playerRecordInfo in tableRecordInfo.items(): recordKey = cls._getTableRecordKey(gameId, userId) ftlog.debug('createTableRecord.saveTableRecord recordKey:', recordKey) #通过recordKey获取当前玩家的战绩记录数据,如果超过最大存储则进行删除处理(同时删除对应的内容) userRecordKeys = gamedata.getGameAttr(userId, gameId, recordKey) if not userRecordKeys: userRecordKeys = [] ftlog.debug( 'createTableRecord.saveTableRecord recordKey content is null' ) else: userRecordKeys = json.loads(userRecordKeys) ftlog.debug( 'createTableRecord.saveTableRecord recordKey content:', userRecordKeys) if len(userRecordKeys) >= cls._user_record_count: #删除最早的记录(附带删除内容) lastestKey = userRecordKeys.pop(0) daobase.executeRePlayCmd('DEL', lastestKey) ftlog.debug( 'createTableRecord.saveTableRecord recordKey len > ', cls._user_record_count, ' delete key:', lastestKey) recordContentKey = cls._getTableRecordContentKey(gameId, userId) userRecordKeys.append(recordContentKey) #保存KEY gamedata.setGameAttr(userId, gameId, recordKey, json.dumps(userRecordKeys)) #保存内容 daobase.executeRePlayCmd('SET', recordContentKey, json.dumps(playerRecordInfo)) ftlog.debug('createTableRecord.saveTableRecord save keys:', userRecordKeys, ' save content:', playerRecordInfo)
def deductionVipComplement(event): userId = event.userId ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|enter", userId, event.rmbs) if event.rmbs and event.rmbs > 0: gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement_msg', 0) vip_complement = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement") vip_complement_max = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement_max") vipL = getVipLevel(userId) vipKey = "vip_" + str(vipL) max = 0 if vipKey in vip_complement: max = vip_complement_max[vipKey] chargeDate = datetime.datetime.now().strftime('%Y-%m-%d') gamedata.setGameAttr(userId, HALL_GAMEID, 'chargeDate', chargeDate) vipcominfo = gamedata.getGameAttr(userId, HALL_GAMEID, 'vip_complement') ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|vipcominfo", userId, event.rmbs, vipcominfo) if vipcominfo: vipcominfo = json.loads(vipcominfo) vipcom = vipcominfo['vipcom'] if vipcom == 0: ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|vipcom|zero", userId, event.rmbs, vipcominfo) return vip_complement_deduction = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement_deduction", 10000) deduction = int(event.rmbs) * vip_complement_deduction delta = vipcom - deduction ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|vip_complement_deduction", userId, event.rmbs, vipcominfo, vip_complement_deduction, deduction, vipcom, delta) if delta < 0: delta = 0 gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement', json.dumps({'vipLevel': vipcominfo['vipLevel'], 'vipcom': int(delta)})) final = userchip.getChip(userId) bireport.reportGameEvent('HALL_VIPCOMPLEMENT', userId, event.gameId, 0, 0, 0, 0, 0, 0, [vipL, 0, deduction, int(max - delta), final], event.clientId, 0, 0) ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement", userId, event.rmbs, vipcominfo['vipLevel'], vipcom, delta)
def sendFishCheckinInfo(userId, continueWindow=0): """ 发送签到详情 :param continueWindow: 0:用户点击签到请求 1:客户端登录时自动请求 """ if util.isVersionLimit(userId): return checkinDay = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.checkinDay) isCheckin = weakdata.getDayFishData(userId, "isCheckin", 0) code = 1 if (continueWindow and isCheckin): code = 2 elif util.isFinishAllNewbieTask(userId): code = 0 if not isCheckin: if checkinDay == len(config.getCheckinConf()): checkinDay = 0 gamedata.setGameAttr(userId, FISH_GAMEID, GameData.checkinDay, checkinDay) module_tip.addModuleTipEvent(userId, "checkin", checkinDay) mo = MsgPack() mo.setCmd("fishCheckin") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("loginDays", gamedata.getGameAttr(userId, FISH_GAMEID, GameData.loginDays)) mo.setResult("day", checkinDay if isCheckin else checkinDay + 1) mo.setResult("checkin", isCheckin) rewards = [] for rewardConf in config.getCheckinConf().values(): if util.isChestRewardId(rewardConf["shareReward"]["name"]): rewards.append(rewardConf["shareReward"]) else: rewards.append(rewardConf["normalReward"]) mo.setResult("rewards", rewards) mo.setResult("continueWindow", continueWindow) mo.setResult("code", code) router.sendToUser(mo, userId)
def npw_notice(userId, gameId, clientId, loginsum, isdayfirst, daylogin, npws_data): ftlog.debug("npw_notice|enter", userId, gameId, clientId, loginsum, isdayfirst, daylogin, npws_data) npws = npws_data[0] data = npws_data[1] enable = data['enable'] condition = npws['condition'] if not enable or not checkConditionsTimes(userId, daylogin, npws): ftlog.debug("npw_notice|timesNotMatch", enable, userId, daylogin) return if condition['typeId'] == "user.cond.and": if not checkConditionsAND(userId, gameId, clientId, condition): ftlog.debug("npw_notice|user.cond.and", userId) return elif condition['typeId'] == "user.cond.or": if not checkConditionsOR(userId, gameId, clientId, condition): ftlog.debug("npw_notice|user.cond.or", userId) return # 查看noticereward buttonText = data['buttonText'] if "sub_action" in data: if "noticereward" in data["sub_action"]: info = gamedata.getGameAttr(userId, HALL_GAMEID, NPW_ + "noticereward") if info: info = json.loads(info) if not info or info != data["sub_action"]["noticereward"]: data['buttonText'] = "领 取" ftlog.debug("noticereward|buttonText", userId, info, data["sub_action"]["noticereward"]) ftlog.debug("noticereward|buttonText2", userId, data["buttonText"]) sendMsg2client(gameId, userId, "newpop_notice", data) gamedata.incrGameAttr(userId, HALL_GAMEID, NPW_ + NPW_NOTICE, 1) data['buttonText'] = buttonText
def sendUpdateRewards(userId, clientId): """ 发放更服奖励 """ conf = config.getUpdateVerRewardsConf() updateClientVer = conf.get("version") if updateClientVer is None: return clientVersion = gamedata.getGameAttr(userId, config.FISH_GAMEID, GameData.clientVersion) if clientVersion == updateClientVer: updateVerRewards = gamedata.getGameAttrJson(userId, config.FISH_GAMEID, GameData.updateVerRewards, []) if clientVersion not in updateVerRewards: updateVerRewards.append(clientVersion) gamedata.setGameAttr(userId, config.FISH_GAMEID, GameData.updateVerRewards, json.dumps(updateVerRewards)) rewardTye = conf.get("type", 1) vipLv = hallvip.userVipSystem.getUserVip(userId).vipLevel.level #message = conf.get("msg", "")# u"您的版本更新已完成,以下是更新奖励,祝您游戏愉快!" lang = util.getLanguage(userId, clientId) message = config.getMultiLangTextConf(conf.get("msg", ""), lang=lang) rewards = conf.get("rewards", {}).get(str(vipLv), {}).get(str(rewardTye), []) if rewards: mail_system.sendSystemMail( userId, mail_system.MailRewardType.SystemCompensate, rewards, message, config.getMultiLangTextConf( "ID_MAIL_VERSION_UPDATE_REWARDS", lang=lang)) if ftlog.is_debug(): ftlog.debug("sendUpdateRewards, userId =", userId, "vip =", vipLv, "type =", rewardTye, "rewards =", rewards, "updateVer =", updateClientVer, "updateVerRewards =", updateVerRewards)
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 doGetPrize(cls, gameId, userId, clientId, action): ''' 新用户领奖接口 ''' conf = hallconf.getNeiTuiGuangConf(clientId) if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo = MsgPack() bindmobile = userdata.getAttr(userId, 'bindMobile') userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state) if cls.bindOk(bindmobile): prizeGet = cls.sendBothUserPrize(gameId, userId, userstate, conf) if prizeGet == -1: # 用户状态错误 NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, "用户状态错误", mo) else: # 发送奖励成功 NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, cls.getprize(gameId, 0, conf, prizeGet), mo) else: # 未绑定手机 NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 2, conf), mo) return mo
def addfriend(cls, userId, friendId, gameId, prize, numlimit): ''' rpc ''' if not cls.friendNumLimit(userId, gameId, numlimit): return -1 friend = {'userId': friendId, 'state': 0} friendlist = gamedata.getGameAttr(userId, gameId, cls.attrname_invitedfriendlist) if not friendlist: friendlist = [] else: friendlist = json.loads(friendlist) existed = False for f in friendlist: if f['userId'] == friendId: existed = True break if existed: return -1 else: friendlist.append(friend) gamedata.setGameAttr(userId, gameId, cls.attrname_invitedfriendlist, json.dumps(friendlist)) gamedata.incrGameAttr(userId, gameId, cls.attrname_failchip, prize["CHIP"]) gamedata.incrGameAttr(userId, gameId, cls.attrname_invitedfriendnum, 1) friendnum = len(friendlist) if friendnum % 5 == 0: gamedata.incrGameAttr(userId, gameId, cls.attrname_failcoupon, prize["COUPON"]) return friendnum
def getDaShiFen(userId, clientId, gameId): """ 获取玩家大师分信息 """ master_point = gamedata.getGameAttr(userId, gameId, 'master_point') if not master_point: master_point = 0 master_point_level = 0 config = configure.get_medal_ui_config(gameId) title_pic, level_pic = '', '' if config: title_pic = config['title'] level_pic = config['level'] % master_point_level return { 'name': '麻将', 'skillscore': master_point, 'level': master_point_level, 'pic': level_pic, 'title': title_pic, 'des': '麻将房间中每次胜利都可获得雀神分,高倍数、高级房间、会员获得的更快!', 'score': master_point, 'grade': 1, 'premaxscore': 0, 'curmaxscore': 0, }
def getDaShiFen(userId, clientId, gameId): """ 获取玩家大师分信息 """ master_point = gamedata.getGameAttr(userId, gameId, 'master_point') if not master_point: master_point = 0 master_point_level = 0 config = configure.get_medal_ui_config(gameId) title_pic, level_pic = '', '' if config: title_pic = config['title'] level_pic = config['level'] % master_point_level return { 'name': '麻将', 'skillscore': master_point, 'level': master_point_level, 'pic': level_pic, 'title': title_pic, 'des': '麻将房间中每次胜利都可获得雀神分,高倍数、高级房间、会员获得的更快!', 'score': master_point, 'grade': 1, 'premaxscore': 0, 'curmaxscore': 0, }
def complementByVip(userId, gameId, clientId): if not checkChargeDate(userId): ftlog.info("complementByVip|charge|surpass|30days", userId) return vip_complement = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement") vip_complement_max = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement_max") vipL = getVipLevel(userId) vipKey = "vip_" + str(vipL) ftlog.info("complementByVip|enter", userId, gameId, vipL, vipKey, vip_complement, clientId) if vipKey in vip_complement: once = vip_complement[vipKey] max = vip_complement_max[vipKey] coin = userdata.getAttr(userId, 'chip') vipcominfo = gamedata.getGameAttr(userId, HALL_GAMEID, 'vip_complement') if not vipcominfo: vipcom = 0 else: vipcominfo = json.loads(vipcominfo) vipLevel = vipcominfo['vipLevel'] if vipL != vipLevel: vipcom = 0 ftlog.info("complementByVip|vip|up", userId, vipL, vipLevel) else: vipcom = vipcominfo['vipcom'] mostchip = max - vipcom ftlog.info("complementByVip|go", userId, gameId, clientId, once, max, coin, vipcom, mostchip, vipcominfo) if vipcom >= max: vip_complement_msg = gamedata.getGameAttr(userId, HALL_GAMEID, 'vip_complement_msg') if not vip_complement_msg: vip_complement_msg = 0 else: if int(vip_complement_msg) >= 3: return gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement_msg', int(vip_complement_msg) + 1) ftlog.info("complementByVip|reach|max", userId ,gameId, clientId, vipcom, max) msg = u"今日您的VIP金币补足权益已停止,充值可恢复权益,充值越多,额度越高。客服电话:4008-098-000" infoTodoTask = TodoTaskShowInfo(msg, True) TodoTaskHelper.sendTodoTask(gameId, userId, infoTodoTask) return if coin >= once: ftlog.info("complementByVip|once|is|ok", userId, coin, once) return else: delta = once - coin if delta > mostchip: delta = mostchip final = addChip(userId, gameId, clientId, delta) if final: gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement', json.dumps({'vipLevel': vipL, 'vipcom': vipcom + delta})) mail = "您当前是VIP%d,今日首次登录为您补足到%d金币"%(vipL, final) pkmessage.sendPrivate(9999, userId, 0, mail) bireport.reportGameEvent('HALL_VIPCOMPLEMENT', userId, gameId, 0, 0, 0, 0, 0, 0, [vipL, delta, -delta, max - vipcom - delta, final], clientId, 0, 0) ftlog.info("complementByVip|", userId, vipL, delta, final)
def friendNumLimit(cls, userId, gameId, numlimit): friendnum = gamedata.getGameAttr(userId, gameId, cls.attrname_invitedfriendnum) if friendnum >= numlimit: return False return True
def redis_readjson(userId, gameId, redisKey): data = gamedata.getGameAttr(userId, gameId, redisKey) ftlog.debug("redis_readjson: userId=", userId, "type:", type(data), "data=", data) if data == None: return {} return json.loads(data)
def loadData(self): jstr = gamedata.getGameAttr(self.userId, DIZHU_GAMEID, 'wxFollowCount') if jstr: jdict = strutil.loads(jstr) return self.decodeFromDict(jdict) return self
def transItemIfNeed(userId): userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() transFlag = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'flag.item.trans') # 如果还没转换过的不需要处理 if not transFlag: ftlog.info('hotfix_item.transItemIfNeed NotTrans1 userId=', userId, 'transFlag=', transFlag) return try: datas = pkgamedata.getAllAttrs(userId, HALL_GAMEID, 'item') ftlog.info('hotfixitem.transItemIfNeed userId=', userId, 'datas=', None if datas is None else [v for i, v in enumerate(datas) if i % 2 == 0]) # 读取用户所有老的道具,和新背包中的道具比较,如果新背包中没有则把老的加到新背包中 if datas: for i in xrange(len(datas) / 2): try: x = i * 2 # fid, utime 更新时间 count道具个数 state 状态 dataBytes = strutil.unicode2Ascii(datas[x + 1]) _fid, utime, count, _state = struct.unpack("3iB", dataBytes) timestamp = pktimestamp.getCurrentTimestamp() kindId = int(datas[x]) if kindId == 0: continue if kindId in __timingItems: now_day = datetime.now().date() uday = datetime.fromtimestamp(utime).date() count -= (now_day - uday).days if count <= 0: ftlog.info('hotfix_item.transItemIfNeed expires userId=', userId, 'kindId=', kindId, 'count=', count, 'utime=', datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')) continue itemKind = itemSystem.findItemKind(kindId) if not itemKind: ftlog.warn('hotfix_item.transItemIfNeed unknownKind userId=', userId, 'kindId=', kindId, 'count=', count, 'utime=', datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')) continue # 在背包中查找是否有老的道具,如果没有则加到背包中、 item = userBag.getItemByKind(itemKind) if not item and count > 0: ftlog.info('hotfix_item.transItemIfNeed transOk userId=', userId, 'kindId=', kindId, 'count=', count, 'utime=', datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')) userBag.addItemUnitsByKind(HALL_GAMEID, itemKind, count, timestamp, 0, "DATA_TRANSFER", 0) else: ftlog.info('hotfix_item.transItemIfNeed alreadyExists userId=', userId, 'kindId=', kindId, 'count=', count, 'utime=', datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')) except: ftlog.error('hotfix_item.transItemIfNeed exception0 userId=', userId) except: ftlog.error('hotfix_item.transItemIfNeed exception1 userId=', userId)
def upgradeSkill(userId, skillId, actionType): """ 技能激活/升级、升星 @return: 是否成功, 当前星级, 原始等级, 当前等级, 升级前的技能等级 """ code, skill = checkSkillStatus(userId, skillId) if code != 0: return code, 0, 0, 0, 0 previousLevel = skill[INDEX_ORIGINAL_LEVEL] if actionType == 0: # 升级 if skill[INDEX_ORIGINAL_LEVEL] >= MAX_ORIGINAL_LEVEL: return 6, 0, 0, 0, 0 skillGradeConf = config.getSkillGradeCommonConf( skillId, skill[INDEX_ORIGINAL_LEVEL] + 1) isOK = consumeUpgradeSkillItem(userId, skillGradeConf["consume"], skillId, skill[INDEX_ORIGINAL_LEVEL] + 1) if isOK: skill[INDEX_ORIGINAL_LEVEL] += 1 skill[INDEX_CURRENT_LEVEL] = skill[INDEX_ORIGINAL_LEVEL] # 激活技能时,技能等级和星级都为1;当技能槽有空位时,自动帮玩家装备该技能 if skill[INDEX_ORIGINAL_LEVEL] == 1: skill[INDEX_STAR_LEVEL] = 1 skillMode = gamedata.getGameAttr(userId, FISH_GAMEID, GameData.skillMode) idleOrder = getSkillIdleOrder(userId, skillMode) if idleOrder > 0: if skillMode == config.CLASSIC_MODE: skill[INDEX_STATE] = idleOrder else: skill[INDEX_STATE_M] = idleOrder setSkill(userId, skillId, skill) else: return 4, skill[INDEX_STAR_LEVEL], skill[ INDEX_ORIGINAL_LEVEL], skill[ INDEX_CURRENT_LEVEL], previousLevel else: # 升星 if skill[INDEX_STAR_LEVEL] == 0 or skill[ INDEX_STAR_LEVEL] >= MAX_STAR_LEVEL: return 6, 0, 0, 0, 0 skillStarConf = config.getSkillStarCommonConf( skillId, skill[INDEX_STAR_LEVEL] + 1) isOK = consumeUpgradeSkillItem(userId, skillStarConf["consume"], skillId, skill[INDEX_STAR_LEVEL] + 1) if isOK: skill[INDEX_STAR_LEVEL] += 1 setSkill(userId, skillId, skill) else: return 4, skill[INDEX_STAR_LEVEL], skill[ INDEX_ORIGINAL_LEVEL], skill[ INDEX_CURRENT_LEVEL], previousLevel upgradedSkill = getSkill(userId, skillId) if not upgradedSkill: ftlog.error("upgradeSkill-> getSkill error", userId, skillId) return 5, skill[INDEX_STAR_LEVEL], skill[INDEX_ORIGINAL_LEVEL], skill[ INDEX_CURRENT_LEVEL], previousLevel datachangenotify.sendDataChangeNotify(FISH_GAMEID, userId, "item") from newfish.game import TGFish from newfish.entity.event import SkillItemCountChangeEvent event = SkillItemCountChangeEvent(userId, FISH_GAMEID) TGFish.getEventBus().publishEvent(event) # 技能升级事件 from newfish.game import TGFish from newfish.entity.event import SkillLevelUpEvent event = SkillLevelUpEvent(userId, FISH_GAMEID, getSkillList(userId), actionType) TGFish.getEventBus().publishEvent(event) bireport.reportGameEvent( "BI_NFISH_GE_SKILL_UPGRADE", userId, FISH_GAMEID, 0, 0, skillId, 0, 0, 0, [upgradedSkill[INDEX_STAR_LEVEL], upgradedSkill[INDEX_ORIGINAL_LEVEL]], util.getClientId(userId)) return 0, upgradedSkill[INDEX_STAR_LEVEL], upgradedSkill[ INDEX_ORIGINAL_LEVEL], upgradedSkill[ INDEX_CURRENT_LEVEL], previousLevel
def handleEvent(cls, event): try: winlose = event.winlose if not winlose.isWin: # 失败不弹出 return if event.skillLevelUp: # 升段不弹出 return clientGiftVer = SessionDizhuVersion.getVersionNumber(event.userId) if clientGiftVer >= 3.824: # 新礼包过滤老礼包 from poker.entity.configure import gdata roomConf = gdata.getRoomConfigure(event.roomId) newTypeOfGift = roomConf.get('newTypeOfGift', 0) if roomConf else None if ftlog.is_debug(): ftlog.debug('ChargeLead handleEvent', 'roomId=', event.roomId, 'clientVer=', clientGiftVer, 'newTypeOfGift=', newTypeOfGift, 'roomConf=', roomConf, 'newTypeOfGift=', newTypeOfGift) if newTypeOfGift: return winstreak = gamedata.getGameAttr(event.userId, event.gameId, 'winstreak') or 0 # 纪录连胜日志, 方便以后线上查询 ftlog.debug('[<ChargeLead>UserTableWinloseEvent|isWin=True]Dizhu', 'gameId=', event.gameId, 'userId=', event.userId, 'roomId=', event.roomId, 'slam=', winlose.slam, 'chunTian=', winlose.chunTian, 'skillLevelUp=', event.skillLevelUp, 'mixConfRoomId=', event.mixConfRoomId, 'winstreak=', winstreak) clientId = sessiondata.getClientId(event.userId) _, clientVer, _ = strutil.parseClientId(clientId) # 当玩家取得3的倍数连胜时或达成春天、大满贯(及以上倍数)取胜时弹出高手礼包 if winstreak % 3 == 0 or winlose.slam or winlose.chunTian: if ftlog.is_debug(): ftlog.debug('ChargeLead.handleEvent gameId=', event.gameId, 'userId=', event.userId, 'roomId=', event.roomId, 'winstreak=', winstreak, 'mixConfRoomId=', event.mixConfRoomId, 'clientId=', clientId) if clientVer >= 3.7: todotask = hallpopwnd.makeTodoTaskWinBuy(event.gameId, event.userId, clientId, event.mixConfRoomId or event.roomId) if todotask: todotask.setParam('delay', 3) TodoTaskHelper.sendTodoTask(event.gameId, event.userId, todotask) else: product, _ = hallproductselector.selectWinleadProduct(event.gameId, event.userId, clientId, event.mixConfRoomId or event.roomId) if not product: ftlog.warn('ChargeLead.handleEvent NotFoundProduct gameId=', event.gameId, 'userId=', event.userId, 'roomId=', event.roomId, 'winstreak=', winstreak, 'mixConfRoomId=', event.mixConfRoomId, 'clientId=', clientId) return cls.sendChargeLeadToDoTask(event.gameId, event.userId, product) except: ftlog.exception()
def transItemIfNeed(userId): userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() transFlag = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'flag.item.trans') # 如果还没转换过的不需要处理 if not transFlag: ftlog.info('hotfix_item_add.transItemIfNeed NotTrans1 userId=', userId, 'transFlag=', transFlag) return try: datas = pkgamedata.getAllAttrs(userId, HALL_GAMEID, 'item') ftlog.info('hotfixitem.transItemIfNeed userId=', userId, 'datas=', None if datas is None else [v for i, v in enumerate(datas) if i % 2 == 0]) # 读取用户所有老的道具,和新背包中的道具比较,如果新背包中没有则把老的加到新背包中 if datas: for i in xrange(len(datas) / 2): try: x = i * 2 # fid, utime 更新时间 count道具个数 state 状态 dataBytes = strutil.unicode2Ascii(datas[x + 1]) _fid, utime, count, _state = struct.unpack("3iB", dataBytes) timestamp = pktimestamp.getCurrentTimestamp() kindId = int(datas[x]) if kindId == 0: continue if kindId in __timingItems: now_day = datetime.now().date() uday = datetime.fromtimestamp(utime).date() count -= (now_day - uday).days if count <= 0: ftlog.info('hotfix_item_add.transItemIfNeed expires userId=', userId, 'kindId=', kindId, 'count=', count, 'utime=', datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')) continue itemKind = itemSystem.findItemKind(kindId) if not itemKind: ftlog.warn('hotfix_item_add.transItemIfNeed unknownKind userId=', userId, 'kindId=', kindId, 'count=', count, 'utime=', datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')) continue # 在背包中查找是否有老的道具,如果没有则加到背包中、 item = userBag.getItemByKind(itemKind) alreadyCount = item.balance(timestamp) if item else 0 ftlog.info('hotfix_item_add.transItemIfNeed transOk userId=', userId, 'kindId=', kindId, 'count=', count, 'alreadyCount=', alreadyCount, 'utime=', datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')) userBag.addItemUnitsByKind(HALL_GAMEID, itemKind, count, timestamp, 0, "DATA_TRANSFER", 0) except: ftlog.error('hotfix_item_add.transItemIfNeed exception0 userId=', userId) except: ftlog.error('hotfix_item_add.transItemIfNeed exception1 userId=', userId)
def doBuyLevelGift(userId, clientId, buyType, productId, itemId=0): """ 购买升级礼包 """ levelGift = config.getLevelGiftConf() giftId = 0 for val in levelGift.values(): if val.get("productId") == productId: giftId = val["giftId"] break if giftId == 0: return levelGiftConf = levelGift.get(str(giftId), {}) commonRewards = [] if _isBought(userId, giftId): code = 1 elif buyType == config.BT_DIAMOND: price = levelGiftConf.get("discountPrice", 0) price, isSucc = store.getUseRebateItemPrice(userId, itemId, price, buyType, productId, clientId) code = 0 if price > 0: consumeCount = 0 if isSucc: # 用优惠券 store.autoConvertVoucherToDiamond(userId, price) consumeCount, final = userchip.incrDiamond(userId, FISH_GAMEID, -abs(price), 0, "BI_NFISH_BUY_LEVEL_GIFT_CONSUME", int(config.DIAMOND_KINDID), util.getClientId(userId), param01=productId) if not isSucc or abs(consumeCount) != price: code = 2 _sendBuyLevelGiftRet(userId, clientId, productId, code, commonRewards) return else: code = 4 else: code = 3 if code == 0: # 记录存档 boughtGift = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.buyLevelGift, []) boughtGift.append(int(giftId)) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.buyLevelGift, json.dumps(boughtGift)) # 升级炮倍率 gunLv = util.getGunLevelVal(userId, config.MULTIPLE_MODE) if gunLv < levelGiftConf["levelUp"]: gunLevel = gunLv for level in config.getGunLevelKeysConf(config.MULTIPLE_MODE): value = config.getGunLevelConf(level, config.MULTIPLE_MODE) if value["levelValue"] == levelGiftConf["levelUp"]: gunLevel = level break gamedata.setGameAttr(userId, FISH_GAMEID, GameData.gunLevel_m, gunLevel) from newfish.game import TGFish from newfish.entity.event import GunLevelUpEvent event = GunLevelUpEvent(userId, FISH_GAMEID, gamedata.getGameAttr(userId, FISH_GAMEID, GameData.level), gunLevel, config.MULTIPLE_MODE) TGFish.getEventBus().publishEvent(event) bireport.reportGameEvent("BI_NFISH_GE_LEVEL_UP", userId, FISH_GAMEID, 0, 0, 0, config.MULTIPLE_MODE, 0, 0, [gunLevel], util.getClientId(userId)) # 发奖励 rewards = levelGiftConf.get("rewards", []) # 资产/道具 code = util.addRewards(userId, rewards, "BI_NFISH_BUY_ITEM_GAIN", int(giftId), param01=int(giftId)) commonRewards.extend(rewards) _sendBuyLevelGiftRet(userId, clientId, productId, code, commonRewards) util.addProductBuyEvent(userId, productId, clientId)
def _getFriendGameInfo(userId, gameIds, for_level_info, for_winchip, for_online_info=1): uid = int(userId) datas = {} gid, rid, tid, sid = 0, 0, 0, 0 state = daoconst.OFFLINE if for_online_info: loclist = onlinedata.getOnlineLocList(uid) state = onlinedata.getOnlineState(uid) if len(loclist) > 0: _rid, _tid, _sid = loclist[0] # gid表示用户在哪个游戏中 gid = strutil.getGameIdFromInstanceRoomId(_rid) # 检查是否可加入游戏 if TYGame(gid).canJoinGame(userId, _rid, _tid, _sid): # rid/tid/sid表示用户所在的游戏是否可加入游戏 # 分享出来的都是可以加入游戏的牌桌信息 rid = _rid tid = _tid sid = _sid if ftlog.is_debug(): ftlog.debug('getFriendGameInfo userId:', userId, ' gameId:', gid, ' roomId:', _rid, ' tableId:', _tid, ' seatId:', _sid, ' can not join game....') if state == daoconst.OFFLINE: offline_time = gamedata.getGameAttr(uid, HALL_GAMEID, 'offlineTime') if not offline_time: # 取不到离线时间,取上线时间 offline_time = userdata.getAttr(uid, 'authorTime') if offline_time: offline_time = pktimestamp.parseTimeMs(offline_time) delta = datetime.now() - offline_time delta = delta.days * 24 * 60 + delta.seconds / 60 # 分钟数 else: # 异常情况 delta = 24 * 60 datas['offline_time'] = delta if delta > 0 else 1 if rid > 0: try: room = gdata.roomIdDefineMap().get(rid, None) if room: datas['room_name'] = room.configure['name'] except: ftlog.error() # 构造回传给SDK的游戏数据 datas.update({ 'uid': uid, 'gid': gid, 'rid': rid, 'tid': tid, 'sid': sid, 'state': state }) if for_level_info: datas['level_game_id'] = 0 datas['level'] = 0 datas['level_pic'] = '' try: for gameId in gameIds: if gameId not in gdata.games(): continue dashifen_info = gdata.games()[gameId].getDaShiFen(uid, '') if dashifen_info: level = dashifen_info['level'] if level > 0 and level > datas['level']: datas['level_game_id'] = gameId datas['level'] = level level_pic = dashifen_info.get('picbig') datas[ 'level_pic'] = level_pic if level_pic else dashifen_info.get( 'pic') except: ftlog.error() if for_winchip: datas['winchip'] = 0 datas['winchips'] = 0 try: for gameId in gameIds: winchips, todaychips = gamedata.getGameAttrs( userId, gameId, ['winchips', 'todaychips'], False) winchips = strutil.parseInts(winchips) yest_winchip = 0 todaychips = strutil.loads(todaychips, ignoreException=True) if todaychips and 'today' in todaychips and 'chips' in todaychips and 'last' in todaychips: if pktimestamp.formatTimeDayInt() == todaychips['today']: yest_winchip = todaychips['last'] elif pktimestamp.formatTimeYesterDayInt( ) == todaychips['today']: yest_winchip = todaychips['chips'] datas['winchip'] += yest_winchip datas['winchips'] += winchips except: ftlog.error() return datas
def getShareReward(gameId, userId, share, shareLoc, timestamp): ''' 给用户发放分享奖励 ''' # 分享BI日志汇报 clientId = sessiondata.getClientId(userId) bireport.reportGameEvent('SHARE_CALLBACK', userId, gameId, share.shareId, 0, 0, 0, 0, 0, [], clientId) # 记录分享次数 gamedata.incrGameAttr(userId, HALL_GAMEID, 'shareCount', 1) TGHall.getEventBus().publishEvent(HallShareEvent(gameId, userId, share.shareId, shareLoc)) # 首先处理 分享相关的通知 notifyInfoStr = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'shareInfo') newInfo = {} pkgamedata.setGameAttr(userId, HALL_GAMEID, 'shareInfo', json.dumps(newInfo)) if notifyInfoStr: notifyInfo = json.loads(notifyInfoStr) shareId = notifyInfo.get('shareId', 0) if shareId == share.shareId: # 通知 info = notifyInfo.get('info', '') module = notifyInfo.get('module', '') if module == hall_red_envelope.TYRedEnvelope.EVENTID: hall_red_envelope.TYRedEnvelopeMgr.changeRedEnvelopeState(info, hall_red_envelope.TYRedEnvelope.STATE_SHARED) from poker.entity.game.game import TYGame clientId = sessiondata.getClientId(userId) gameids = hallconf.getDaShiFenFilter(clientId) for gid in gameids: TYGame(gid).sendTuyooRedEnvelopeCallBack(userId, clientId, info) # 分享奖励 ok, rewardCount = incrRewardCount(userId, share, timestamp) if not ok: if ftlog.is_debug(): ftlog.debug('hallshare.getShareReward already no share, check update share promote ...') ftlog.debug('hallshare.getShareReward fail gameId=', gameId, 'userId=', userId, 'shareId=', share.shareId, 'shareLoc=', shareLoc, 'rewardCount=', rewardCount, 'maxRewardCount=', share.maxRewardCount) return False assetList = sendReward(gameId, userId, share, shareLoc) if assetList and share.mail: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain(share.mail)) ftlog.debug('hallshare.getShareReward ok gameId=', gameId, 'userId=', userId, 'shareId=', share.shareId, 'shareLoc=', shareLoc, 'rewardCount=', rewardCount, 'maxRewardCount=', share.maxRewardCount, 'reward=', [(at[0].kindId, at[1]) for at in assetList] if assetList else []) if share.mail: pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, share.mail) # udpate free & promotion_loc datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) return True
def getShareReward(gameId, userId, share, shareLoc, timestamp): ''' 给用户发放分享奖励 ''' # 分享BI日志汇报 clientId = sessiondata.getClientId(userId) bireport.reportGameEvent('SHARE_CALLBACK', userId, gameId, share.shareId, 0, 0, 0, 0, 0, [], clientId) # 记录分享次数 gamedata.incrGameAttr(userId, HALL_GAMEID, 'shareCount', 1) TGHall.getEventBus().publishEvent( HallShareEvent(gameId, userId, share.shareId, shareLoc)) # 首先处理 分享相关的通知 notifyInfoStr = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'shareInfo') newInfo = {} pkgamedata.setGameAttr(userId, HALL_GAMEID, 'shareInfo', json.dumps(newInfo)) if notifyInfoStr: notifyInfo = json.loads(notifyInfoStr) shareId = notifyInfo.get('shareId', 0) if shareId == share.shareId: # 通知 info = notifyInfo.get('info', '') module = notifyInfo.get('module', '') if module == hall_red_envelope.TYRedEnvelope.EVENTID: hall_red_envelope.TYRedEnvelopeMgr.changeRedEnvelopeState( info, hall_red_envelope.TYRedEnvelope.STATE_SHARED) from poker.entity.game.game import TYGame clientId = sessiondata.getClientId(userId) gameids = hallconf.getDaShiFenFilter(clientId) for gid in gameids: TYGame(gid).sendTuyooRedEnvelopeCallBack( userId, clientId, info) # 分享奖励 ok, rewardCount = incrRewardCount(userId, share, timestamp) if not ok: if ftlog.is_debug(): ftlog.debug( 'hallshare.getShareReward already no share, check update share promote ...' ) ftlog.debug('hallshare.getShareReward fail gameId=', gameId, 'userId=', userId, 'shareId=', share.shareId, 'shareLoc=', shareLoc, 'rewardCount=', rewardCount, 'maxRewardCount=', share.maxRewardCount) return False assetList = sendReward(gameId, userId, share, shareLoc) if assetList and share.mail: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain(share.mail)) ftlog.debug('hallshare.getShareReward ok gameId=', gameId, 'userId=', userId, 'shareId=', share.shareId, 'shareLoc=', shareLoc, 'rewardCount=', rewardCount, 'maxRewardCount=', share.maxRewardCount, 'reward=', [(at[0].kindId, at[1]) for at in assetList] if assetList else []) if share.mail: pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, share.mail) # udpate free & promotion_loc datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) # 深圳研发中心修改,增加领奖后的返回指令 from freetime.entity.msg import MsgPack from poker.protocol import router mp = MsgPack() mp.setCmd('share_hall') mp.setAction('reward') mp.setResult('gameId', gameId) mp.setResult('userId', userId) mp.setResult('shareId', share.shareId) mp.setResult('rewards', [(at[0].kindId, at[1]) for at in assetList] if assetList else []) router.sendToUser(mp, userId) return True
def _sendAllRecordToUser(cls, userId, gameId, startRecordIndex, endRecordIndex, playMode=None, targetUserId=None, targetTableNo=None): """全量下发 带分页参数 """ #获取keys if targetUserId is None: targetUserId = userId recordKey = cls._getTableRecordKey(gameId, targetUserId) ftlog.debug('createTableRecord.sendAllRecordToUser2 recordKey:', recordKey, 'startRecordIndex:', startRecordIndex, 'endRecordIndex:', endRecordIndex) if startRecordIndex < 0: startRecordIndex = 0 if endRecordIndex < startRecordIndex: endRecordIndex = startRecordIndex userRecordKeys = gamedata.getGameAttr(targetUserId, gameId, recordKey) if not userRecordKeys: userRecordKeys = [] ftlog.debug( 'createTableRecord.sendAllRecordToUser2 recordKey content is null' ) else: userRecordKeys = json.loads(userRecordKeys) ftlog.debug( 'createTableRecord.sendAllRecordToUser2 recordKey content:', userRecordKeys) rLength = len(userRecordKeys) urKeys = [] for index in range(startRecordIndex, endRecordIndex + 1): newIndex = rLength - index - 1 if newIndex >= 0: urKeys.append(userRecordKeys[rLength - index - 1]) ftlog.debug('createTableRecord.sendAllRecordToUser2 urKeys:', urKeys) msg = MsgPack() msg.setCmd('create_table') msg.setResult('action', 'record') msg.setResult('type', 'update') playerRecordList = [] for userRecordKey in urKeys: playerRecordInfo = daobase.executeRePlayCmd('GET', userRecordKey) if not playerRecordInfo: ftlog.warn('createTableRecord.sendAllRecordToUser2 key:', userRecordKey, ' is null') else: playerRecordDist = json.loads(playerRecordInfo) # playMode过滤 if playMode and playMode != playerRecordDist.get('playMode'): continue # 房间号过滤 if targetTableNo and targetTableNo != playerRecordDist.get( 'tableNo'): continue playerRecordList.append(playerRecordDist) ftlog.debug('createTableRecord.sendAllRecordToUser2 key:', userRecordKey, ' content:', playerRecordDist) msg.setResult('list', playerRecordList) router.sendToUser(msg, userId)
def getGameClientVer(gameId, userId): return gamedata.getGameAttr(userId, gameId, _VERSION_KEY)
def loginGame(userId, gameId, clientId, iscreate, isdayfirst): """ 用户登录一个游戏, 游戏自己做一些其他的业务或数据处理 """ if ftlog.is_debug(): ftlog.debug("userId =", userId, "gameId =", gameId, "clientId =", clientId, "iscreate =", iscreate, "isdayfirst =", isdayfirst, gdata.name()) gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.gunLevel_m, 2101) if isdayfirst: sendVipSpringFestivalRewards(userId) if isdayfirst: vipAutoSupplyPerDay(userId) if isdayfirst: from newfish.entity.quest import daily_quest from newfish.entity import weakdata resetTime = weakdata.getDayFishData(userId, "resetTime") if not resetTime: weakdata.setDayFishData(userId, "resetTime", int(time.time())) daily_quest.refreshDailyQuestData(userId) # FTLoopTimer(1, 0, util.doSendFishNotice, userId).start() gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.vipShow, 1) serverVersion = gamedata.getGameAttrInt(userId, gameId, GameData.serverVersion) if isdayfirst and gamedata.getGameAttr( userId, FISH_GAMEID, GameData.hasBoughtMonthCard) is None: from hall.entity import hallitem userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() item = userBag.getItemByKindId(config.PERMANENT_MONTH_CARD_KINDID) or \ userBag.getItemByKindId(config.MONTH_CARD_KINDID) bought = 1 if item else 0 gamedata.setGameAttr(userId, FISH_GAMEID, GameData.hasBoughtMonthCard, json.dumps(bought)) if serverVersion and serverVersion <= 20180907: # 珍珠数量调整 util.adjustPearlCount(userId) if serverVersion and serverVersion <= 20180918: # 老玩家屏蔽10元话费卡兑换 gamedata.setGameAttr(userId, gameId, GameData.exchangeCount, 1) if serverVersion and serverVersion <= 20180928: # 老玩家金猪出现次数数据迁移 from newfish.entity import share_system from newfish.entity.share_system import FlyingPig shareClass = FlyingPig(userId) flyPigFinishCount = shareClass.shareData[ share_system.INDEX_FINISH_COUNT] gamedata.incrGameAttr(userId, FISH_GAMEID, GameData.flyPigFinishCount, flyPigFinishCount) # 清理金币购买记录,19/12/25日0点后开始检测 if int(time.time()) >= util.getTimestampFromStr("2019-12-25 00:00:00") and \ not gamedata.getGameAttrInt(userId, gameId, "resetBuyCoinCount"): gamedata.delGameAttr(userId, FISH_GAMEID, GameData.buyCoinCount) gamedata.setGameAttr(userId, gameId, "resetBuyCoinCount", 1) if not serverVersion or int(serverVersion) != SERVER_VERSION: gamedata.setGameAttr(userId, gameId, GameData.serverVersion, SERVER_VERSION) if not util.isFinishAllNewbieTask(userId): # 没完成所有新手引导,不主动弹出每日签到和最新消息 return # 限定玩家比赛幸运值. from newfish.entity.match_record import MatchRecord vip = hallvip.userVipSystem.getUserVip(userId).vipLevel.level for roomId in [44102]: key = "initLuckyValue:%d" % int(roomId) initVal = config.getVipConf(vip).get(key, 10000) record = MatchRecord.loadRecord(FISH_GAMEID, userId, roomId) record.luckyValue = min(record.luckyValue, initVal) MatchRecord.saveRecord(FISH_GAMEID, userId, roomId, record)
def _getFriendGameInfo(userId, gameIds, for_level_info, for_winchip, for_online_info=1): uid = int(userId) datas = {} gid, rid, tid, sid = 0, 0, 0, 0 state = daoconst.OFFLINE if for_online_info: loclist = onlinedata.getOnlineLocList(uid) state = onlinedata.getOnlineState(uid) if len(loclist) > 0: _rid, _tid, _sid = loclist[0] # gid表示用户在哪个游戏中 gid = strutil.getGameIdFromInstanceRoomId(_rid) # 检查是否可加入游戏 if TYGame(gid).canJoinGame(userId, _rid, _tid, _sid): # rid/tid/sid表示用户所在的游戏是否可加入游戏 # 分享出来的都是可以加入游戏的牌桌信息 rid = _rid tid = _tid sid = _sid if ftlog.is_debug(): ftlog.debug('getFriendGameInfo userId:', userId, ' gameId:', gid, ' roomId:', _rid, ' tableId:', _tid, ' seatId:', _sid, ' can not join game....') if state == daoconst.OFFLINE: offline_time = gamedata.getGameAttr(uid, HALL_GAMEID, 'offlineTime') if not offline_time: # 取不到离线时间,取上线时间 offline_time = userdata.getAttr(uid, 'authorTime') if offline_time: offline_time = pktimestamp.parseTimeMs(offline_time) delta = datetime.now() - offline_time delta = delta.days * 24 * 60 + delta.seconds / 60 # 分钟数 else: # 异常情况 delta = 24 * 60 datas['offline_time'] = delta if delta > 0 else 1 if rid > 0: try: room = gdata.roomIdDefineMap().get(rid, None) if room: datas['room_name'] = room.configure['name'] except: ftlog.error() # 构造回传给SDK的游戏数据 datas.update({'uid': uid, 'gid': gid, 'rid': rid, 'tid': tid, 'sid': sid, 'state': state}) if for_level_info: datas['level_game_id'] = 0 datas['level'] = 0 datas['level_pic'] = '' try: for gameId in gameIds: if gameId not in gdata.games(): continue dashifen_info = gdata.games()[gameId].getDaShiFen(uid, '') if dashifen_info: level = dashifen_info['level'] if level > 0 and level > datas['level']: datas['level_game_id'] = gameId datas['level'] = level level_pic = dashifen_info.get('picbig') datas['level_pic'] = level_pic if level_pic else dashifen_info.get('pic') except: ftlog.error() if for_winchip: datas['winchip'] = 0 datas['winchips'] = 0 try: for gameId in gameIds: winchips, todaychips = gamedata.getGameAttrs(userId, gameId, ['winchips', 'todaychips'], False) winchips = strutil.parseInts(winchips) yest_winchip = 0 todaychips = strutil.loads(todaychips, ignoreException=True) if todaychips and 'today' in todaychips and 'chips' in todaychips and 'last' in todaychips: if pktimestamp.formatTimeDayInt() == todaychips['today']: yest_winchip = todaychips['last'] elif pktimestamp.formatTimeYesterDayInt() == todaychips['today']: yest_winchip = todaychips['chips'] datas['winchip'] += yest_winchip datas['winchips'] += winchips except: ftlog.error() return datas
def getGameInfo(userId, clientId): """ 获取玩家的游戏数据 """ from newfish.entity import user_system ukeys = getInitDataKeys() uvals = gamedata.getGameAttrs(userId, FISH_GAMEID, ukeys) uvals = list(uvals) values = getInitDataValues() for x in xrange(len(uvals)): if uvals[x] is None: uvals[x] = values[x] gdata = dict(zip(ukeys, uvals)) gdata["name"] = util.getNickname(userId) gdata["userGuideStep"] = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.userGuideStep, []) redState = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.redState) gdata["redState"] = redState gdata["giftState"] = newbie_7days_gift.checkNewbie7DaysGiftState( userId, redState) # 是否可以领取启航礼包(1:是 0:否) # gdata["sailGiftState"] = 1 if gift_system.SailGift(userId, clientId).getGiftInfo() else 0 gdata["surpriseGift"] = weakdata.getDayFishData(userId, GameData.surpriseGift, 0) gdata["exchangeCount"] = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.exchangeCount) gdata["nowServerTime"] = time.time() gdata["isAdult"] = user_system.isAdult(userId) # 是否为v2版本老玩家(1:是 0:否) isOldPlayerV2 = gamedata.getGameAttr(userId, FISH_GAMEID, GameData.isOldPlayerV2) if isOldPlayerV2 is None: isOldPlayerV2 = 0 clientVersion = gamedata.getGameAttr(userId, FISH_GAMEID, GameData.clientVersion) if redState: isOldPlayerV2 = 1 elif clientVersion and StrictVersion( str(clientVersion)) < StrictVersion("3.0.0"): isOldPlayerV2 = 1 gamedata.setGameAttr(userId, FISH_GAMEID, GameData.redState, 1) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.isOldPlayerV2, isOldPlayerV2) v2DataTov3Data(userId, clientId) gdata["isOldPlayerV2"] = isOldPlayerV2 # 当前技能页面显示的模式,老玩家默认为经典模式(0:经典 1:千炮) skillMode = gamedata.getGameAttr(userId, FISH_GAMEID, GameData.skillMode) if skillMode is None: skillMode = config.CLASSIC_MODE if isOldPlayerV2 else config.MULTIPLE_MODE gamedata.setGameAttr(userId, FISH_GAMEID, GameData.skillMode, skillMode) gdata["skillMode"] = skillMode # 当前炮台页显示的模式,老玩家默认为经典模式(0:经典 1:千炮) gunMode = gamedata.getGameAttr(userId, FISH_GAMEID, GameData.gunMode) if gunMode is None: gunMode = config.CLASSIC_MODE if isOldPlayerV2 else config.MULTIPLE_MODE gamedata.setGameAttr(userId, FISH_GAMEID, GameData.gunMode, gunMode) gdata["gunMode"] = gunMode exp, level = gamedata.getGameAttrs(userId, FISH_GAMEID, [GameData.exp, GameData.level]) exp = exp or 0 level = level or 1 _, expPct = util.getUserLevelExpData(userId, level, exp) gdata["level"] = level gdata["expPct"] = expPct return gdata
def queryExitPluginRemind(userId, _gameId, clientId, gamesUserCanSee): ''' 获取推荐的快开配置 ''' global _ordersMap templateName = hallconf.getExitPluginRemindTemplateName(clientId) ftlog.debug('templateName:', templateName) templates = _ordersMap.get('templates', []) for template in templates: ftlog.debug('template:', template) if template.get('name', '') == templateName: # 找到当前的模板了 remindGames = template.get('remindGames', []) # 首先获取可以引导去哪些游戏 gameIds = [] for remindGame in remindGames: gameId = remindGame.get('gameId', 0) if (gameId != 0) and (gameId not in gameIds) and (gameId in gamesUserCanSee) and (gameId != _gameId): gameIds.append(gameId) # 第二,获取目标游戏的游戏行为 mostGameId = 0 # 玩儿的最多的游戏一个,进入次数最多的游戏 mostGameLoginSum = 0 lastGameId = 0 # 上次玩儿的游戏一个,通过游戏的进入时间判断,时间最大的 lastAuthTime = 0 leastGameId = 0 # 最长时间没玩儿的游戏一个,通过游戏进入时间判断,时间最小的 leastAuthTime = 0 neverGames = [] # 没玩儿的游戏若干,没有游戏记录的,游戏登录次数为0的 for game in gameIds: loginSum = gamedata.getGameAttr(userId, game, 'loginsum') if 0 == loginSum: neverGames.append(game) else: if loginSum > mostGameLoginSum: mostGameId = game mostGameLoginSum = loginSum authorTimeStr = gamedata.getGameAttr(userId, game, 'authorTime') _lastAuthTime = 0 if authorTimeStr: _lastAuthTime = pktimestamp.timestrToTimestamp(authorTimeStr, '%Y-%m-%d %H:%M:%S.%f') if _lastAuthTime and (_lastAuthTime > lastAuthTime): lastGameId = game lastAuthTime = _lastAuthTime if 0 == leastAuthTime or (_lastAuthTime and (_lastAuthTime < leastAuthTime)): leastAuthTime = _lastAuthTime leastGameId = game ftlog.debug('mostGameId:', mostGameId , ' lastGameId:', lastGameId , ' leastGameId:', leastGameId , ' neverGames:', neverGames) choices = [] if mostGameId: choices.append(TYPE_MOST) if lastGameId: choices.append(TYPE_LAST) if leastGameId: choices.append(TYPE_LEAST) if neverGames: choices.append(TYPE_NEVER) if not choices: return cType = random.choice(choices) cGame = 0 if TYPE_MOST == cType: cGame = mostGameId elif TYPE_LAST == cType: cGame = lastGameId elif TYPE_LEAST == cType: cGame = leastGameId elif TYPE_NEVER == cType: cGame = random.choice(neverGames) ftlog.debug('cType:', cType , ' cGame:', cGame) reminds = [] for remindGame in remindGames: gameId = remindGame.get('gameId', 0) if gameId == cGame: reminds.append(remindGame) if reminds: remind = random.choice(reminds) ftlog.debug('remind:', remind) # 第四,选择游戏进行引导挽留 return sendExitPluginRemindMsg(userId, _gameId, clientId, remind, cType) return '1'
def _sendAllRecordToUser(cls , userId , gameId , startRecordIndex , endRecordIndex , playMode=None , targetUserId=None , targetTableNo=None ): """全量下发 带分页参数 """ #获取keys if targetUserId is None: targetUserId = userId recordKey = cls._getTableRecordKey(gameId, targetUserId) ftlog.debug('createTableRecord.sendAllRecordToUser2 recordKey:', recordKey, 'startRecordIndex:', startRecordIndex, 'endRecordIndex:', endRecordIndex) if startRecordIndex < 0: startRecordIndex = 0 if endRecordIndex < startRecordIndex: endRecordIndex = startRecordIndex userRecordKeys = gamedata.getGameAttr(targetUserId, gameId, recordKey) if not userRecordKeys: userRecordKeys = [] ftlog.debug('createTableRecord.sendAllRecordToUser2 recordKey content is null') else: userRecordKeys = json.loads(userRecordKeys) ftlog.debug('createTableRecord.sendAllRecordToUser2 recordKey content:', userRecordKeys) rLength = len(userRecordKeys) urKeys = [] for index in range(startRecordIndex, endRecordIndex + 1): newIndex = rLength - index - 1 if newIndex >= 0: urKeys.append(userRecordKeys[rLength - index - 1]) ftlog.debug('createTableRecord.sendAllRecordToUser2 urKeys:', urKeys) msg = MsgPack() msg.setCmd('create_table') msg.setResult('action', 'record') msg.setResult('type', 'update') playerRecordList = [] for userRecordKey in urKeys: playerRecordInfo = daobase.executeRePlayCmd('GET', userRecordKey) if not playerRecordInfo: ftlog.warn('createTableRecord.sendAllRecordToUser2 key:', userRecordKey, ' is null') else: playerRecordDist = json.loads(playerRecordInfo) # playMode过滤 if playMode and playMode != playerRecordDist.get('playMode'): continue # 房间号过滤 if targetTableNo and targetTableNo != playerRecordDist.get('tableNo'): continue playerRecordList.append(playerRecordDist) ftlog.debug('createTableRecord.sendAllRecordToUser2 key:', userRecordKey, ' content:', playerRecordDist) msg.setResult('list', playerRecordList) router.sendToUser(msg, userId)
def noticeReward(userId, gameId, clientId, msg): from hall.entity.localservice import localservice ftlog.debug("noticeReward:", userId, gameId, clientId, msg) # 是否是登录大厅 if gameId != HALL_GAMEID: ftlog.debug("noticeReward|isnotloginHall", gameId) return # 是否是v4.56 if not localservice.checkClientVer(userId, gameId, clientId): ftlog.debug("noticeReward|failer|clientVer|isnotMatch|", userId, gameId, clientId) return data = getNoticeRewardData(userId, gameId, clientId) if not data: ftlog.warn("noticeReward|haveNotConfig", userId, gameId, clientId) return ftlog.debug("noticeReward|data|", userId, "sub_action" in data, data) if "sub_action" in data: if "noticereward" in data["sub_action"]["params"]: info = gamedata.getGameAttr(userId, HALL_GAMEID, NPW_ + "noticereward") ftlog.debug("noticereward|redis", userId, info, type(info), data["sub_action"]["params"]["noticereward"], type(data["sub_action"]["params"]["noticereward"]), info == data["sub_action"]["params"]["noticereward"]) if info: info = json.loads(info) if not info or info != data["sub_action"]["params"]["noticereward"]: if "params" not in data["sub_action"] or "reward" not in data[ "sub_action"]["params"]: ftlog.warn("noticeReward|ConfigError!", userId, gameId, clientId) return rewardList = [] rewardds = data["sub_action"]["params"]["reward"] for rewardd in rewardds: addAssetnpw(userId, rewardd['itemId'], rewardd['count'], "HALL_NEWNOTICEREWARD") rewardList.append({ 'name': rewardd['name'], 'pic': rewardd['pic'], 'count': rewardd['count'] }) gamedata.setGameAttr( userId, HALL_GAMEID, NPW_ + "noticereward", json.dumps(data["sub_action"]["params"]["noticereward"])) rewardTodotask = TodoTaskShowRewards(rewardList) TodoTaskHelper.sendTodoTask(gameId, userId, rewardTodotask) ftlog.debug("noticereward|addAssetnpw。", userId) else: ftlog.debug("noticereward|alreadydone。", userId) msg = u"对不起,您已经领过该奖励了。" infoTodoTask = TodoTaskShowInfo(msg, True) TodoTaskHelper.sendTodoTask(gameId, userId, infoTodoTask)
def handleEvent(cls, event): try: gameId = 6 userId = event.userId conf = dizhuconf.getActivityConf("dashi_send") # 检查日期在活动日期内 if not cls.dateCheck(gameId, userId, conf): cls.removeDashiItems(gameId, userId, conf) return # 检查用户当前在地主游戏中 if not cls.gameCheck(userId, gameId): return # 获得大师分段位 dashi_score = gamedata.getGameAttr(userId, gameId, 'skillscore') or 1 dashi_level = skillscore.get_skill_level(dashi_score) # 获取配置中大师分的段位限制 dashi_level_limit = conf.get("dashi_level", 1) if dashi_level < dashi_level_limit: return # 如果已经发送过大师登陆礼包,则不发送 attrname = cls.getFlagAttr(conf.get('start_date', '2015-01-01')) is_send = gamedata.getGameAttr(userId, gameId, attrname) if is_send: return # 道具生成时间 timestamp = pktimestamp.getCurrentTimestamp() # 要发送的道具列表 items = conf.get("item_send", []) for item in items: contentItem = TYContentItem.decodeFromDict(item) userAssets = hallitem.itemSystem.loadUserAssets(userId) assetKind, _, _ = userAssets.addAsset(gameId, contentItem.assetKindId, contentItem.count, timestamp, 'DIZHU_DASHI_SEND', 0) # 发送邮箱信息 mail_message = conf.get("mail", "") if mail_message: pkmessage.sendPrivate(9999, userId, 0, mail_message) # 通知用户道具和消息存在改变 if assetKind.keyForChangeNotify: datachangenotify.sendDataChangeNotify( gameId, userId, [assetKind.keyForChangeNotify, 'message']) # 成功发送大师登陆礼包,记录下来,避免重复发送 gamedata.setGameAttr(userId, gameId, attrname, 1) ftlog.debug('dashisend dashi_level=', dashi_level, 'dashi_level_limit=', dashi_level_limit, 'userId=', userId) except: ftlog.exception()