def _exchange(self, gameid, userid, actkey, exchangeid): info = self._exchanges.get(exchangeid) if not info: return {'result': 'fail', 'tip': "unknown productId"} buynum = self.get_exchange_buynum(userid, actkey, info) if buynum >= info['limitTimes']: return {'result': 'fail', 'tip': '兑换次数已满'} curtime = timestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(userid) try: userAssets.consumeContentItemList(gameid, info['costs'], False, curtime, "ACT_ITEM_EXCHANGE_COST", exchangeid) except: return {'result': 'fail', 'tip': '您的道具不足,快去获取道具吧'} daobase.executeUserCmd(userid, 'HINCRBY', actkey, self.FIELD_EXCHANGE_NUM.format(exchangeid), 1) assetList = userAssets.sendContent(gameid, info['content'], 1, True, timestamp.getCurrentTimestamp(), "ACT_ITEM_EXCHANGE_GAIN", exchangeid) response = self._query(userid, actkey) ftlog.info('TYActItemExchange._exchange gameId=', gameid, 'userId=', userid, 'activityId=', self.getid(), 'reward=', TYAssetUtils.buildContents(assetList), 'buynum=', buynum + 1, 'credit=', response['credit']) changeNames = TYAssetUtils.getChangeDataNames(assetList) datachangenotify.sendDataChangeNotify(gameid, userid, changeNames) response['result'] = 'ok' response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(assetList) return response
def gainAssistance(self, gameId, userId): ''' 领取江湖救急 @param gameId: gameId @param userId: userId @return: consumeCount, finalCount, sendChip ''' # 检查金币数量是否符合领取江湖救急的条件 userAllChip = pkuserchip.getUserChipAll(userId) assistanceChipUpperLimit = self._vipSystem.getAssistanceChipUpperLimit() if userAllChip >= assistanceChipUpperLimit: raise TYAssistanceChipTooMuchException(userAllChip, assistanceChipUpperLimit) timestamp = pktimestamp.getCurrentTimestamp() # 发放江湖救急金 userAssets = hallitem.itemSystem.loadUserAssets(userId) _assetKind, consumeCount, final = userAssets.consumeAsset(gameId, 'game:assistance', 1, timestamp, 'VIP_GOT_ASSISTANCE', 0) assistanceChip = self._vipSystem.getAssistanceChip() if consumeCount >= 1 and assistanceChip > 0: pkuserchip.incrChip(userId, gameId, assistanceChip, pkdaoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 'VIP_GOT_ASSISTANCE', 0, 0) ftlog.debug('TYUserVipSystemImpl.gainAssistance gameId=', gameId, 'userId=', userId, 'consumeCount=', consumeCount, 'assistanceChip=', assistanceChip) return consumeCount, final, assistanceChip
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 loadUserBenefits(self, gameId, userId, timestamp=None): ''' 加载用户的救济金数据 @return: TYUserBenefits ''' if timestamp is None: timestamp = pktimestamp.getCurrentTimestamp() # 加载用户的救济金配置 userBenefits = self._loadUserBenefits(gameId, userId, timestamp) if ftlog.is_debug(): ftlog.debug('TYBenefitsSystemImpl.loadUserBenefits before filter gameId=', gameId, 'userId=', userBenefits.userId, 'benefits=', userBenefits.__dict__) # 矫正救济金数据 p, extTimes, extChip = self._findFirstHasChipPrivileges(gameId, userBenefits) if p: userBenefits.extTimes = extTimes userBenefits.extSendChip = extChip userBenefits.privilege = p if ftlog.is_debug(): ftlog.debug('TYBenefitsSystemImpl.loadUserBenefits after filter gameId=', gameId, 'userId=', userBenefits.userId, 'benefits=', userBenefits.__dict__, 'privilege=', p, 'leftTimes=', userBenefits.leftTimes()) return userBenefits
def checkin(self, gameId, userId, timestamp=None): ''' @return: checkinOk, checkinDays ''' if timestamp is None: timestamp = pktimestamp.getCurrentTimestamp() status = self._dao.loadStatus(userId) checkinDays, canCheckin = self.calcCheckinState(status, timestamp) if canCheckin and self.isScriptDoGetReward(userId): canCheckin = 0 if ftlog.is_debug(): ftlog.debug('TYDailyCheckin.checkin gameId=', gameId, 'userId=', userId, 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'checkinDays=', checkinDays, 'canCheckin=', canCheckin, 'firstCheckinTime=', status.firstCheckinTime if status else None, 'lastCheckinTime=', status.lastCheckinTime if status else None) if not canCheckin: return 0, checkinDays if not status: status = TYDailyCheckinStatus(timestamp, timestamp) else: status.lastCheckinTime = timestamp if checkinDays == 0: status.firstCheckinTime = timestamp self._dao.saveStatus(userId, status) ftlog.debug('TYDailyCheckin.checkin ok gameId=', gameId, 'userId=', userId, 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')) return 1, checkinDays
def _canEnterGame(self, userId, gameId): """是否可进入游戏""" gameTime = gamedata.getGameAttrInt(userId, gameId, 'createTableTime') nowTime = pktimestamp.getCurrentTimestamp() ftlog.debug('Majiang2 game_handler _canEnterGame gameTile:', gameTime , ' nowTime:', nowTime) return (nowTime - gameTime) >= 5
def getAllReward(status): from hall.entity import hallitem count = 0 for invitation in status.inviteeMap.values(): if invitation.state == Invitation.STATE_ACCEPT: invitation.state = Invitation.STATE_REWARD count += 1 assetTupleList = [] if count > 0: _saveStatus(status) timestamp = pktimestamp.getCurrentTimestamp() if _conf.prizeRewardItem: ftlog.info('neituiguang.getAllReward userId=', status.userId, 'assetKindId=', _conf.prizeRewardItem.assetKindId, 'assetCount=', _conf.prizeRewardItem.count, 'invitationCount=', count) assetTuple = hallitem.itemSystem.loadUserAssets(status.userId).addAsset(HALL_GAMEID, _conf.prizeRewardItem.assetKindId, _conf.prizeRewardItem.count, timestamp, 'PROMOTE_REWARD', 0) assetTupleList.append(assetTuple) datachangenotify.sendDataChangeNotify(HALL_GAMEID, status.userId, TYAssetUtils.getChangeDataNames(assetTupleList)) return count, assetTupleList
def setUp(self): self.testContext.startMock() self.timestamp = pktimestamp.getCurrentTimestamp() self.pktimestampPatcher = patch('poker.util.timestamp.getCurrentTimestamp', self.getCurrentTimestamp) self.pktimestampPatcher.start() # self.neituiguangRemotePatcher = mock._patch_multiple('hall.servers.util.rpc.neituiguang_remote', # consumeAssets=self.userRemote.consumeAssets, # addAssets=self.userRemote.addAssets, # queryUserWeardItemKindIds=self.userRemote.queryUserWeardItemKindIds, # presentItemByUnitsCount=self.userRemote.presentItemByUnitsCount, # presentItem=self.userRemote.presentItem) self.testContext.configure.setJson('game:9999:map.clientid', clientIdMap, 0) self.testContext.configure.setJson('game:9999:item', item_conf, 0) self.testContext.configure.setJson('game:9999:products', products_conf, 0) self.testContext.configure.setJson('game:9999:store', store_template_conf, 0) self.testContext.configure.setJson('game:9999:store', store_default_conf, clientIdMap[self.clientId]) self.testContext.configure.setJson('game:9999:vip', vip_conf, 0) self.testContext.configure.setJson('game:9999:tasks', tasks_conf, 0) self.testContext.configure.setJson('game:9999:share', share_conf, 0) self.testContext.configure.setJson('game:9999:neituiguang2', neituiguang2, 0) hallitem._initialize() hallvip._initialize() hallshare._initialize() if not TestDailyCheckin.regTaskClass: TestDailyCheckin.regTaskClass=True halltask._registerClasses() neituiguang._initialize() neituiguangtask._initialize()
def doBindInviteCode(self, gameId, userId, clientId, inviteCode): """绑定上线推荐人ID""" try: hall_simple_invite.bindSimpleInviteRelationShip(inviteCode, userId) mo = MsgPack() mo.setCmd('invite_info') mo.setResult('action', 'bind_invite_code') mo.setResult('code', 0) mo.setResult('state', 1) mo.setResult('gameId', gameId) # 绑定成功,获取推荐人信息 name, pic = self.getUserNameAndPic(inviteCode) mo.setResult('bindName', name) mo.setResult('bindPic', pic) mo.setResult('bindUserId', inviteCode) # 校验自己的领奖状态 timestamp = pktimestamp.getCurrentTimestamp() inviteeStatus = hall_simple_invite.loadStatus(userId, timestamp) mo.setResult('rewardState', inviteeStatus.getRewardState(userId, gameId, clientId)) router.sendToUser(mo, userId) except Exception, e: if not isinstance(e, TYBizException): ftlog.error() ec, info = (e.errorCode, e.message) if isinstance(e, TYBizException) else (-1, '系统错误') ftlog.info('invite.statics eventId=', 'INPUT_INVITE_CODE', 'userId=', userId, 'clientId=', clientId, 'inviteCode=', inviteCode, 'result=', 'failed', 'ec=', ec, 'info=', info) router.sendToUser(self.makeErrorResponse('invite_info', 'bind_invite_code', ec, info), userId)
def setUserByInputType(self, gameId, inputType, userId, score, timestamp=None): ''' 更新所有能处理inputType和gameId的排行榜中指定用户的信息 @return: map<rankingId, rankingUser> ''' timestamp = timestamp or pktimestamp.getCurrentTimestamp() retMap = {} ftlog.debug('TYRankingSystemImpl.setUserByInputType gameId=', gameId, 'inputType=', inputType, 'userId=', userId, 'score=', score, 'timestamp=', timestamp) rankingDefineList = list(self._rankingDefineMap.values()) for rankingDefine in rankingDefineList: if rankingDefine.isSupport(gameId, inputType): rank = self._setUserByRankingDefine(rankingDefine, userId, score, timestamp) if rank >= 0: retMap[rankingDefine.rankingId] = TYRankingUser(userId, score, rank) ftlog.debug('TYRankingSystemImpl.setUserByInputType gameId=', gameId, 'inputType=', inputType, 'userId=', userId, 'score=', score, 'rankingDefine.gameIds=', rankingDefine.gameIds, 'rankingDefine.inputType=', rankingDefine.inputType, 'rank=', rank) else: ftlog.debug('TYRankingSystemImpl.setUserByInputType NotSupport gameId=', gameId, 'inputType=', inputType, 'userId=', userId, 'score=', score, 'rankingDefine.gameIds=', rankingDefine.gameIds, 'rankingDefine.inputType=', rankingDefine.inputType) return retMap
def encodePromote(cls, gameId, userId, clientId, promote): try: todotasks = TodoTaskHelper.makeTodoTasksByFactory(gameId, userId, clientId, promote.promotion.todotasks) tempRedPoint = False timestamp = pktimestamp.getCurrentTimestamp() ftlog.debug('promote.promotion.redPoint =', promote.promotion.redPoint) for d in promote.promotion.redPoint: if d: tempRedPoint = d.check(HALL_GAMEID, userId, clientId, timestamp) ret = { 'id': promote.promotion.promotionId, 'loc': promote.position.pos, 'name': promote.promotion.displayName, 'url': promote.promotion.url, 'defaultRes': promote.promotion.defaultRes, 'animate': promote.promotion.animate, 'redPoint': tempRedPoint, 'tasks': TodoTaskHelper.encodeTodoTasks(todotasks) } if promote.stopTime != -1: ret['endtime'] = datetime.fromtimestamp(promote.stopTime).strftime('%Y-%m-%d %H:%M:%S') return ret except: ftlog.error('PromotionHelper.encodePromote gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'promotionId=', promote.promotion.promotionId) return None
def _exchange(self, gameid, userid, actkey, exchangeid): info = self._exchanges.get(exchangeid) if not info: return {'result': 'fail', 'tip': "unknown productId"} buynum = self.get_exchange_buynum(userid, actkey, info) if buynum >= info['limitTimes']: return {'result': 'fail', 'tip': '兑换次数已满'} if not self.alter_user_credit(userid, actkey, -info['price']): return {'result': 'fail', 'tip': '您的积分不足'} daobase.executeUserCmd(userid, 'HINCRBY', actkey, self.FIELD_EXCHANGE_NUM.format(exchangeid), 1) userAssets = hallitem.itemSystem.loadUserAssets(userid) assetList = userAssets.sendContent(gameid, info['content'], 1, True, timestamp.getCurrentTimestamp(), "ACTIVITY_CREDIT_EXCHANGE", exchangeid) response = self._query(userid, actkey) ftlog.debug('TYActCreditExchange._exchange gameId=', gameid, 'userId=', userid, 'activityId=', self.getid(), 'reward=', TYAssetUtils.buildContents(assetList), 'buynum=', buynum + 1, 'credit=', response['credit']) changeNames = TYAssetUtils.getChangeDataNames(assetList) datachangenotify.sendDataChangeNotify(gameid, userid, changeNames) response['result'] = 'ok' response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(assetList) return response
def doSilverLottery(userId, gameId, clientId): ''' 银盘抽奖 ''' # 减少抽奖卡 timestamp = pktimestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(userId) _, consumeCount, _final = userAssets.consumeAsset(gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, 1, timestamp, 'ROULETTE_SILVER', 0) if consumeCount < 1: # 去金盘抽奖 result = doGetGoldUpdate(userId, gameId, clientId) from hall.servers.util.roulette_handler import rouletteHelper mo = rouletteHelper.makeRouletteQueryResponse(gameId, userId, clientId, 'roulette_goldUpdate', result) from poker.protocol import router router.sendToUser(mo, userId) return datachangenotify.sendDataChangeNotify(gameId, userId, 'item') # 抽奖 result = {} result['items'] = doRouletteSilverLottery(userId, gameId, clientId) # 判断下次的抽奖为金盘还是银盘 result['rouletteType'] = 'silver' result['cardNumber'] = userAssets.balance(gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, timestamp) # 返回信息,判断是否有抽奖卡,没有的话,改为金盘抽奖 ftlog.hinfo('doSilverLottery.userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'items=', result.get('items', []), 'rouletteType=', 1, 'number=', 1) sendGiftsToUser(userId, gameId, clientId, [result['items']]) return result
def doCancelCodeCheck(self, gameId, userId, clientId): ''' 取消code_check ''' try: timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) neituiguang.setInviter(status, 0) ftlog.hinfo('neituiguang.statics eventId=', 'CANCEL_INPUT_PRMOTE_CODE', 'userId=', userId, 'clientId=', clientId, 'result=', 'ok') mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'cancel_code_check') mo.setResult('code', 0) router.sendToUser(mo, userId) except Exception, e: if not isinstance(e, TYBizException): ftlog.error() ec, info = (e.errorCode, e.message) if isinstance(e, TYBizException) else (-1, '系统错误') ftlog.hinfo('neituiguang.statics eventId=', 'CANCEL_INPUT_PRMOTE_CODE', 'userId=', userId, 'clientId=', clientId, 'result=', 'failed') router.sendToUser(self.makeErrorResponse('cancel_code_check', ec, info), userId)
def queryUserItemTabsByGame(cls, gameId, userId, userBag=None): ret = [] if userBag is None: userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() timestamp = pktimestamp.getCurrentTimestamp() ret.append({'name': '', 'items': cls.encodeUserItemListByGame(gameId, userBag, timestamp)}) return ret
def queryUserItemList(cls, gameId, userId): ret = [] userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() itemList = userBag.getAllItem() timestamp = pktimestamp.getCurrentTimestamp() for item in itemList: if (not item.itemKind.singleMode or not item.itemKind.visibleInBag or not item.visibleInBag(timestamp)): continue itemId = cls.translateItemId(9999, gameId, item.itemKind.kindId) actionNameForUse = cls.translateUseActionName(item) if itemId != -1: balance = item.balance(timestamp) # 记牌器特殊处理,老版本客户端只认30这个itemId useGameId = 9999 if item.kindId == 2003: itemId = 30 useGameId = 6 data = { 'id': itemId, 'name': item.itemKind.displayName, 'count': '%s%s' % (balance, item.itemKind.units.displayName), 'desc': item.itemKind.desc, 'pic': item.itemKind.pic, 'canUse': True if actionNameForUse else False, 'num': balance, 'gameId': useGameId } ret.append(data) return ret
def exchange(self, userId, gameId, clientId, userBag): if ftlog.is_debug(): ftlog.debug('HallItemAutoExchange.exchange src:', self.itemSrc, ' dst:', self.itemDst, ' ratio:', self.ratio) timestamp = pktimestamp.getCurrentTimestamp() for cond in self.conditions: if not cond.check(gameId, userId, clientId, timestamp): return from hall.entity import hallitem srcItemKind = hallitem.itemSystem.findItemKind(self.itemSrc) dstItemKind = hallitem.itemSystem.findItemKind(self.itemDst) count = userBag.calcTotalUnitsCount(srcItemKind) if ftlog.is_debug(): ftlog.debug('HallItemAutoExchange.exchange delItemKind:', srcItemKind, ' count:', count) delCount = 0 newCount = 0 while count >= self.ratio: count -= self.ratio delCount += self.ratio newCount += 1 if delCount > 0: ftlog.info('HallItemAutoExchange.exchange delItemKind:', srcItemKind, 'delCount:', delCount, 'addItemKind:', dstItemKind, 'addCount:', newCount) userBag.forceConsumeUnitsCountByKind(gameId, srcItemKind, delCount, timestamp, 'ITEM_AUTO_EXCHANGE', 0) userBag.addItemUnitsByKind(gameId, dstItemKind, newCount, timestamp, 0, 'ITEM_AUTO_EXCHANGE', 0)
def getConfigForClient(self, gameId, userId, clientId): status = self.loadUserQuizStatus(userId) userAssets = hallitem.itemSystem.loadUserAssets(userId) chip = userAssets.balance(gameId, self._serverConf['chipAssetId'], pktimestamp.getCurrentTimestamp()) or 0 stopBetTime = self.stopBetTime.strftime(self.TIMEFMT) if self.stopBetTime else '' config = { 'stopBetTime': stopBetTime, 'bgImg': self._serverConf['bgImg'], 'gameId': self._serverConf['gameId'], 'chip': self.buildChipStr(chip), 'leftImg': self._serverConf['leftImg'], 'leftTitle': self._serverConf['leftTitle'], 'leftBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('l')}), 'leftOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['leftOdds']}), 'middleBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('m')}), 'middleOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['middleOdds']}), 'rightImg': self._serverConf['rightImg'], 'rightTitle': self._serverConf['rightTitle'], 'rightBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('r')}), 'rightOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['rightOdds']}), 'bet1': self._serverConf['bet1'], 'bet2': self._serverConf['bet2'], 'bet3': self._serverConf['bet3'] } self._clientConf['config'] = config return self._clientConf
def do_get_task_reward(self, gameId, userId, clientId, taskid): curtime = pktimestamp.getCurrentTimestamp() task_kind = halltask._taskSystem.findTaskKind(taskid) if not task_kind: return subsys = task_kind.taskUnit.subTaskSystem if not isinstance(subsys, (HallNewUserSubTaskSystem, HallChargeSubTaskSystem)): # 目前只有这俩走这里 return try: taskmodel = subsys.loadTaskModel(userId, curtime, clientId) if not taskmodel: raise TYTaskException(-1, "未知的任务:%s" % taskid) task = taskmodel.userTaskUnit.findTask(taskid) if not task: raise TYTaskException(-2, "未知的任务:%s" % taskid) asset_list = subsys.getTaskReward(task, curtime, 'FREE_TASK', taskid) router.sendToUser(self._build_task_info(gameId, userId, clientId), userId) rewardstr = TYAssetUtils.buildContentsString(asset_list) mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'get_task_reward') mo.setResult('code', 0) mo.setResult('info', '恭喜您获得了%s' % rewardstr) router.sendToUser(mo, userId) except TYTaskException, e: mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'get_task_reward') mo.setResult('code', e.errorCode) mo.setResult('info', e.message) router.sendToUser(mo, userId)
def buildID(cls, version, ntype, gameId, count, userId, idExtendInfo): ''' 生成红包ID 1)校验自推广红包,每人一个 2)其他类型红包暂时不校验 ''' global _redEnvelopeConfig # 取消推广红包每人一个的限制 # if ntype == TYRedEnvelopeMgr.RED_ENVELOPE_PROMOTE: # # 推广红包 # # pkgamedata.setGameAttr(userId, 9999, _buildModuleTipKey(tipModule, gameId, userId), count) # promoteEnvelopeID = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'promote_red_envelope') # if promoteEnvelopeID: # return False, _redEnvelopeConfig['tips']['promote_already_have']; otime = pktimestamp.getCurrentTimestamp() return True, '%s%s%s%s%s%s%s' % (version , strutil.tostr62(ntype, 2) , strutil.tostr62(gameId, 3) , strutil.tostr62(otime, 6) , strutil.tostr62(userId, 6) , strutil.tostr62(int(count % 1000), 2) , strutil.tostr62(idExtendInfo, 6) )
def _query(self, userid, actkey): products = {} for iid, info in self._exchanges.iteritems(): products[iid] = self.get_exchange_buynum(userid, actkey, info) return {'products': products, 'credit': hallitem.itemSystem.loadUserAssets(userid).balance(HALL_GAMEID, self.costAssetKindId, timestamp.getCurrentTimestamp())}
def getRanking(self, userId, rankingDefine): ''' @return: (TYRankingList, timestamp, rankingList) ''' timestamp = pktimestamp.getCurrentTimestamp() cacheRanking = self._cacheRankings.get(rankingDefine.rankingId) if (not cacheRanking or (timestamp - cacheRanking[1]) >= cacheRanking[0].rankingDefine.cacheTimes or pktimestamp.getDayStartTimestamp(timestamp) != pktimestamp.getDayStartTimestamp(cacheRanking[1])): cacheRanking = self._getRanking(rankingDefine, timestamp) if cacheRanking: self._cacheRankings[rankingDefine.rankingId] = cacheRanking if ftlog.is_debug(): ftlog.debug('RankTcpHandler.getRanking cache userId=', userId, 'rankingId=', rankingDefine.rankingId, 'rankingIssueNumber=', cacheRanking[0].issueNumber, 'rankingCycle=', ('[%s,%s)' % (cacheRanking[0].timeCycle.startTime, cacheRanking[0].timeCycle.endTime)), 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'data=', cacheRanking[2]) else: if rankingDefine.rankingId in self._cacheRankings: del self._cacheRankings[rankingDefine.rankingId] if ftlog.is_debug(): ftlog.debug('RankTcpHandler.getRanking remove userId=', userId, 'rankingId=', rankingDefine.rankingId) return cacheRanking
def testAddUserVipExp(self): hallvip.userVipSystem.addUserVipExp(self.gameId, self.userId, 100, 0, 0) userVip = hallvip.userVipSystem.getUserVip(self.userId) self.assertEqual(userVip.vipExp, 100) self.assertEqual(userVip.vipLevel.level, 1) hallvip.userVipSystem.gainUserVipGift(self.gameId, self.userId, 1) hallvip.userVipSystem.addUserVipExp(self.gameId, self.userId, 260, 0, 0) userVip = hallvip.userVipSystem.getUserVip(self.userId) self.assertEqual(userVip.vipExp, 360) self.assertEqual(userVip.vipLevel.level, 2) userAssets = hallitem.itemSystem.loadUserAssets(self.userId) _assetKind, count, final = userAssets.addAsset(self.gameId, 'game:assistance', 1, pktimestamp.getCurrentTimestamp(), 'TEST_ADJUST', 0) self.assertEqual(count, 1) self.assertEqual(final, 7) assistanceCount = hallvip.userVipSystem.getAssistanceCount(self.gameId, self.userId) self.assertEqual(assistanceCount, 7) consumeCount, finalCount, sendChip = hallvip.userVipSystem.gainAssistance(self.gameId, self.userId) self.assertEqual(consumeCount, 1) self.assertEqual(finalCount, 6) self.assertEqual(sendChip, hallvip.vipSystem.getAssistanceChip())
def addUserItemByKindId(cls, userId, gameId, clientId, kindId, count): timestamp = pktimestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(userId) calcGameId = strutil.getGameIdFromHallClientId(clientId) userAssets.addAsset(calcGameId, kindId, count, timestamp, 'MAJIANG_FANGKA_INVITE_REWARD', 0) datachangenotify.sendDataChangeNotify(gameId, userId, 'item') ftlog.debug('addUserItemByKindId userId:', userId, ' gameId:', gameId, 'kindId', kindId, 'count', count)
def doUpdate(userId, gameId, clientId): ''' 刷新信息,判断用户进入银盘抽奖还是金盘抽奖 ''' result = {} # 判断用户是否是第一次进入该功能,如果是,则赠送一张银盘抽奖卡 isFirstRoulette = pkgamedata.setnxGameAttr(userId, gameId, 'isFirstRoulette', 1) if isFirstRoulette: sendToUserALotteryCard(userId, gameId, clientId) # 拿到配置信息 tempResult = getConfForClient(userId, gameId, clientId) # 判断用户的抽奖卡张数,决定进入金盘抽奖还是银盘抽奖 if nowUserLotteryCardNumber(userId, gameId, clientId) or (not tempResult.get('gold_items', None)): # 银盘 result['rouletteType'] = 'silver' result['items'] = tempResult.get('silver_items', []) timestamp = pktimestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(userId) result['cardNumber'] = userAssets.balance(gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, timestamp) else: # 金盘 result['rouletteType'] = 'gold' result['isFirstCheck'] = doGetFisrtToGold(userId, gameId) result['items'] = tempResult.get('gold_items', []) return result
def onTimer(evt): global _prevProcessRankingTime timestamp = pktimestamp.getCurrentTimestamp() if (not _prevProcessRankingTime or timestamp - _prevProcessRankingTime > _processRankingInterval): _prevProcessRankingTime = timestamp rankingSystem.processRankings(timestamp)
def setUp(self): self.testContext.startMock() self.testContext.configure.setJson('game:9999:item', conf, 0) self.timestamp = pktimestamp.getCurrentTimestamp() self.pktimestampPatcher = patch('poker.util.timestamp.getCurrentTimestamp', self.getCurrentTimestamp) self.pktimestampPatcher.start() hallitem._initialize()
def check_reset(self, resettype, userid, actkey, data_field, time_field): oldtime = daobase.executeUserCmd(userid, 'HGET', actkey, time_field) curtime = timestamp.getCurrentTimestamp() if not oldtime or (resettype == 'day' and not timestamp.is_same_day(oldtime, curtime)): daobase.executeUserCmd(userid, 'HMSET', actkey, time_field, curtime, data_field, 0) return 0 return daobase.executeUserCmd(userid, 'HGET', actkey, data_field)
def doGetTaskReward(self, gameId, userId, taskId): ''' 获取活动奖励 ''' try: timestamp = pktimestamp.getCurrentTimestamp() taskModel = neituiguangtask.newUserTaskSystem.loadTaskModel(userId, timestamp) task = taskModel.userTaskUnit.findTask(taskId) if not task: raise TYBizException(-1, '未知的任务:%s' % (taskId)) expiresTime = self.calcTaskExpires(userId) if timestamp >= expiresTime: raise TYBizException(-1, '任务已经过期') if not userdata.getAttr(userId, 'bindMobile'): conf = neituiguang.getConf() TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskBindPhone(conf.pleaseBindPhone, '')) return assetList = neituiguangtask.newUserTaskSystem.getTaskReward(task, timestamp, 'PROMOTE_TASK', taskId) router.sendToUser(self.buildTaskInfoResponse(userId), userId) rewardStr = TYAssetUtils.buildContentsString(assetList) mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'get_task_reward') mo.setResult('code', 0) mo.setResult('info', '恭喜您获得了%s' % rewardStr) router.sendToUser(mo, userId) except TYBizException, e: router.sendToUser(self.makeErrorResponse('get_task_reward', e.errorCode, e.message), userId)
def _onUserLogin(event): timestamp = pktimestamp.getCurrentTimestamp() chip = userchip.getChip(event.userId) rankingSystem.setUserByInputType(event.gameId, TYRankingInputTypes.CHIP, event.userId, chip, timestamp) charm = userdata.getCharm(event.userId) rankingSystem.setUserByInputType(event.gameId, TYRankingInputTypes.CHARM, event.userId, charm, timestamp)
def _onUserCouponReceiveEvent(evt): if ftlog.is_debug(): ftlog.debug('user_coupon_details._onUserCouponReceiveEvent userId=', evt.userId, 'gameId=', evt.gameId, 'source=', evt.source, 'sourceDesc=', getSourceName(evt.source)) if evt.count > 0: clientId = sessiondata.getClientId(evt.userId) timestamp = pktimestamp.getCurrentTimestamp() status = loadUserStatus(evt.userId, clientId) status.addReceivedItem(evt.count, evt.source, timestamp) saveUserStatus(status)
def consume_content_item_list(uid, content): """通过FixedCount方式扣费""" content_item_list = content.getItems() timestamp = pktimestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(uid) assetList = userAssets.consumeContentItemList(DIZHU_GAMEID, content_item_list, False, timestamp, 'HALL_DUOBAO_COST', 0) if assetList: return True return False
def consumeAsset(gameId, userId, assetKindId, count, eventId, intEventParam): try: userAssets = hallitem.itemSystem.loadUserAssets(userId) _, consumeCount, final = userAssets.consumeAsset( gameId, assetKindId, count, pktimestamp.getCurrentTimestamp(), eventId, intEventParam) return consumeCount, final except: ftlog.error('user_remote.consumeAsset gameId=', gameId, 'userId=', userId, 'assetKindId=', assetKindId, 'count=', count, 'eventId=', eventId, 'intEventParam=', intEventParam) return 0, 0
def onInvitationAccepted(userId, invitee): try: if not userdata.checkUserData(userId): raise BadInviterException('用户不存在') timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) invitation = status.findInvitee(invitee) if invitation: neituiguang.onInvitationAccepted(status, invitation) return 0, None except NeituiguangException, e: return e.errorCode, e.message
def needSendBenefits(self, gameId, userId, timestamp=None): ''' 检查是否需要给用户发救济金 @return: True/False ''' if self._checkInNotSendGameIds(userId): return False if timestamp is None: timestamp = pktimestamp.getCurrentTimestamp() chip = pkuserchip.getUserChipAll(userId) userBenefits = self.loadUserBenefits(gameId, userId, timestamp) return userBenefits.hasLeftTimes() and chip < userBenefits.minChip
def getTaskContext(cls, userId, backendActivityNewActId): ''' 获得趣味任务上下文 ''' actobj = activitysystemnew.findActivity(backendActivityNewActId) if ftlog.is_debug(): ftlog.debug('QuweiTaskProxy.getTaskContext', 'userId=', userId, 'backendActivityNewActId=', backendActivityNewActId, 'actobj=', actobj) taskStatus = actobj.loadStatus(userId, pktimestamp.getCurrentTimestamp()) return taskStatus
def getTaskInfo(self, userId): ''' 新手任务信息,table_info协议调用 ''' if not isNewer(userId): return None kindId, completedList = self.getTaskStatus(userId) if len(completedList) >= self.taskKindCount \ or pktimestamp.getCurrentTimestamp() >= self.getDeadlineTimestamp(userId): return None curTask = self.getTaskByKindId(userId, kindId) if curTask is None: return None if ftlog.is_debug(): ftlog.debug('DizhuNewbieTaskSystem.getTaskInfo', 'userId=', userId, 'kindId=', kindId, 'curTask=', curTask, 'completelist=', completedList, caller=self) finalRewordConf = dizhuconf.getNewbieTaskConf().get('rewardContent', {}) finalRewordContent = TYContentRegister.decodeFromDict(finalRewordConf) tasksInfo = { 'details': self._encodeTaskList(userId, list(set(completedList + [curTask.kindId]))), 'final': self._encodeRewardContent(finalRewordContent), 'count': self.taskKindCount, 'deadline': max( self.getDeadlineTimestamp(userId) - pktimestamp.getCurrentTimestamp(), 0) } return tasksInfo
def handleEvent(cls, event): try: gameId = 6 userId = event.userId conf = dizhuconf.getActivityConf("vip_send") if not cls.dateCheck(gameId, userId, conf): cls.removeVipItems(gameId, userId, conf) return if not cls.gameCheck(userId, gameId): return vipLevel = int( hallvip.userVipSystem.getUserVip(userId).vipLevel.level) vipLevelLimit = conf.get("vip_level", 1) ftlog.debug('VipSend.handleEvent vipLevel=', vipLevel, 'vipLevelLimit=', vipLevelLimit, 'userId=', userId) if vipLevel >= vipLevelLimit: attrname = cls.getFlagAttr(conf.get('start_date', '2015-01-01')) is_send = gamedata.getGameAttr(userId, gameId, attrname) if is_send: return items = conf.get("item_send", []) timestamp = pktimestamp.getCurrentTimestamp() for item in items: contentItem = TYContentItem.decodeFromDict(item) userAssets = hallitem.itemSystem.loadUserAssets(userId) assetKind, _, _ = userAssets.addAsset( gameId, contentItem.assetKindId, contentItem.count, timestamp, 'DIZHU_VIP_SEND', 0) mail = conf.get("mail", "") if mail: pkmessage.sendPrivate(9999, userId, 0, mail) if assetKind.keyForChangeNotify: datachangenotify.sendDataChangeNotify( gameId, userId, [assetKind.keyForChangeNotify, 'message']) gamedata.setGameAttr(userId, gameId, attrname, 1) ftlog.debug('vipsend vipLevel=', vipLevel, 'vipLevelLimit=', vipLevelLimit, 'userId=', userId, "attrname=", attrname) except: ftlog.exception()
def loadUserData(self, actId): jstr = daobase.executeUserCmd( self.userId, 'hget', 'actwx:%s:%s' % (DIZHU_GAMEID, self.userId), actId) if jstr: jdict = strutil.loads(jstr) self.timestamp = jdict.get('timestamp', pktimestamp.getCurrentTimestamp()) self.isShareLogin = jdict.get('isShareLogin', 0) charmL = jdict.get('charmList', []) for charm in charmL: self.charmList.append(ShareCharmItem().fromDict(charm)) return self
def onMatchWinlose(cls, event): clientId = sessiondata.getClientId(event.userId) timestamp = pktimestamp.getCurrentTimestamp() if ftlog.is_debug(): ftlog.debug('FiveStarRate.onMatchWinlose userId=', event.userId, 'clientId=', clientId, 'signinUserCount=', event.signinUserCount, 'rank=', event.rank) # 玩家在比赛场获得名次时(100人以上的比赛获得前三名,或100人以下50人以上的比赛,获得第一名) if ((event.signinUserCount >= 100 and event.rank <= 3) or (event.signinUserCount >= 50 and event.signinUserCount < 100 and event.rank == 1)): winDesc = dizhuconf.getPublicConf('five_star_win_desc', '') hallfivestarrate.triggleFiveStarRateIfNeed(event.userId, clientId, timestamp, winDesc)
def executeChestAction(userId, order, actionType): """ 对背包中的宝箱执行行为 """ rewards = [] userBag, chestItem, openingChestItem, nextOpeningChestItem = getChestItemDetail(userId, order) if actionType in [ChestAction.NormalOpen, ChestAction.AtOnceOpen]: # [普通开启, 立即开启] if not chestItem: ftlog.info("openChest->not chestItem", userId) return 1, rewards if actionType == ChestAction.NormalOpen and chestItem.state != ChestState.Opened: ftlog.error("openChest->state error", userId) return 2, rewards if actionType == ChestAction.AtOnceOpen: # 立即开启宝箱,执行扣金币操作 chestTimeLeft = chestItem.beginTime + chestItem.totalTime - pktimestamp.getCurrentTimestamp() if chestTimeLeft > 0: needCoin = _needCoinAsOpenChest(chestItem.chestId, chestTimeLeft) chip = userchip.getChip(userId) if chip < needCoin: ftlog.debug("openChest->chip not enough") return 3, rewards util.addRewards(userId, [{"name": config.CHIP_KINDID, "count": -abs(needCoin)}], "BI_NFISH_ATONCE_OPEN_CHEST") # 修改下个宝箱的状态及时间 if chestItem == openingChestItem and nextOpeningChestItem: nextOpeningChestItem.state = ChestState.Opening nextOpeningChestItem.beginTime = pktimestamp.getCurrentTimestamp() userBag.updateItem(FISH_GAMEID, nextOpeningChestItem, pktimestamp.getCurrentTimestamp()) # 发放宝箱奖励 rewards = getChestRewards(userId, chestItem.chestId) deliveryChestRewards(userId, chestItem.chestId, rewards) # 删除已开启宝箱 userBag.removeItem(FISH_GAMEID, chestItem, pktimestamp.getCurrentTimestamp(), "ITEM_USE", actionType) # 打开宝箱事件 from newfish.game import TGFish from newfish.entity.event import OpenChestEvent event = OpenChestEvent(userId, FISH_GAMEID, chestItem.chestId, actionType) TGFish.getEventBus().publishEvent(event) elif actionType == ChestAction.Discard: # 丢弃宝箱 # 获得宝箱开启倒计时 chestTimeLeft = chestItem.beginTime + chestItem.totalTime - pktimestamp.getCurrentTimestamp() if chestTimeLeft > 0: # 修改下个宝箱的状态及时间 if chestItem == openingChestItem and nextOpeningChestItem: nextOpeningChestItem.state = ChestState.Opening nextOpeningChestItem.beginTime = pktimestamp.getCurrentTimestamp() userBag.updateItem(FISH_GAMEID, nextOpeningChestItem, pktimestamp.getCurrentTimestamp()) # 删除已丢弃宝箱 userBag.removeItem(FISH_GAMEID, chestItem, pktimestamp.getCurrentTimestamp(), "ITEM_USE", actionType) return 0, rewards
def setTableTasks(gameId, userId, taskIdList): ftlog.info('setTableTask gameId=', gameId, 'userId=', userId, 'taskIdList=', taskIdList) timestamp = pktimestamp.getCurrentTimestamp() taskModel = dizhutask.tableTaskSystem.loadTaskModel(userId, timestamp) taskModel.userTaskUnit.removeAllTask() for taskId in taskIdList: taskKind = taskModel.userTaskUnit.taskUnit.findTaskKind(taskId) if not taskKind: raise TYTaskException(-1, 'Not found taskKind %s' % (taskId)) task = taskKind.newTask(None, timestamp) taskModel.userTaskUnit.addTask(task) return [task.kindId for task in taskModel.userTaskUnit.taskList]
def _processTables(self): ftlog.info('TableController._processTables') timestamp = pktimestamp.getCurrentTimestamp() winloseTables = set() for table, t in self._tableMap.iteritems(): if timestamp - t > 1: winloseTables.add(table) for table in winloseTables: winloseList = self._randomUserWinlose(table) for winlose in winloseList: # tableId, ccrc, seatId, userId, deltaScore, isWin self.match.winlose(table.tableId, table.ccrc, winlose[1], winlose[0], winlose[2], winlose[3])
def buildTableInfoResp(self, seat, isRobot): mp = super(DizhuTableProtoFriend, self).buildTableInfoResp(seat, isRobot) if self.tableCtrl._preDisbind: mp.setResult('disbind', { 'reqSeatId':self.tableCtrl._preDisbindSeat.seatId, 'states':self.tableCtrl._preDisbindSeatState[:], 'optime':max(0, self.tableCtrl._preDisbindExpires - pktimestamp.getCurrentTimestamp()) }) mp.setResult('ftInfo', self.buildFTInfo()) mp.setResult('results', self.tableCtrl.results or []) dailyPlayCount = new_table_remote.doGetUserDailyPlayCount(seat.userId, DIZHU_GAMEID) mp.setResult('dailyPlay', dailyPlayCount) return mp
def sendDailyPlayTimesWinReward(userId, roomId, clientId, tableId, assetKindId, count): try: userAssets = hallitem.itemSystem.loadUserAssets(userId) _, addCount, final = userAssets.addAsset( DIZHU_GAMEID, assetKindId, count, pktimestamp.getCurrentTimestamp(), 'DDZ_GAMEWIN_REWARD', roomId) return addCount, final except: ftlog.error('new_table_remote.sendDailyPlayTimesWinReward gameId=', DIZHU_GAMEID, 'userId=', userId, 'assetKindId=', assetKindId, 'count=', count) return 0, 0
def addInvitee(userId, invitee, accepted): try: if not userdata.checkUserData(userId): raise BadInviterException('用户不存在') timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) if not status.findInvitee(invitee): if status.inviteeCount: pass neituiguang.addInvitee(status, invitee, accepted) return 0, None except NeituiguangException, e: return e.errorCode, e.message
def consume_user_item(uid, item_id, count, product_id, issue_no): """扣某个道具""" timestamp = pktimestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(uid) _, consume_count, final = userAssets.consumeAsset(DIZHU_GAMEID, item_id, count, timestamp, 'HALL_DUOBAO_COST', int(product_id), int(issue_no)) if consume_count < consume_count: return False return True
def queryAlarm(userId): alarms = AlarmDao.load(userId) if not alarms: return mo = MsgPack() mo.setCmd('game') mo.setAction('alarmList') mo.setResult('gameId', 9999) mo.setResult('userId', userId) mo.setResult('curtime', timestamp.getCurrentTimestamp()) mo.setResult('alarms', alarms) router.sendToUser(mo, userId) return mo
def checkIsDownload(self, userId, gameId): userAssets = hallitem.itemSystem.loadUserAssets(userId) timestamp = pktimestamp.getCurrentTimestamp() cardNum = userAssets.balance(gameId, hallitem.ASSET_ITEM_CUSTOM_SKIN_CARD_ID, timestamp) if cardNum > 0: #存在换肤卡 self.isDownload = True else: #不存在换肤卡 self.isDownload = False self.isDownload = True
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 onTimer(event): """排行榜的定时器""" global _prevProcessRankingTime timestamp = pktimestamp.getCurrentTimestamp() if (not _prevProcessRankingTime or timestamp - _prevProcessRankingTime > _processRankingInterval): # # 隔天清理竞赛活动过期数据 # if _prevProcessRankingTime and util.getDayStartTimestamp(timestamp) != util.getDayStartTimestamp(_prevProcessRankingTime): # from newfish.entity.fishactivity import competition_activity # competition_activity.clearCompActExpireData() _prevProcessRankingTime = timestamp processRankings() addRobotToGrandPrix()
def getConfigForClient(self, gameId, userId, clientId): status = self.loadUserQuizStatus(userId) userAssets = hallitem.itemSystem.loadUserAssets(userId) chip = userAssets.balance(gameId, self._serverConf['chipAssetId'], pktimestamp.getCurrentTimestamp()) or 0 stopBetTime = self.stopBetTime.strftime( self.TIMEFMT) if self.stopBetTime else '' config = { 'stopBetTime': stopBetTime, 'bgImg': self._serverConf['bgImg'], 'gameId': self._serverConf['gameId'], 'chip': self.buildChipStr(chip), 'leftImg': self._serverConf['leftImg'], 'leftTitle': self._serverConf['leftTitle'], 'leftBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('l')}), 'leftOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['leftOdds']}), 'middleBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('m')}), 'middleOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['middleOdds']}), 'rightImg': self._serverConf['rightImg'], 'rightTitle': self._serverConf['rightTitle'], 'rightBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('r')}), 'rightOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['rightOdds']}), 'bet1': self._serverConf['bet1'], 'bet2': self._serverConf['bet2'], 'bet3': self._serverConf['bet3'] } self._clientConf['config'] = config return self._clientConf
def presentItemByUnitsCount(gameId, userId, fromUserId, kindId, count, receiveMail): itemKind = hallitem.itemSystem.findItemKind(kindId) if not itemKind: return False userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() userBag.addItemUnitsByKind(gameId, itemKind, count, pktimestamp.getCurrentTimestamp(), fromUserId, 'ACCEPT_PRESENT_ITEM', fromUserId) if receiveMail: pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, receiveMail) datachangenotify.sendDataChangeNotify(gameId, userId, 'item') return True
def _clearReplayRound(self): self._curReplayyRound = None toRemove = [] for roundId, (gameRound, _) in self._gameRoundMap.iteritems(): delta = pktimestamp.getCurrentTimestamp() - ( gameRound.gameOverTimestamp or 0) # TODO if delta > 600: toRemove.append(roundId) for roundId in toRemove: ftlog.info('DizhuTable._clearReplayRound removeRound roomId=', self.roomId, 'tableId=', self.tableId, 'roundId=', roundId) del self._gameRoundMap[roundId]
def registerAlarm(userId, pluginId, deadline, notice, extparam=None): """ :param userId: 玩家id :param pluginId: 插件id :param deadline: 到期时间,距1970.1.1零点的秒数 :param notice: 通知文本 :param extparam: 可json化的字典,传入自定义参数,诸如roomId :return: 闹钟id,0为异常 """ if deadline <= timestamp.getCurrentTimestamp(): return 0 aid = AlarmDao.save(userId, pluginId, deadline, notice, extparam) queryAlarm(userId) return aid
def _doView(cls, userId, gameId, clientId, videoId, timestmap=None): msg = MsgPack() msg.setCmd('dizhu') msg.setResult('action', 'replay_view') msg.setResult('gameId', gameId) msg.setResult('userId', userId) try: timestamp = timestmap or pktimestamp.getCurrentTimestamp() replay = replay_service.view(videoId, userId, timestamp) msg.setResult('video', {'views':replay.viewsCount, 'likes':replay.likesCount, 'url':''}) msg.setResult('videoUrl', replay_service.buildVideoDataUrl(videoId)) except TYBizException, e: msg.setResult('code', e.errorCode) msg.setResult('info', e.message)
def _doListMine(cls, userId, gameId, clientId): msg = MsgPack() msg.setCmd('dizhu') msg.setResult('action', 'replay_mine_list') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('shareMsg', replay_service.getShareDesc(userId, gameId, clientId)) timestamp = pktimestamp.getCurrentTimestamp() lastView = replay_service.getLastView(userId) replays = replay_service.getMine(userId, timestamp) msg.setResult('videos', cls.encodeReplaysForMine(userId, replays, lastView)) router.sendToUser(msg, userId) replay_service.setLastView(userId, timestamp) return msg
def _onUserReceivedCouponEvent(event): if ftlog.is_debug(): ftlog.debug('hall_red_packet_exchange._onUserReceivedCouponEvent', 'userId=', event.userId, 'count=', event.count, 'source=', event.source) if event.count > 0: clientId = sessiondata.getClientId(event.userId) timestamp = pktimestamp.getCurrentTimestamp() status = loadUserStatus(event.userId, clientId, timestamp) status.addReceivedItem(event.count, event.source, timestamp) saveUserStatus(status) datachangenotify.sendDataChangeNotify(HALL_GAMEID, event.userId, 'rpexchange')
def __init__(self, userId, initLandlordCards, initFarmerCards, isHelp=False): self.userId = userId self.initLandlordCards = initLandlordCards self.initFarmerCards = initFarmerCards self.landlordCards = [card for card in initLandlordCards] self.farmerCards = [card for card in initFarmerCards] self.reply = [] self.lastFarmerMove = [] # 转换后的对应的point值 self.currentRoundNum = EndgameHelper.getUserCurrentRoundData(userId).roundNum self.maxRoundNum = 1 self.state = self.STATE_PLAYING self.historyRoundData = None self.expireTimeStamp = pktimestamp.getCurrentTimestamp() + 3600 self.isHelp = isHelp
def _doFTBind(self, ftTable): self._doTableClear() self._ftTable = ftTable interval = ftTable.expires - pktimestamp.getCurrentTimestamp() self.notStartGameTimer.setup(self.runConfig.notStartTimeout, 'FT_NOT_START_TIMEOUT', {}) self.forceDisbindTimer.setup(interval, 'FT_FORCE_DISBIND_TIMEOUT', {}) ftlog.info( 'DizhuFriendTable._doFTBind', 'tableId=', self.tableId, 'ftId=', ftTable.ftId, 'nRound=', ftTable.nRound, 'canDouble=', ftTable.canDouble, 'playMode=', ftTable.playMode, 'goodCard=', ftTable.goodCard, 'expires=', datetime.fromtimestamp( ftTable.expires).strftime('%Y-%m-%d %H:%M:%S'))