def getGlobal(gameId, userId, pageNo=1): """ 已废弃,待删除 取得当前用户的全局未读私信的内容 """ maxMsgId = daobase.executeMixCmd('HGET', 'msg', 'msg.id.max.' + str(gameId)) readMaxId = gamedata.getGameAttrs(userId, gameId, 'msg.id.global') rediskey = 'msg:' + str(gameId) maxMsgId, readMaxId = strutil.parseInts(maxMsgId, readMaxId) msglist = [] maxId = readMaxId if pageNo < 1: pageNo = 1 lstart = (pageNo - 1) * 20 lend = lstart + 20 - 1 datas = daobase.executeMixCmd('LRANGE', rediskey, lstart, lend) count = 0 if datas: for msgstr in datas: msg = strutil.loads(msgstr, ignoreException=True) if msg: maxId = max(maxId, msg['id']) msglist.append(msg) count += 1 if maxId > readMaxId: gamedata.setGameAttr(userId, gameId, 'msg.id.global', maxId) return { 'count': count, 'maxId': maxMsgId, 'readId': readMaxId, 'pageNo': pageNo, 'list': msglist }
def _moveHall51DataBack(userId, gameId, clientId): try: gameId = HALL_ID flag = gamedata.getGameAttrInt(userId, gameId, 'userChipMoveGame') ftlog.info('_moveHall51DataBack', userId, gameId, flag) if flag > 0: # 当前用户登录过HALL51 chip, exp, charm, coupon = gamedata.getGameAttrs( userId, gameId, ['chip', 'exp', 'charm', 'coupon']) chip, exp, charm, coupon = strutil.parseInts( chip, exp, charm, coupon) ftlog.info('_moveHall51DataBack data->', userId, gameId, chip, exp, charm, coupon) if charm > 0: userdata.incrCharm(userId, charm) if exp > 0: userdata.incrExp(userId, exp) if coupon > 0: trueDelta, finalCount = userchip.incrCoupon( userId, gameId, coupon, userchip.ChipNotEnoughOpMode.NOOP, userchip.EVENT_NAME_SYSTEM_REPAIR, 0, clientId) ftlog.info('_moveHall51DataBack data coupon->', userId, gameId, coupon, trueDelta, finalCount) if chip > 0: trueDelta, finalCount = userchip.incrChip( userId, gameId, chip, userchip.ChipNotEnoughOpMode.NOOP, userchip.EVENT_NAME_SYSTEM_REPAIR, 0, clientId) ftlog.info('_moveHall51DataBack data chip->', userId, gameId, chip, trueDelta, finalCount) gamedata.delGameAttrs( userId, gameId, ['chip', 'exp', 'charm', 'coupon', 'userChipMoveGame']) datachangenotify.sendDataChangeNotify(gameId, userId, 'chip') except: ftlog.error()
def _checkSetMedal(userId, roomMutil, basebet, basemulti, isGameStart, winchip): winchip = 0 if isGameStart else winchip winrate, oldLevel = gamedata.getGameAttrs(userId, DIZHU_GAMEID, ['winrate', 'level'], False) winrate = strutil.loads(winrate, ignoreException=True, execptionValue={}) if winchip >= 0 or isGameStart: _processGamePlayWinTimes(winrate, isGameStart) oldLevel = strutil.parseInts(oldLevel) detalExp = 0 if winchip > 0 or isGameStart: detalExp = _calUserDetalExp(winchip, roomMutil, basebet, basemulti) exp = userdata.incrExp(userId, detalExp) explevel = dizhuaccount.getExpLevel(exp) gamedata.setGameAttrs(userId, DIZHU_GAMEID, ['winrate', 'level'], [strutil.dumps(winrate), explevel]) if oldLevel != explevel: from dizhu.game import TGDizhu TGDizhu.getEventBus().publishEvent( UserLevelGrowEvent(DIZHU_GAMEID, userId, oldLevel, explevel)) if isGameStart: # 广告商通知 pcount = dizhuconf.getAdNotifyPlayCount() if pcount > 0 and winrate.get('pt', 0) == pcount: sdkclient.adNotifyCallBack(DIZHU_GAMEID, userId) nextExp = dizhuaccount.getGameUserNextExp(explevel) title = dizhuaccount.getGameUserTitle(explevel) return [explevel, exp, detalExp, nextExp, title]
def get_kvs(cls, tasklet, uid, gid): ''' attrs = ['lastlogin', 'nslogin', 'play_game_count', 'win_game_count', 'draw_game_count', 'lose_game_count', 'bang_count', 'highest_lose_chip', 'highest_win_chip', 'highest_chip_record', 'day_win_game_count', 'day_win_sequence_count', 'day_max_win_sequence_count', 'big_pattern_history', 'best_pattern', 'online_records', 'guobiao_play_game_count', 'guobiao_win_game_count', 'guobiao_draw_game_count', 'guobiao_lose_game_count', 'guobiao_bang_count', 'guobiao_highest_lose_chip', 'guobiao_highest_win_chip', 'guobiao_highest_chip_record', 'win_sequence_count', 'max_win_sequence_count', 'guobiao_best_pattern', 'guobiao_online_records', 'max_degree_week_duration', 'max_degree_week_duration_ts', 'master_point', 'week_master_point', 'week_master_point_ts', 'day_play_game_count'] ''' attrs = ['win_sequence_count', 'max_win_sequence_count', 'guobiao_best_pattern'] values = gamedata.getGameAttrs(uid, gid, attrs) for i, value in enumerate(values): if value is None: ftlog.debug(attrs[i], 'is None') values[i] = cls.get_default_value(attrs[i])[1] else: values[i] = cls.parse_content_from_redis(attrs[i], value) kvs = dict(zip(attrs, values)) cls.check_attrs_timestamp(tasklet, uid, gid, kvs) kvs['chip'] = userchip.getChip(uid) kvs['exp'] = userdata.getExp(uid) kvs['charm'] = userdata.getCharm(uid) if not kvs['chip']: kvs['chip'] = 0 if not kvs['exp']: kvs['exp'] = 0 if not kvs['charm']: kvs['charm'] = 0 return kvs
def do_xq_update_old_user(uid, snsId, chessExp, totalNum, winNum, loseNum, drawNum): ret = userdata.checkUserData(uid, PCCLIENTID, 3) ftlog.info('PCXQ_USER load already user data !', uid, snsId, 'ret=', ret) chessExpOld, chessRecordOld = gamedata.getGameAttrs(uid, 3, ['chessExp', 'chessRecord'], False) creat = 0 if chessExpOld == None or chessRecordOld == None : creat = 1 else: try: chessExpOld = int(chessExpOld) except: creat = 1 try: chessRecordOld = json.loads(chessRecordOld) totalNum = totalNum + int(chessRecordOld.get('totalNum')) winNum = winNum + int(chessRecordOld.get('winNum')) loseNum = loseNum + int(chessRecordOld.get('loseNum')) drawNum = drawNum + int(chessRecordOld.get('drawNum')) except: creat = 1 if creat : ftlog.info('PCXQ_USER creat old user XQ gamedata !', uid, snsId, 'chessExpOld=', chessExpOld, 'chessRecordOld=', chessRecordOld) creat_gamedata(uid, chessExp, totalNum, winNum, loseNum, drawNum) else: ftlog.info('PCXQ_USER update old user XQ gamedata !', uid, snsId, 'chessExpOld=', chessExpOld, 'chessRecordOld=', chessRecordOld) chessExp = max(chessExpOld, chessExp) chessRecordOld['totalNum'] = totalNum chessRecordOld['winNum'] = winNum chessRecordOld['loseNum'] = loseNum chessRecordOld['drawNum'] = drawNum gamedata.setGameAttrs(uid, 3, ['chessExp', 'chessRecord'], [chessExp, json.dumps(chessRecordOld)])
def checkSetMedal(gameId, userId, baseScore, isGameStart, winchip): winchip = 0 if isGameStart else winchip winrate, oldLevel = gamedata.getGameAttrs(userId, gameId, ['winrate', 'level'], False) winrate = strutil.loads(winrate, ignoreException=True, execptionValue={}) if winrate is None: winrate = {} if winchip >= 0 or isGameStart: _processGamePlayWinTimes(winrate, isGameStart) oldLevel = strutil.parseInts(oldLevel) deltaExp = 0 if winchip > 0 or isGameStart: deltaExp = _calUserDetalExp(winchip, baseScore) exp = userdata.incrExp(userId, deltaExp) explevel, _ = gameexp.getLevelInfo(gameId, exp) gamedata.setGameAttrs(userId, gameId, ['winrate', 'level'], [strutil.dumps(winrate), explevel]) if oldLevel != explevel: TYGame(gameId).getEventBus().publishEvent( UserLevelGrowEvent(gameId, userId, oldLevel, explevel)) if isGameStart: # 广告商通知 pcount = commconf.getAdNotifyPlayCount(gameId) if pcount > 0 and winrate.get('pt', 0) == pcount: sdkclient.adNotifyCallBack(gameId, userId) return exp, deltaExp, winrate
def onWinlose(cls, event): clientId = sessiondata.getClientId(event.userId) timestamp = pktimestamp.getCurrentTimestamp() if ftlog.is_debug(): ftlog.debug('FiveStarRate.onWinlose userId=', event.userId, 'clientId=', clientId, 'roomId=', event.roomId, 'tableId=', event.tableId, 'winlose=', event.winlose.__dict__) if not event.winlose.isWin: return winDesc = dizhuconf.getPublicConf('five_star_win_desc', '') # 玩家在高倍场馆单局倍数超过128倍并获胜,且获胜得到的金币大于20W时 if event.winlose.windoubles >= 128: hallfivestarrate.triggleFiveStarRateIfNeed(event.userId, clientId, timestamp, winDesc) return # 账号注册时间大于五天、游戏局数超过20局的玩家,连续获胜3局时 if cls.calcRegisterDays(event.userId, timestamp) > 5: winrate, winstreak = gamedata.getGameAttrs(event.userId, DIZHU_GAMEID, ['winrate', 'winstreak']) winrate = strutil.loads(winrate, ignoreException=True, execptionValue={'pt':0, 'wt':0}) try: winstreak = 0 if winstreak is None else int(winstreak) except: winstreak = 0 if winrate.get('pt', 0) > 20 and winstreak == 3: hallfivestarrate.triggleFiveStarRateIfNeed(event.userId, clientId, timestamp, winDesc)
def sendCardsToAllUserIds(cls, gameId, userIds): bcards = [] allCards = cls.getQuickPokers() ret = [None for _ in xrange(len(userIds) + 1)] try: for i, userId in enumerate(userIds): cards, bcards = gamedata.getGameAttrs( userId, gameId, ['test.cards', 'test.bcards']) if cards: cards = cls.decodeCards(cards) if len(cards) > 13: cards = cards[0:13] cards = cls._sendCards(cards, allCards) cards = cls._buqiCards(cards, allCards, 13) ret[i] = list(cards) if bcards: bcards = cls.decodeCards(bcards) if len(bcards) > 3: bcards = bcards[0:3] if bcards: bcards = cls._sendCards(bcards, allCards) bcards = cls._buqiCards(bcards, allCards, 3) ret[-1] = list(bcards) for i in xrange(len(userIds)): if not ret[i] or len(ret[i]) != 13: ret[i] = list(cls._buqiCards(ret[i], allCards, 13)) return ret except: ftlog.error('dizhu_quick_laizi_sendCardsToAllUserIds error') return None
def enter(self, userId): '''玩家进入队列''' if self.users.get(userId) != None: ftlog.error(getMethodName(), "already in queue!", self.baseLogStr(None, userId)) return False onlinedata.addOnlineLoc(userId, self.room.roomId, self.room.roomId * 10000, 1) cardLevel, isWinner, isToBeBanker = \ gamedata.getGameAttrs(userId, self.room.gameId, ["cardLevel", "isWinner", "isToBeBanker"]) if cardLevel == None: # 新玩家, 必须初始化cardLevel cardLevel, isWinner, isToBeBanker = 2, False, False gamedata.setGameAttrs(userId, self.room.gameId, ["cardLevel", "isWinner", "isToBeBanker"], [2, False, False]) # 修改users数据的代码段中不允许有异步操作 self.users[userId] = {"enterTime": time.time()} self.users[userId]["cardLevel"], self.users[userId]["isWinner"], self.users[userId]["isToBeBanker"] = \ cardLevel, isWinner, isToBeBanker self.matchTeamMate(userId) if ftlog.is_debug(): ftlog.debug(">>", self.baseLogStr(None, userId), "|self.users[userId]:", self.users[userId], "|locList:", onlinedata.getOnlineLocList(userId), caller=self) return True
def getUserGamePlayTimes(userId): ''' 获取用户当游戏总局数 ''' winrate = gamedata.getGameAttrs(userId, 6, ['winrate']) winrate = strutil.loads(winrate[0], ignoreException=True, execptionValue={'pt': 0, 'wt': 0}) return winrate.get('pt', 0)
def get_unread_count(userid, typeid): """ 取得当前用户的未读站内消息的个数 """ readkey = MESSAGE_TYPES[typeid] maxid, readid = gamedata.getGameAttrs(userid, HALL_GAMEID, ['msg.id.max', readkey]) maxid, readid = strutil.parseInts(maxid, readid) return maxid - readid
def increaceChipTableWinrate(gameId, userId, isGameStart, winchip): winchip = 0 if isGameStart else winchip winrate2 = gamedata.getGameAttrs(userId, gameId, ['winrate2'], False)[0] winrate2 = strutil.loads(winrate2, ignoreException=True, execptionValue={}) if not winrate2: winrate2 = {'pt': 0, 'wt': 0} if winchip >= 0 or isGameStart: _processGamePlayWinTimes(winrate2, isGameStart) gamedata.setGameAttrs(userId, gameId, ['winrate2'], [strutil.dumps(winrate2)]) return winrate2
def getGameInfo(userId, clientId, gameId): """ 获取玩家的游戏数据 """ ukeys = getInitDataKeys() uvals = gamedata.getGameAttrs(userId, gameId, ukeys) uvals = list(uvals) values = getInitDataValues() for x in xrange(len(uvals)): if uvals[x] == None: uvals[x] = values[x] gdata = dict(zip(ukeys, uvals)) return gdata
def getGameInfo(userId, clientId, gameId): """ 获取玩家的游戏数据 """ ukeys = getInitDataKeys() uvals = gamedata.getGameAttrs(userId, gameId, ukeys) uvals = list(uvals) values = getInitDataValues() for x in xrange(len(uvals)): if uvals[x] == None: uvals[x] = values[x] gdata = dict(zip(ukeys, uvals)) return gdata
def getShareStatus(userId, share, nowDate): try: keyOfRewardDay = 'share_reward_day:%s' % (share.shareId) keyOfRewardCount = 'share_reward:%s' % (share.shareId) rewardDate, rewardCount = gamedata.getGameAttrs(userId, HALL_GAMEID, [keyOfRewardDay, keyOfRewardCount]) if rewardDate is not None: rewardDate = datetime.strptime(rewardDate, '%Y-%m-%d').date() if rewardDate == nowDate: return rewardDate, rewardCount except: ftlog.error('hallshare.getShareStatus userId=', userId, 'shareId=', share.shareId) return nowDate, 0
def doGetUserDailyPlayCountLocal(userId, gameId, **kwargs): dailyPlay = gamedata.getGameAttrs(userId, gameId, ['dailyPlay']) dailyPlay = strutil.loads(dailyPlay[0], ignoreException=True, execptionValue={ 'count': 0, 'timestamp': pktimestamp.getCurrentTimestamp() }) if ftlog.is_debug(): ftlog.debug('doGetUserDailyPlayCount userId=', userId, 'dailyPlay=', dailyPlay) return dailyPlay['count']
def getShareStatus(userId, share, nowDate): try: keyOfRewardDay = 'share_reward_day:%s' % (share.shareId) keyOfRewardCount = 'share_reward:%s' % (share.shareId) rewardDate, rewardCount = gamedata.getGameAttrs( userId, HALL_GAMEID, [keyOfRewardDay, keyOfRewardCount]) if rewardDate is not None: rewardDate = datetime.strptime(rewardDate, '%Y-%m-%d').date() if rewardDate == nowDate: return rewardDate, rewardCount except: ftlog.error('hallshare.getShareStatus userId=', userId, 'shareId=', share.shareId) return nowDate, 0
def getDaShiFen(userId, clientId): """ 获取玩家大师分信息 """ exp, level = gamedata.getGameAttrs(userId, FISH_GAMEID, [GameData.exp, GameData.level]) info = {} info["score"] = exp info["level"] = level info[ "pic"] = "http://ddz.dl.tuyoo.com/texas/res/icon/shark/texas_shark_icon_" + level + ".png" info["title"] = "" info["name"] = "捕鱼" info["des"] = "捕鱼积分" return info
def isSentStartChip(userId): ''' 已经发放过启动资金 :param userId: ''' isSendChip = 0 values = gamedata.getGameAttrs(userId, hallconf.HALL_GAMEID, ["fuzhou_start_chip", "start_chip_dfchip"]) for value in values: if not isinstance(value, (int, float)): value = 0 isSendChip += value if isSendChip > 0: return True return False
def sendCards(self, tableId, userIds): from poker.entity.configure import gdata if gdata.mode() == gdata.RUN_MODE_ONLINE: return None final_bcards = [] allCards = set([c for c in xrange(54)]) if len(userIds) == 2: kick_out_card = set([2, 3, 15, 16, 28, 29, 41, 42]) allCards -= kick_out_card ret = [[] for _ in xrange(len(userIds) + 1)] changed = False try: for i, userId in enumerate(userIds): cards, bcards = gamedata.getGameAttrs( userId, DIZHU_GAMEID, ['test.cards', 'test.bcards']) if cards: changed = True cards = self.decodeCards(cards) if len(cards) > 17: cards = cards[0:17] cards = self.__sendCards(cards, allCards) cards = self.__buqiCards(cards, allCards, 17) ret[i] = list(cards) if not final_bcards and bcards: final_bcards = self.decodeCards(bcards) if len(final_bcards) > 3: final_bcards = final_bcards[0:3] if final_bcards: changed = True final_bcards = self.__sendCards(final_bcards, allCards) final_bcards = self.__buqiCards(final_bcards, allCards, 3) ret[-1] = list(final_bcards) if changed: for i in xrange(len(userIds)): if not ret[i] or len(ret[i]) != 17: ret[i] = list(self.__buqiCards(ret[i], allCards, 17)) return ret return None except: ftlog.error('sendCards.sendCardsToAllUserIds error') return None
def getUserPlayCount(userId): """ 获取用户打过的牌局数 @return {'total': 总局数,'win': 胜局数} """ swinrate = gamedata.getGameAttrs(userId, DIZHU_GAMEID, ['winrate']) if ftlog.is_debug(): ftlog.debug('getUserPlayCount', 'swinrate=', swinrate[0]) swinrate = strutil.loads(swinrate[0], ignoreException=True, execptionValue={ 'pt': 0, 'wt': 0 }) ftlog.debug('getUserPlayCount', 'swinrate=', swinrate) totalplays = swinrate.get('pt', 0) winplays = swinrate.get('wt', 0) return {'total': totalplays, 'win': winplays}
def fuzhou_checkAndSendGuide(userId, clientId): ''' 检测并发送抚州金币场新手引导 :param userId: :param clientId: ''' isSendGuide = 0 values = gamedata.getGameAttrs( userId, hallconf.HALL_GAMEID, ["fuzhou_chip_guide", "newuser_guide_dfchip"]) for value in values: if not isinstance(value, (int, float)): value = 0 isSendGuide += value if _checkConditions(userId, clientId) and isSendGuide <= 0: return True return False
def ensureGameDataExists(userId, gameId, clientId): ''' 判定用户游戏数据是否存在, 若不存在则初始化该游戏的所有的相关游戏数据 包括: 主游戏数据gamedata, 道具, 勋章等 ''' isCreate = False gaccount = TYGame(gameId) # 以游戏主数据的前2个字段为判定条件 ukeys = gaccount.getInitDataKeys()[0:2] d1, d2 = gamedata.getGameAttrs(userId, gameId, ukeys) if d1 is None or d2 is None: gdkeys, gdata = gaccount.createGameData(userId, gameId) gdkeys.append('createTime') gdata.append(timestamp.formatTimeMs()) bireport.creatGameData(gameId, userId, clientId, gdkeys, gdata) bireport.reportGameEvent('CREATE_GAME_DATA', userId, gameId, 0, 0, 0, 0, 0, 0, [], clientId) isCreate = True return isCreate
def sendCardsToUserIds(cls, gameId, tableId, userIds): bcards = [] final_bcards = [] allCards = set([c for c in xrange(54)]) if len(userIds) == 2: kick_out_card = set([2, 3, 15, 16, 28, 29, 41, 42]) allCards -= kick_out_card ret = [[] for _ in xrange(len(userIds) + 1)] try: for i, userId in enumerate(userIds): cards, bcards = gamedata.getGameAttrs( userId, gameId, ['test.cards', 'test.bcards']) if cards: cards = cls.decodeCards(cards) if len(cards) > 17: cards = cards[0:17] cards = cls._sendCards(cards, allCards) cards = cls._buqiCards(cards, allCards, 17) ret[i] = list(cards) if not final_bcards and bcards: final_bcards = cls.decodeCards(bcards) if len(final_bcards) > 3: final_bcards = final_bcards[0:3] if final_bcards: final_bcards = cls._sendCards(final_bcards, allCards) final_bcards = cls._buqiCards(final_bcards, allCards, 3) ret[-1] = list(final_bcards) for i in xrange(len(userIds)): if not ret[i] or len(ret[i]) != 17: ret[i] = list(cls._buqiCards(ret[i], allCards, 17)) if ftlog.is_debug(): ftlog.debug( 'playmodes.base.SendCardPolicyUserId.sendCards tableId=', tableId, 'userIds=', userIds, 'cards=', ret) return ret except: ftlog.error('sendCards.sendCardsToAllUserIds error') return None
def get(userid, typeid): """ 获取消息列表 @param userid: @param typeid: 类型, L{message.MESSAGE_TYPES} @return: """ if typeid not in MESSAGE_TYPES: raise Exception("message.get, unkown type:{}".format(typeid)) rediskey = REDIS_KEY.format(typeid, HALL_GAMEID, userid) msglist = _msg_load_and_expire(userid, rediskey) msglist.sort(key=_msg_order) readkey = MESSAGE_TYPES[typeid] maxid, readid = gamedata.getGameAttrs(userid, HALL_GAMEID, ['msg.id.max', readkey]) maxid, readid = strutil.parseInts(maxid, readid) if maxid > readid: gamedata.setGameAttr(userid, HALL_GAMEID, readkey, maxid) return {'readid': readid, 'list': msglist}
def can_ios_tablefinish_fivestar(event): if not event.winlose.isWin: return False # 玩家在高倍场馆单局倍数超过128倍并获胜 if event.winlose.windoubles >= 128: return True # 账号注册时间大于五天、游戏局数超过20局的玩家,连续获胜3局时 timestamp = pktimestamp.getCurrentTimestamp() if UserInfo.getRegisterDays(event.userId, timestamp) > 5: winrate, winstreak = gamedata.getGameAttrs(event.userId, 6, ['winrate', 'winstreak']) winrate = strutil.loads(winrate, ignoreException=True, execptionValue={'pt':0, 'wt':0}) try: winstreak = 0 if winstreak is None else int(winstreak) except: winstreak = 0 if winrate.get('pt', 0) > 20 and winstreak == 3: return True return False
def getGameInfo(userId, clientId): ftlog.debug('dizhu.getGameInfo->', userId, clientId) ukeys = getInitDataKeys() uvals = gamedata.getGameAttrs(userId, DIZHU_GAMEID, ukeys) uvals = list(uvals) values = getInitDataValues() for x in xrange(len(uvals)): if uvals[x] == None: uvals[x] = values[x] gdata = dict(zip(ukeys, uvals)) level = gdata['level'] gdata['nextexp'] = getGameUserNextExp(level) gdata['title'] = getGameUserTitle(level) gdata['referrerSwitch'] = dizhuconf.getReferrerSwitch() gdata['canSetReferrer'] = getCanSetReferrer(userId) gdata['skillScoreInfo'] = skillscore.score_info(userId) gdata['charm'] = userdata.getCharm(userId) gdata['chip'] = userchip.getUserChipAll(userId) gdata['dashifen'] = getDaShiFen(userId, clientId) ftlog.debug('dizhu.getGameInfo->', userId, clientId, gdata) return gdata
def get_kvs(cls, tasklet, uid, gid): ''' attrs = ['lastlogin', 'nslogin', 'play_game_count', 'win_game_count', 'draw_game_count', 'lose_game_count', 'bang_count', 'highest_lose_chip', 'highest_win_chip', 'highest_chip_record', 'day_win_game_count', 'day_win_sequence_count', 'day_max_win_sequence_count', 'big_pattern_history', 'best_pattern', 'online_records', 'guobiao_play_game_count', 'guobiao_win_game_count', 'guobiao_draw_game_count', 'guobiao_lose_game_count', 'guobiao_bang_count', 'guobiao_highest_lose_chip', 'guobiao_highest_win_chip', 'guobiao_highest_chip_record', 'win_sequence_count', 'max_win_sequence_count', 'guobiao_best_pattern', 'guobiao_online_records', 'max_degree_week_duration', 'max_degree_week_duration_ts', 'master_point', 'week_master_point', 'week_master_point_ts', 'day_play_game_count'] ''' attrs = [ 'win_sequence_count', 'max_win_sequence_count', 'guobiao_best_pattern' ] values = gamedata.getGameAttrs(uid, gid, attrs) for i, value in enumerate(values): if value is None: ftlog.debug(attrs[i], 'is None') values[i] = cls.get_default_value(attrs[i])[1] else: values[i] = cls.parse_content_from_redis(attrs[i], value) kvs = dict(zip(attrs, values)) cls.check_attrs_timestamp(tasklet, uid, gid, kvs) kvs['chip'] = userchip.getChip(uid) kvs['exp'] = userdata.getExp(uid) kvs['charm'] = userdata.getCharm(uid) if not kvs['chip']: kvs['chip'] = 0 if not kvs['exp']: kvs['exp'] = 0 if not kvs['charm']: kvs['charm'] = 0 return kvs
def getUserTotalPlayCount(cls, userId): winrate = gamedata.getGameAttrs(userId, DIZHU_GAMEID, ['winrate'], False)[0] winrate = strutil.loads(winrate, ignoreException=True, execptionValue={'pt': 0, 'wt': 0}) return winrate.get('pt', 0)
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 doInitTableUserData(userId, bigRoomId, tableId, isNextBuyin, buyinchip, isMatch=False): clientId = sessiondata.getClientId(userId) isSupportBuyin = dizhuconf.isSupportBuyin(clientId) exp, suaddress, susex, suname, sucoin, charm = userdata.getAttrs( userId, ['exp', 'address', 'sex', 'name', 'coin', 'charm']) sugold, slevel, swinrate, winchips, starid, winstreak = gamedata.getGameAttrs( userId, DIZHU_GAMEID, ['gold', 'level', 'winrate', 'winchips', 'starid', 'winstreak']) ftlog.debug('isSupportBuyin=', isSupportBuyin, 'userdata->', suaddress, susex, suname, sucoin, exp, charm) ftlog.debug('gamedata->', sugold, slevel, swinrate, winchips, starid) swinrate = strutil.loads(swinrate, ignoreException=True, execptionValue={ 'pt': 0, 'wt': 0 }) suchip = userchip.getChip(userId) buyin_tip = '' if not isSupportBuyin or isMatch: buyinMark = 0 buyin_chip = suchip else: buyinMark = 1 buyin_chip = userchip.getTableChip(userId, DIZHU_GAMEID, tableId) buyinconf = dizhuconf.getBuyInConf() if buyin_chip == buyinchip: if isNextBuyin: buyin_tip = buyinconf.get('tip_auto', '') else: buyin_tip = buyinconf.get('tip', '').format(BUYIN_CHIP=buyinchip) else: if suchip <= 0: if isNextBuyin: buyin_tip = buyinconf.get('tip_auto_all_next', '') else: buyin_tip = buyinconf.get('tip_auto_all', '') suchip = buyin_chip tbplaytimes, tbplaycount = treasurebox.getTreasureBoxState( userId, bigRoomId) try: if TYPlayer.isRobot(userId): supic, isBeauty = '', False else: supic, isBeauty = halluser.getUserHeadUrl(userId, clientId) except: supic, isBeauty = '', False slevel = _recoverUserAttr(slevel, int, 0) datas = {} datas['uid'] = userId datas['address'] = _recoverUserAttr(suaddress, unicode, '') datas['sex'] = _recoverUserAttr(susex, int, 0) datas['name'] = _recoverUserAttr(suname, unicode, '') datas['coin'] = _recoverUserAttr(sucoin, int, 0) datas['headUrl'] = '' datas['purl'] = supic datas['isBeauty'] = isBeauty datas['chip'] = suchip datas['buyinMark'] = buyinMark datas['buyinChip'] = buyin_chip datas['buyinTip'] = buyin_tip datas['exp'] = _recoverUserAttr(exp, int, 0) datas['gold'] = _recoverUserAttr(sugold, int, 0) datas['vipzuan'] = [] datas['tbc'] = tbplaycount datas['tbt'] = tbplaytimes datas['level'] = slevel datas['wins'] = swinrate.get('wt', 0) datas['plays'] = swinrate.get('pt', 0) datas['winchips'] = _recoverUserAttr(winchips, int, 0) datas['nextexp'] = dizhuaccount.getGameUserNextExp(slevel) datas['title'] = dizhuaccount.getGameUserTitle(slevel) datas['medals'] = _buildUserMedals() datas['skillScoreInfo'] = skillscore.score_info(userId) datas['charm'] = 0 if charm == None else _recoverUserAttr(charm, int, 0) datas['vipInfo'] = hallvip.userVipSystem.getVipInfo(userId) datas['starid'] = 0 if starid == None else _recoverUserAttr(starid, int, 0) datas['winstreak'] = 0 if winstreak == None else _recoverUserAttr( winstreak, int, 0) datas['gameClientVer'] = SessionDizhuVersion.getVersionNumber(userId) # TODO 查询用户增值位 datas['wearedItems'] = [] userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() timestamp = pktimestamp.getCurrentTimestamp() memberCardItem = userBag.getItemByKindId(hallitem.ITEM_MEMBER_NEW_KIND_ID) datas[ 'memberExpires'] = memberCardItem.expiresTime if memberCardItem else 0 item = userBag.getItemByKindId(hallitem.ITEM_CARD_NOTE_KIND_ID) cardNoteCount = 0 if item and not item.isDied(timestamp): cardNoteCount = max(1, item.balance(timestamp)) ftlog.debug('DizhuPlayer->userId=', userId, 'isSupportBuyin=', isSupportBuyin, 'cardNoteCount=', cardNoteCount, 'clientId=', clientId, 'data=', datas) return isSupportBuyin, cardNoteCount, clientId, datas
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 _calRankInfoData(userId, seatDeltaChip, winslam, windoubles): ftlog.debug('calRankInfoData->', userId, seatDeltaChip, winslam, windoubles) # 每周,城市赢金榜 if seatDeltaChip > 0 and dizhuconf.isUseTuyouRanking(): # 陌陌使用自己的排行榜 city_code = sessiondata.getCityZip(userId) city_index = city_locator.ZIP_CODE_INDEX.get(city_code, 1) rankingId = 110006100 + city_index hallranking.rankingSystem.setUserScore(str(rankingId), userId, seatDeltaChip) # 更新gamedata中的各种max和累积值 winchips, losechips, maxwinchip, weekchips, winrate, maxweekdoubles, slams, todaychips = gamedata.getGameAttrs( userId, DIZHU_GAMEID, [ 'winchips', 'losechips', 'maxwinchip', 'weekchips', 'winrate', 'maxweekdoubles', 'slams', 'todaychips' ], False) ftlog.debug('calRankInfoData->', winchips, losechips, maxwinchip, weekchips, winrate, maxweekdoubles, slams) winchips, losechips, maxwinchip, maxweekdoubles, slams = strutil.parseInts( winchips, losechips, maxwinchip, maxweekdoubles, slams) updatekeys = [] updatevalues = [] # 计算累计的输赢金币 if seatDeltaChip > 0: winchips = winchips + seatDeltaChip updatekeys.append('winchips') updatevalues.append(winchips) else: losechips = losechips + seatDeltaChip updatekeys.append('losechips') updatevalues.append(losechips) # 计算增加最大的赢取金币数 if seatDeltaChip > maxwinchip: updatekeys.append('maxwinchip') updatevalues.append(seatDeltaChip) # 计算增加每星期的累计赢取、输掉的金币数 weekchips = strutil.loads(weekchips, ignoreException=True) if weekchips == None or len(weekchips) != 2 or ( not 'week' in weekchips) or (not 'chips' in weekchips): weekchips = {'week': -1, 'chips': 0} weekOfYear = pktimestamp.formatTimeWeekInt() if weekOfYear != weekchips['week']: weekchips = {'week': weekOfYear, 'chips': seatDeltaChip} else: weekchips['chips'] = weekchips['chips'] + seatDeltaChip updatekeys.append('weekchips') updatevalues.append(strutil.dumps(weekchips)) # 计算增加每星期的累计赢取的金币数 if seatDeltaChip > 0: todaychips = strutil.loads(todaychips, ignoreException=True) if todaychips == None or len(todaychips) != 3 \ or (not 'today' in todaychips) or (not 'chips' in todaychips) or (not 'last' in todaychips) : todaychips = {'today': -1, 'chips': 0, 'last': 0} today = pktimestamp.formatTimeDayInt() if today != todaychips['today']: yesterdaychips = 0 if todaychips['today'] == pktimestamp.formatTimeYesterDayInt(): yesterdaychips = todaychips['chips'] todaychips = { 'today': today, 'chips': seatDeltaChip, 'last': yesterdaychips } else: todaychips['chips'] = todaychips['chips'] + seatDeltaChip updatekeys.append('todaychips') updatevalues.append(strutil.dumps(todaychips)) # 计算marsscore winchipsDelta = int(winchips) - int(losechips) winrate = strutil.loads(winrate, ignoreException=True, execptionValue={'wt': 0}) wintimes = int(winrate.get('wt', 0)) marsscore = winchipsDelta * 0.6 + wintimes * 200 * 0.4 if marsscore > 0: updatekeys.append('marsscore') updatevalues.append(marsscore) # 计算slams和maxweekdoubles if seatDeltaChip > 0: if winslam: updatekeys.append('slams') updatevalues.append(slams + 1) if maxweekdoubles < windoubles: updatekeys.append('maxweekdoubles') updatevalues.append(windoubles) if len(updatekeys) > 0: gamedata.setGameAttrs(userId, DIZHU_GAMEID, updatekeys, updatevalues) return 1
def upgradeGun(userId, protect, mode, byGift=False, upToLevel=0): """ 升级普通炮 """ def consume(items, level): """消耗升级所需道具""" _consumeList = [] for kindId, count in items.iteritems(): if int(kindId) == config.PURPLE_CRYSTAL_KINDID: _consumeList.extend( consumeBindOrNotBindItem(userId, config.BIND_PURPLE_CRYSTAL_KINDID, config.PURPLE_CRYSTAL_KINDID, count)) elif int(kindId) == config.YELLOW_CRYSTAL_KINDID: _consumeList.extend( consumeBindOrNotBindItem(userId, config.BIND_YELLOW_CRYSTAL_KINDID, config.YELLOW_CRYSTAL_KINDID, count)) else: _consume = {"name": int(kindId), "count": count} _consumeList.append(_consume) util.consumeItems(userId, _consumeList, "ITEM_USE", level) gunLevelKey = GameData.gunLevel if mode == CLASSIC_MODE else GameData.gunLevel_m gunLevel, level = gamedata.getGameAttrs(userId, FISH_GAMEID, [gunLevelKey, GameData.level]) if not gunLevel or gunLevel >= config.getMaxGunLevel(mode): return False nextGunLevel = config.getNextGunLevel(gunLevel, mode) if nextGunLevel == -1: ftlog.error("gunLevel error! userId =", userId, "gunLevel =", gunLevel, "mode =", mode) return False nextGunLevelConf = config.getGunLevelConf(nextGunLevel, mode) upgradeItemsConf = getUpgradeItemsConf(userId, nextGunLevel, mode=mode) returnRewards = None levelUpRewards = None if not byGift: if isEnough(userId, upgradeItemsConf): # 判断升级所需物品是否足够 if nextGunLevelConf["successRate"] >= 10000: # 是否100%成功 consume(upgradeItemsConf, level) # 消耗升级所需物品 code = 0 # 升级成功 else: if protect: # 是否使用五彩水晶 if isEnough( userId, nextGunLevelConf["protectItems"]): # 判断五彩水晶是否足够 consume(upgradeItemsConf, level) # 消耗升级所需物品 consume(nextGunLevelConf["protectItems"], level) # 消耗五彩水晶 code = 0 else: code = 99 # 五彩水晶物品不足 else: consume(upgradeItemsConf, level) # 消耗升级所需物品 randInt = random.randint(1, 10000) if randInt <= nextGunLevelConf["successRate"]: code = 0 else: randInt = random.randint(1, 10000) for item in nextGunLevelConf["returnItems"]: if item["probb"][0] <= randInt <= item["probb"][1]: returnRewards = [{ "name": item["kindId"], "count": item["count"] }] break code = 1 # 升级失败,返还道具 else: code = 99 # 升级所需物品不足 else: if upToLevel > gunLevel: code = 0 else: code = 1 if code == 0: # level += 1 # gunLevel += 1 # gamedata.setGameAttrs(userId, FISH_GAMEID, [GameData.level, GameData.gunLevel], [level, gunLevel]) # gunLevel += 1 if "levelRewards" in nextGunLevelConf and nextGunLevelConf[ "levelRewards"] > 0: levelUpRewards = [{ "name": config.CHIP_KINDID, "count": nextGunLevelConf["levelRewards"] }] gunLevel = nextGunLevel if not byGift else upToLevel gamedata.setGameAttr(userId, FISH_GAMEID, gunLevelKey, gunLevel) from newfish.game import TGFish from newfish.entity.event import GunLevelUpEvent event = GunLevelUpEvent(userId, FISH_GAMEID, level, gunLevel, mode) TGFish.getEventBus().publishEvent(event) bireport.reportGameEvent("BI_NFISH_GE_LEVEL_UP", userId, FISH_GAMEID, 0, 0, int(level), mode, 0, 0, [byGift, upToLevel, gunLevel], util.getClientId(userId)) mo = MsgPack() mo.setCmd("gun_up") # 升级普通炮 mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("level", level) mo.setResult("gunLevel", gunLevel) mo.setResult("gameMode", mode) mo.setResult("code", code) if returnRewards: util.addRewards(userId, returnRewards, "ASSEMBLE_ITEM", level) mo.setResult("returnRewards", returnRewards) if levelUpRewards: util.addRewards(userId, levelUpRewards, "ASSEMBLE_ITEM", level) mo.setResult("levelUpRewards", levelUpRewards) router.sendToUser(mo, userId) sendGunInfoMsg(userId, mode) # 发送普通炮信息 return code == 0
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