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 recommendProductIfCan(self, gameId, userId): # 没有配置推荐商品,则不推荐 payOrder = Tool.dictGet(self._clientConf, 'config.server.payOrder') if not payOrder: return False clientId = sessiondata.getClientId(userId) product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder) ftlog.debug('FunAct.recommendProductIfCan:', 'userId=', userId, 'product=', product) # 没有在货架中找到商品 if not product: return False translateMap = { 'product.displayName': product.displayName, 'product.price': product.price, 'count': payOrder.get('contains', {}).get('count', 0) } desc = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipDesc') note = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipNote') desc = strutil.replaceParams(desc, translateMap) note = strutil.replaceParams(note, translateMap) todotask = TodoTaskLessBuyOrder(desc, None, note, product) TodoTaskHelper.sendTodoTask(gameId, userId, todotask) return True
def sendBuyDiamondTodoTask(userId, gameId, clientId, pay_order): """ 幸运大抽奖,钻石购买 @param pay_order 挑选商品模板 """ if not TYPlayer.isHuman(userId): return product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, pay_order) if not product: ftlog.error('userId =', userId, 'clientId =', clientId, 'pay_order =', pay_order, 'can not find suitable product!') return try: product = product.clone() except: product = strutil.cloneData(product) desc = u'您的钻石不够哦~\n现在' + unicode(product.price) + u'元立得' + unicode( product.priceDiamond) + u'钻石!' product.content.desc = str(product.priceDiamond) + '钻石' client_ver = sessiondata.getClientIdVer(userId) if client_ver < 3.74: # 客户端bug,小于3.74的版本转换一下 product.priceDiamond = product.price todotasks = TodoTaskOrderShow.makeByProduct(desc, '', product) TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
def triggleFiveStarRateIfNeed(userId, clientId, timestamp, desc): clientConf = hallconf.getFiveStarClientConf(clientId) if clientConf.get('disable', 0): if ftlog.is_debug(): ftlog.debug('fivestarrate.triggleFiveStarRateIfNeed userId=', userId, 'clientId=', clientId, 'timestamp=', timestamp, 'desc=', desc, 'clientConf=', clientConf) return False, None ver, channelName = _parseClientId(clientId) channel = _channels.get(channelName) if ftlog.is_debug(): ftlog.debug('fivestarrate.triggleFiveStarRateIfNeed userId=', userId, 'clientId=', clientId, 'timestamp=', timestamp, 'desc=', desc, 'channelName=', channelName, 'channel=', channel) if channel: fsRate = _loadFiveStarRate(userId, channel) if _canPopFiveStarRate(userId, ver, fsRate, timestamp): if 'appendDesc' in channel and _canSendPrize(channel): desc += "\n" + channel['appendDesc'] todotask = TodoTaskPopFiveStarWnd(desc, channel['rateUrl']) TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, todotask) fsRate.popTime = timestamp _saveFiveStarRate(userId, fsRate) ftlog.debug('fivestarrate.triggleFiveStarRateIfNeed userId=', userId, 'clientId=', clientId, 'timestamp=', timestamp, 'desc=', desc, 'channelName=', channelName, 'channel=', channel, 'rateUrl=', channel['rateUrl']) return True, todotask return False, None
def doCheckout(self, gameId, userId, clientId, freeItemId): """ { "cmd": "game", "params": { "action": "free_checkout", "userId": 10856, "gameId": 9999, "freeItemId": 1 } } """ if freeItemId == FREEITEMID_NEWCHECKIN: from hall.entity.newcheckin import clientReqCheckin clientReqCheckin(userId,clientId,gameId) return timestamp = pktimestamp.getCurrentTimestamp() freeList = hallfree.getFree(gameId, userId, clientId, timestamp) free = FreeHelper.getFreeById(freeList, freeItemId) if free: curState = FreeHelper.getCurStateOfFreeItem(gameId, userId, clientId, free, timestamp) if curState: todotasks = TodoTaskHelper.makeTodoTasksByFactory(gameId, userId, clientId, curState.todotaskList) if todotasks: TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
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 _doChangeNameTry(self, userId, clientId, newName): # renameConf = hallconf.getClientRenameConf(clientId) # if (renameConf # and not renameConf.get('containsSensitive', 1) # and keywords.isContains(newName)): # info = TodoTaskShowInfo(hallrename.stringRenameContainsSensitive) # return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, info) code, info = hallrename.tryRename(HALL_GAMEID, userId, newName) if ftlog.is_debug(): ftlog.debug('hallrename._doChangeNameTry->', code, info) if code == -3: # name not changed !! pass elif code == -2: # 没有改名卡 info = TodoTaskShowInfo(hallrename.stringRenameCardRequired, True) if hallrename.payOrder: product, _ = hallstore.findProductByPayOrder(HALL_GAMEID, userId, clientId, hallrename.payOrder) if product: info.setSubCmd(TodoTaskPayOrder(product)) return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, info) elif code == 0: # 改名成功 return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip(hallrename.stringRenameSuccessed)) else: # SDK改名失败 return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip(info))
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 _changeUserBehaviourInfo(userId, ret, behaviourConf): try: reward = behaviourConf.get('reward') if behaviourConf else None if not reward: return ret['type'] = BEHAVIOUR_TYPE_REWARDED daobase.executeUserCmd(userId, 'HSET', 'userBehaviour:6:' + str(userId), 'info', strutil.dumps(ret)) mailStr = behaviourConf.get('mail', '幸运女神的眷顾使你获得了奖励') contentItems = TYContentItem.decodeList(reward) assetList = dizhu_util.sendRewardItems(userId, contentItems, mailStr, 'USER_BEHAVIOUR_REWARD', userId) datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, mailStr) # 发奖弹窗 rewardsList = [] for assetItemTuple in assetList: assetItem = assetItemTuple[0] reward = {} reward['name'] = assetItem.displayName reward['pic'] = assetItem.pic reward['count'] = assetItemTuple[1] rewardsList.append(reward) reward_task = TodoTaskShowRewards(rewardsList) TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, reward_task) ftlog.info('userBehaviour.sendReward userId=', userId, 'reward=', [(atp[0].kindId, atp[1]) for atp in assetList]) except Exception, e: ftlog.warn('_changeUserBehaviourInfo userId=', userId, 'ret=', ret, 'err=', e)
def enterFriendTable(userId, gameId, clientId, ftId): """进入自建桌""" if ftlog.is_debug(): ftlog.debug('hall_friend_table.enterFriendTable userId:', userId, ' pluginId:', gameId, ' clientId:', clientId, ' ftId:', ftId) pluginId = queryFriendTable(ftId) if not pluginId: TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip('该房间不存在')) return if TYPlayer.isRobot(userId): isValidPluginId = True else: isValidPluginId = False from hall.entity import hallgamelist2 template = hallgamelist2.getUITemplate(gameId, userId, clientId) for version in template.versionList: if pluginId == version.game.gameId: isValidPluginId = True break if not isValidPluginId: TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip('该安装包不支持此房间号所对应的玩法')) return ftlog.info('hall_friend_table.enterFriendTable userId:', userId, ' lead to pluginId:', pluginId) pluginId = int(pluginId) TYGame(pluginId).enterFriendTable(userId, gameId, clientId, ftId)
def _doChangeNameTry(self, userId, clientId, newName): # renameConf = hallconf.getClientRenameConf(clientId) # if (renameConf # and not renameConf.get('containsSensitive', 1) # and keywords.isContains(newName)): # info = TodoTaskShowInfo(hallrename.stringRenameContainsSensitive) # return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, info) code, info = hallrename.tryRename(HALL_GAMEID, userId, newName) if ftlog.is_debug(): ftlog.debug('hallrename._doChangeNameTry->', code, info) if code == -3: # name not changed !! pass elif code == -2: # 没有改名卡 info = TodoTaskShowInfo(hallrename.stringRenameCardRequired, True) if hallrename.payOrder: product, _ = hallstore.findProductByPayOrder( HALL_GAMEID, userId, clientId, hallrename.payOrder) if product: info.setSubCmd(TodoTaskPayOrder(product)) return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, info) elif code == 0: # 改名成功 return TodoTaskHelper.sendTodoTask( HALL_GAMEID, userId, TodoTaskPopTip(hallrename.stringRenameSuccessed)) else: # SDK改名失败 return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip(info))
def processInvitees(self, enterParam, note, invitees, userId, gameId): ''' 邀请好友牌桌游戏 invitees - 被邀请者 ''' if not invitees: return uds = userdata.getAttrs(userId, ['name']) # 检查是否在线 for invitee in invitees: # invitee - 被邀请者 state = onlinedata.getOnlineState(invitee) if state: # 在线,则进行下一步操作 ids = userdata.getAttrs(invitee, ['name']) _, clientVer, _, _ = sessiondata.getClientIdInfo(invitee) if clientVer < 3.77: # 版本号小于3.77,则提示升级 TodoTaskHelper.sendTodoTask(gameId, invitee, TodoTaskPopTip(note + ' 请升级至新版本与好友 ' + uds[0] + ' 一起玩耍!')) TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskPopTip('您的好友 ' + ids[0] + ' 版本较低,提醒他升级到最新版本一起玩耍吧!')) else: # 判断是否在同一牌桌上 if self.isInSameTable(userId, invitee): TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskPopTip('您的好友 ' + ids[0] + ' 正在跟您一起游戏呢')) else: # 版本号大于3.77,则发送邀请 TodoTaskHelper.sendTodoTask(gameId, invitee, TodoTaskInviteToGame(userId, note, enterParam)) else: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskPopTip('您的好友当前不在线')) ftlog.debug('您的好友当前不在线')
def _onEnterRoomFailed(cls, msg, checkResult, userId, gameId, clientId, roomId=0): '''进入房间失败回调函数''' ftlog.warn("|userId, reason, roomId:", userId, checkResult, roomId, caller=cls) # 调用最小房间金币不够充值提醒的todotask if not roomId: roomId = msg.getParam('candidateRoomId', 0) if checkResult == TYRoom.ENTER_ROOM_REASON_LESS_MIN or checkResult == 104: from hall.entity import hallproductselector product, _ = hallproductselector.selectLessbuyProduct( gameId, userId, clientId, roomId) if product: from hall.entity.todotask import TodoTaskOrderShow todotask = TodoTaskOrderShow.makeByProduct( "金币不够啦,买一个超值礼包吧!", "", product) if todotask: TodoTaskHelper.sendTodoTask(gameId, userId, todotask) mo = MsgPack() mo.setCmd('quick_start') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setError(checkResult, '进入房间失败,请稍后重试') router.sendToUser(mo, userId)
def sendShareForWXRedEnvelope(userId, record, item): try: action = item.itemKind.findActionByName('exchange') from hall.entity.hallitem import TYItemActionExchange if isinstance( action, TYItemActionExchange) and action.isWechatRedPack(): # 微信红包 from poker.util import strutil from poker.entity.dao import sessiondata clientId = sessiondata.getClientId(userId) _, cVer, _ = strutil.parseClientId(clientId) if cVer >= 3.90: from hall.entity import hallshare gameId = strutil.getGameIdFromHallClientId(clientId) shareId = hallshare.getShareId('wxRedEnvelope', userId, gameId) share = hallshare.findShare(shareId) if share: todotask = share.buildTodotask(HALL_GAMEID, userId, 'wxRedEnvelope') if todotask: from hall.entity.todotask import TodoTaskHelper TodoTaskHelper.sendTodoTask(gameId, userId, todotask) except: ftlog.error('sendShareForWXRedEnvelope', 'userId=', userId, 'exchangeId=', record.exchangeId, 'itemId=', item.itemId, 'itemKindId=', item.kindId)
def _doSit(self, msg, userId, seatId, clientId, checkGameStart=True): selectedRoomOptions = msg.getParam("selectedRoomOptions") ftId = msg.getParam("ftId") if ftlog.is_debug(): ftlog.debug(self._baseLogStr("<<", userId), "|selectedRoomOptions, ftId, self.cMaxSeatNum:", selectedRoomOptions, ftId, self.cMaxSeatNum, caller=self) if selectedRoomOptions: self._refreshCustomConf(selectedRoomOptions) self.firstPlayerId = userId # 房主 self.ftId = ftId # 6位自建号 self.createTime = int(time.time()) ftlog.info(self._baseLogStr("_doSit <<", userId), "|selectedRoomOptions, ftId, self.cMaxSeatNum:", selectedRoomOptions, ftId, self.cMaxSeatNum, caller=self) result = super(DiFangCustomTable, self)._doSit(msg, userId, seatId, clientId) if result["reason"] == TYRoom.ENTER_ROOM_REASON_TABLE_FULL: tip = u"您好, 牌桌已满。" TodoTaskHelper.sendTodoTask(self.gameId, userId, TodoTaskShowInfo(tip, True)) return result if result["reason"] != TYRoom.ENTER_ROOM_REASON_OK: return result # 坐下成功, 人满后检查开桌 if ftlog.is_debug(): ftlog.debug(self._baseLogStr(">>", userId), "|self.playersNum, self.cMaxSeatNum:", self.playersNum, self.cMaxSeatNum, caller=self) if selectedRoomOptions: for _ in range(self.cMaxSeatNum - self.playersNum): self.sendRobotNotifyCallUp(None) if self.gamePlay.isWaitingState( ) and checkGameStart and self.playersNum == self.cMaxSeatNum: func = functools.partial(self.gamePlay.doActionCheckStartGame) msgPackParams = {"seatId": result["seatId"] - 1} self.callLaterFunc(0, func, userId, timer=None, msgPackParams=msgPackParams) # 需要异步锁桌子 return result
def sendWinBuyTodotask(userId, clientId, bigRoomId): from hall.entity import hallpopwnd from hall.entity.todotask import TodoTaskHelper todotask = hallpopwnd.makeTodoTaskWinBuy(DIZHU_GAMEID, userId, clientId, bigRoomId) if todotask: todotask.setParam('delay', 3) TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, todotask)
def _doItemActionUnsupportedExchange(self, gameId, userId, clientId, itemId, params): todotaskD = self.UNSUPPORTED_TODOTASK_PC if self._isNotPCorMAC( clientId) else self.UNSUPPORTED_TODOTASK todotaskFac = TodoTaskRegister.decodeFromDict(todotaskD) if todotaskFac: todotask = todotaskFac.newTodoTask(gameId, userId, clientId) TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
def enterFriendTable(self, userId, gameId, clientId, ftId): todotask = TodoTaskEnterGameNew(DIZHU_GAMEID, { 'type':'game', 'pluginParams':{ 'gameType':9, 'ftId':ftId, 'action':'enter' } }) TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, todotask)
def on_praise_friend(cls, gameId, uid, clientId, mo): code = mo.getResult('code', 0) # vip = mo.getResult('vip') if code == 0: friend_uid = int(mo.getResult('friend_uid')) nick_name = mo.getResult('nick_name') friend_nick_name = mo.getResult('friend_nick_name') my_add_charm = mo.getResult('my_add_charm') friend_add_charm = mo.getResult('friend_add_charm') my_charm = mo.getResult('my_charm') friend_charm = mo.getResult('friend_charm') msg1 = '给"' + friend_nick_name + '"点赞获得' + str(my_add_charm) + '个魅力值' msg2 = '"' + nick_name + '"给您点赞获得' + str(friend_add_charm) + '个魅力值' from poker.entity.biz.message import message message.send(gameId, message.MESSAGE_TYPE_SYSTEM, int(uid), msg1) message.send(gameId, message.MESSAGE_TYPE_SYSTEM, int(friend_uid), msg2) ftlog.debug('on praise friend.... ' + msg1) ftlog.debug('on praise friend.... ' + msg2) datachangenotify.sendDataChangeNotify(gameId, uid, 'charm') from hall.entity.hallranking import rankingSystem, TYRankingInputTypes timestamp = pktimestamp.getCurrentTimestamp() rankingSystem.setUserByInputType(gameId, TYRankingInputTypes.CHARM, uid, my_charm, timestamp) rankingSystem.setUserByInputType(gameId, TYRankingInputTypes.CHARM, friend_uid, friend_charm, timestamp) # 历史获赞次数 history_praised_num = gamedata.incrGameAttr(friend_uid, gameId, 'history_praised_num', 1) mo.setResult('friend_history_praised_num', history_praised_num) if code != 2: return from hall.entity.todotask import TodoTaskPayOrder, TodoTaskShowInfo from hall.entity.todotask import TodoTaskHelper from hall.entity import hallvip, hallitem user_vip = hallvip.userVipSystem.getUserVip(uid) delta_exp = user_vip.deltaExpToNextLevel() product, _ = hallstore.findProductByContains(gameId, uid, clientId, ['coin'], None, hallitem.ASSET_CHIP_KIND_ID, delta_exp * 1000) pay_order = TodoTaskPayOrder(product) if user_vip == 0: msg = '点赞次数已达今日上限,开通VIP可提高点赞次数上限获得更多福利哦~' btnTxt = '开通VIP' else: msg = '点赞次数已达今日上限,升级VIP等级可提高点赞次数上限获得更多福利哦~' btnTxt = '升级VIP' dialog_task = TodoTaskShowInfo(msg, True) dialog_task.setSubCmd(pay_order) dialog_task.setSubText(btnTxt) TodoTaskHelper.sendTodoTask(gameId, uid, [dialog_task])
def doBuyProduct(self, gameId, userId, prodId): try: clientId = sessiondata.getClientId(userId) orderId = self._makeOrderId(gameId, userId, prodId) orderDeliveryResult = hallstore.exchangeProduct(gameId, userId, clientId, orderId, prodId, 1) mo = StoreHelper.makeProductDeliveryResponse(userId, orderDeliveryResult) router.sendToUser(mo, userId) except TYBizException, e: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message))
def sendRewards(self, userId, gameId, clientId): bSend = True for cond in self.conditions: if not cond.check(gameId, userId, clientId, pktimestamp.getCurrentTimestamp()): bSend = False if bSend: from hall.entity import hallitem userAssets = hallitem.itemSystem.loadUserAssets(userId) assetList = userAssets.sendContent( gameId, self.items, 1, True, pktimestamp.getCurrentTimestamp(), 'LOGIN_REWARD', 0) if assetList: if ftlog.is_debug(): ftlog.debug('hall_login_reward.sendReward gameId=', gameId, 'userId=', userId, 'rewards=', [(atup[0].kindId, atup[1]) for atup in assetList]) # 记录登录奖励获取时间 gamedata.setGameAttr(userId, HALL_GAMEID, 'login_reward', pktimestamp.getCurrentTimestamp()) # 通知更新 changedDataNames = TYAssetUtils.getChangeDataNames(assetList) datachangenotify.sendDataChangeNotify(gameId, userId, changedDataNames) pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, self.mail) from poker.util import strutil _, cVer, _ = strutil.parseClientId(clientId) if cVer < 3.90: TodoTaskHelper.sendTodoTask( gameId, userId, TodoTaskShowInfo(self.mail, True)) else: rewardsList = [] for assetItemTuple in assetList: ''' 0 - assetItem 1 - count 2 - final ''' assetItem = assetItemTuple[0] reward = {} reward['name'] = assetItem.displayName reward['pic'] = assetItem.pic reward['count'] = assetItemTuple[1] rewardsList.append(reward) if ftlog.is_debug(): ftlog.debug( 'hall_login_reward.TodoTaskShowRewards rewardsList: ', rewardsList) TodoTaskHelper.sendTodoTask( gameId, userId, TodoTaskShowRewards(rewardsList))
def doAssistanceGet(self, gameId, userId): try: _consumeCount, finalCount, sendChip = hallvip.userVipSystem.gainAssistance(gameId, userId) if sendChip > 0: datachangenotify.sendDataChangeNotify(gameId, userId, 'udata') todotask = TodoTaskGoldRain(VipHelper.buildGotAssistanceDesc(finalCount, sendChip)) TodoTaskHelper.sendTodoTask(gameId, userId, todotask) except TYAssistanceChipTooMuchException, e: ftlog.warn('ERROR, doAssistanceGet', gameId, userId, e.chip, e.upperChipLimit, e.errorCode, e.message)
def onUserVipLevelUp(self, event): if ftlog.is_debug(): ftlog.debug('VipHandlerImpl.onUserVipLevelUp userId=', event.userId, 'gameId=', event.gameId, 'oldLevel=', event.oldVipLevel.level, 'newLevel=', event.userVip.vipLevel.level) todotask = TodoTaskVipLevelUp(VipHelper.buildVipInfo(event.userVip), self.buildVipLevelUpDesc(event.userId, event.oldVipLevel, event.userVip)) TodoTaskHelper.sendTodoTask(event.gameId, event.userId, todotask)
def onRoomCreateCustomTable(self, gameId, msg): '''在GR处理自建桌逻辑 ''' if ftlog.is_debug(): ftlog.debug("<< |msg", msg, caller=self) userId = msg.getParam("userId") selectedRoomOptions = msg.getParam("selectedRoomOptions") if not selectedRoomOptions: return customConfVer = msg.getParam("customConfVer") if customConfVer != difangConf.getCustomRoomConf(gameId, 'ver'): ftlog.warn("onRoomCreateCustomTable confVer error! |msg:", msg, caller=self) return gameRoundN = selectedRoomOptions.get("gameRoundN") if not gameRoundN: return roomId = msg.getParam("roomId") room = gdata.rooms()[roomId] clientId = msg.getParam("clientId") needRoomCardN = difangConf.getCustomRoomConf(gameId, 'roomCardNCost').get(str(gameRoundN), -1) if needRoomCardN == -1: tips = difangConf.getCustomRoomConf(difangConf.GAME_ID, 'err_tips') tip = tips[self.CREATE_CUSTOM_TABLE_ERR_NO_NOT_ALLOW] TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(tip, True)) ftlog.warn("onRoomCreateCustomTable get needRoomCardN error! |msg:", msg, caller=self) self.sendGameCreateCustomTableRes(0, userId) return if ftlog.is_debug(): ftlog.debug("|userId, gameId, customConfVer, gameRoundN, needRoomCardN:", userId, gameId, customConfVer, gameRoundN, needRoomCardN, caller=self) if needRoomCardN > 0 and not self.isCardEnough(gameId, userId, needRoomCardN, clientId): tips = difangConf.getCustomRoomConf(difangConf.GAME_ID, 'err_tips') tip = tips[self.CREATE_CUSTOM_TABLE_ERR_NO_NOT_ENOUGH] TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(tip, True)) self.sendGameCreateCustomTableRes(0, userId) return tableId = room.getIdleTableId() if not tableId: ftlog.error("there are no idle tables!", "|userId, roomId:", userId, room.roomId) return ftId = self.assignFriendTableId(gameId, tableId) ftlog.info("onRoomCreateCustomTable |userId, tableId, ftId:", userId, tableId, ftId, caller=self) self.sendGameCreateCustomTableRes(ftId, userId) gamedata.setGameAttr(userId, gameId, "selectedRoomOptions", json.dumps(selectedRoomOptions)) gamedata.setGameAttr(userId, gameId, "customConfVer", customConfVer) shadowRoomId = tableId / 10000 room.querySitReq(userId, shadowRoomId, tableId, clientId, extParams={"selectedRoomOptions": selectedRoomOptions, "ftId": ftId})
def onCmdQuickStart1(cls, msg, userId, gameId, roomId, tableId, playMode, clientId): ''' 拦截父类处理的选择房间逻辑,先于父类处理,若选择成功,则不进行父类的选择房间处理逻辑,否则正常走父类的处理逻辑 ''' if not pokerconf.isOpenMoreTable(clientId): ok, loc = cls.checkUserLoc(userId, gameId, roomId, tableId, clientId) if not ok: # 弹框 tipsPlaying = dizhuconf.getPublicConf('tips.playing', '您正在其它房间对局,是否回去?') showInfo = TodoTaskShowInfo(tipsPlaying) showInfo.setSubCmd( TodoTaskQuickStart(loc[0], loc[1], loc[2], loc[3])) TodoTaskHelper.sendTodoTask(gameId, userId, showInfo) ftlog.debug('DizhuQuickStartV4_0.onCmdQuickStart Fail userId=', userId, 'roomId=', roomId, 'tableId=', tableId, 'clientId=', clientId, 'loc=', loc) return if loc: tableId = loc[2] _, version, _ = strutil.parseClientId(clientId) ftlog.debug("DizhuQuickStartV4_0.onCmdQuickStart: clientId=", clientId, "userId=", userId, "roomId=", roomId, "tableId=", tableId, "version=", version, "type:", type(version), "playMode=", playMode) # 地主会优先去匹配比赛的房间,客户端是3.76及更高版本才支持 if (playMode == None or playMode == "match" or playMode == "straightMatch") and roomId == 0 and gameId == 6 and ( version >= 3.76 or (version >= 3.73 and not (clientId in _DIZHU_QMATCH_V3_73_IGNORE))): chose_roomid, ok = cls._chooseDizhuMatchRoom( userId, gameId, playMode) ftlog.debug( "DizhuQuickStartV4_0._chooseDizhuMatchRoom:chosen|room_id=", chose_roomid, "userId=", userId, "ok=", ok) if ok: bigroomid = gdata.getBigRoomId(chose_roomid) ftlog.debug( "DizhuQuickStartV4_0._chooseDizhuMatchRoom: userId=", userId, "roomId=", chose_roomid) cls.notifyQuickGotoDizhuMatch(gameId, userId, bigroomid) return if playMode == "match": playMode = dizhuconf.PLAYMODE_123 super(DizhuQuickStartV4_0, cls).onCmdQuickStart(msg, userId, gameId, roomId, tableId, playMode, clientId) return
def doGetInviteReward(self, gameId, userId, inviteeId, clientId): """ 获取推荐人奖励 作为上线奖励 """ if (not inviteeId) or (inviteeId <= 0): TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('请输入推荐人ID', True)) return try: timestamp = pktimestamp.getCurrentTimestamp() status = hall_simple_invite.loadStatus(userId, timestamp) inviteeInvitation = status.findInvitee(inviteeId) if not inviteeInvitation: TodoTaskHelper.sendTodoTask( gameId, userId, TodoTaskShowInfo('没有推荐此人,请重新领取', True)) return if inviteeInvitation.inviterState == Invitation.STATE_REWARDED: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('已经领取推荐奖励', True)) return if hall_simple_invite.getGameCount(inviteeId, clientId) == 0: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('玩家还未进行游戏', True)) return inviteeInvitation.inviterState = Invitation.STATE_REWARDED hall_simple_invite.saveStatus(status) ftlog.info('doGetInviteReward userId=', status.userId, 'invitee=', inviteeId) conf = hall_simple_invite.getSimpleInviteConf( userId, gameId, clientId) mo = MsgPack() mo.setCmd('invite_info') mo.setResult('action', 'get_invite_reward') mo.setResult('gameId', gameId) count = self.getTotalReward(status) if conf.inviteRewardItem: mo.setResult('totalReward', count * conf.inviteRewardItem.count) self.addUserItemByKindId(userId, gameId, clientId, conf.inviteRewardItem.assetKindId, conf.inviteRewardItem.count) userInfo = {} userInfo['userId'] = inviteeId userInfo['rewardState'] = inviteeInvitation.inviterState mo.setResult('updateInfo', userInfo) router.sendToUser(mo, userId) except TYBizException, e: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message, True))
def on_ready_invite_friend(cls, gameId, uid, clientId, mo): from hall.entity.todotask import TodoTaskHelper code = mo.getResult('code', 0) if code != 1: return from hall.entity.todotask import TodoTaskBindPhoneFriend info_ = '请绑定手机,成为正式账号即可与朋友一起玩!' task = TodoTaskBindPhoneFriend(info_, 0) task.setSubText('绑定手机') TodoTaskHelper.sendTodoTask(gameId, uid, [task])
def doGameGetMemberReward(self, userId, gameId, clientId): userAssets = hallitem.itemSystem.loadUserAssets(userId) userBag = userAssets.getUserBag() memberCardItem = userBag.getItemByKindId(hallitem.ITEM_MEMBER_NEW_KIND_ID) timestamp = pktimestamp.getCurrentTimestamp() if memberCardItem and memberCardItem.canCheckin(timestamp): checkinAction = memberCardItem.itemKind.findActionByName('checkin') checkinAction.doAction(gameId, userAssets, memberCardItem, timestamp, {}) datachangenotify.sendDataChangeNotify(gameId, userId, 'free') TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain('恭喜您领取了今天的会员福利'))
def notifyUserGameWillShutDown(userId, clientId, isNeedPopShutDownGameWnd): #过期不弹窗 nowStamp = int(time.time()) if nowStamp >= 1524326400: return if not isNeedPopShutDownGameWnd: return from hall.entity.todotask import TodoTaskHelper from hall.entity.todotask import TodoTaskShowInfo TodoTaskHelper.sendTodoTask(9999, userId, TodoTaskShowInfo('因运营需要,4月19日起暂停发财扑克(含天地麻将)等功能模块,恢复时间请关注官网,感谢理解!', True))
def throwEmoji(self, userId, seatId, toSeatId, emojiId, count=1): seatFrom = self.checkSeatAndPlayer(seatId, userId) seatTo = self.checkSeat(toSeatId) try: self._throwEmoji(seatFrom, seatTo, emojiId, count) except ChipNotEnoughException: TodoTaskHelper.sendTodoTask(self.table.gameId, userId, TodoTaskPopTip('背包剩余金币不足无法使用互动表情')) except TYBizException, e: self.proto.sendSmilesResError(userId, e.message)
def doUserStandUp(userId, roomId, tableId, clientId, reason): _, clientVer, _ = strutil.parseClientId(clientId) ftlog.debug('table_remote.doUserStandUp userId=', userId, 'roomId=', roomId, 'tableId=', tableId, 'clientId=', clientId, 'reason=', reason, 'clientVer=', clientVer) if reason not in (TableStandUpEvent.REASON_GAME_OVER, ): return 0 chipCount = userchip.getChip(userId) roomConf = gdata.getRoomConfigure(roomId) or {'minCoin': 0, 'maxCoin': -1} if chipCount < roomConf['minCoin']: reason = TableStandUpEvent.REASON_CHIP_NOT_ENOUGHT if clientVer >= 3.77: # 新版救济金弹气泡支持 processLoseOutRoomV3_77(DIZHU_GAMEID, userId, clientId, roomId, showMemberTry=False) elif clientVer >= 3.7: hallpopwnd.processLoseOutRoomV3_7(DIZHU_GAMEID, userId, clientId, roomId, showMemberTry=False) elif clientVer == 3.502: processLoseOutRoom(DIZHU_GAMEID, userId, clientId, roomId) elif clientVer >= 3.0: timestamp = pktimestamp.getCurrentTimestamp() benefitsSend, userBenefits = hallbenefits.benefitsSystem.sendBenefits( DIZHU_GAMEID, userId, timestamp) ftlog.debug('benefitsSend, userBenefits =', benefitsSend, userBenefits) zhuanyun = hallpopwnd.makeTodoTaskZhuanyun(DIZHU_GAMEID, userId, clientId, benefitsSend, userBenefits, roomId) if zhuanyun: TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, zhuanyun) else: ttask = TodoTaskHelper.makeBenefitsTodoTask( DIZHU_GAMEID, userId, clientId, benefitsSend, userBenefits) if ttask: TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, ttask) datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, 'chip') else: benefitsSend, userBenefits = hallbenefits.benefitsSystem.sendBenefits( DIZHU_GAMEID, userId, pktimestamp.getCurrentTimestamp()) ftlog.debug('benefitsSend, userBenefits =', benefitsSend, userBenefits) elif (roomConf['maxCoin'] != -1 and chipCount > roomConf['maxCoin']): pass # reason = TableStandUpEvent.REASON_CHIP_TOO_MUCH # from dizhu.gametable.quick_start import DizhuQuickStartV4_0 # DizhuQuickStartV4_0._sendTodoTaskJumpHighRoom(userId, roomConf['playMode'], clientId) return 1
def _doChangeNameCheck(self, userId, clientId): canRename, desc = hallrename.checkRename(HALL_GAMEID, userId) if canRename: return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskRename(desc)) else: info = TodoTaskShowInfo(desc, True) if hallrename.payOrder: product, _ = hallstore.findProductByPayOrder(HALL_GAMEID, userId, clientId, hallrename.payOrder) if product: info.setSubCmd(TodoTaskPayOrder(product)) return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, info)
def sendTodoTaskResponse(self, userId, gameId, clientId, isdayfirst): ''' 发送当前用户的TODOtask列表消息 ''' ftlog.debug('UtilHelper.sendTodoTaskResponse userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'isdayfirst=', isdayfirst) todotasks = TYGame(gameId).getTodoTasksAfterLogin( userId, gameId, clientId, isdayfirst) if todotasks: TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
def sendTodoTaskResponse(self, userId, gameId, clientId, isdayfirst): ''' 发送当前用户的TODOtask列表消息 ''' ftlog.debug('UtilHelper.sendTodoTaskResponse userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'isdayfirst=', isdayfirst) todotasks = TYGame(gameId).getTodoTasksAfterLogin(userId, gameId, clientId, isdayfirst) if todotasks: TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
def onUserVipLevelUp(self, event): if ftlog.is_debug(): ftlog.debug('VipHandlerImpl.onUserVipLevelUp userId=', event.userId, 'gameId=', event.gameId, 'oldLevel=', event.oldVipLevel.level, 'newLevel=', event.userVip.vipLevel.level) todotask = TodoTaskVipLevelUp( VipHelper.buildVipInfo(event.userVip), self.buildVipLevelUpDesc(event.userId, event.oldVipLevel, event.userVip)) TodoTaskHelper.sendTodoTask(event.gameId, event.userId, todotask)
def doAssistanceGet(self, gameId, userId): try: _consumeCount, finalCount, sendChip = hallvip.userVipSystem.gainAssistance( gameId, userId) if sendChip > 0: datachangenotify.sendDataChangeNotify(gameId, userId, 'udata') todotask = TodoTaskGoldRain( VipHelper.buildGotAssistanceDesc(finalCount, sendChip)) TodoTaskHelper.sendTodoTask(gameId, userId, todotask) except TYAssistanceChipTooMuchException, e: ftlog.warn('ERROR, doAssistanceGet', gameId, userId, e.chip, e.upperChipLimit, e.errorCode, e.message)
def _doChangeNameTry(self, userId, clientId, newName): # renameConf = hallconf.getClientRenameConf(clientId) # if (renameConf # and not renameConf.get('containsSensitive', 1) # and keywords.isContains(newName)): # info = TodoTaskShowInfo(hallrename.stringRenameContainsSensitive) # return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, info) code, info = hallrename.tryRename(HALL_GAMEID, userId, newName) if ftlog.is_debug(): ftlog.debug('hallrename._doChangeNameTry->', code, info) CLIENT_VER = 4.57 _, clientVer, _ = strutil.parseClientId(clientId) if ftlog.is_debug(): ftlog.debug("_doChangeNameTry clientVer", userId, clientId, newName, code, info, clientVer) reInfo = "" if code == -3 : reInfo = "昵称没有变化" elif code == -2 : # 没有改名卡 info = TodoTaskShowInfo(hallrename.stringRenameCardRequired, True) if hallrename.payOrder: product, _ = hallstore.findProductByPayOrder(HALL_GAMEID, userId, clientId, hallrename.payOrder) if product: info.setSubCmd(TodoTaskPayOrder(product)) return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, info) elif code == 0 : reInfo = "昵称修改成功" # 改名成功 if clientVer < CLIENT_VER: if ftlog.is_debug(): ftlog.debug("_doChangeNameTry ok", userId, clientId, newName, code, info, clientVer) return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip(hallrename.stringRenameSuccessed)) else: #reInfo = "修改昵称失败,请重试" reInfo = info # SDK改名失败 if clientVer < CLIENT_VER: if ftlog.is_debug(): ftlog.debug("_doChangeNameTry fail", userId, clientId, newName, code, info, clientVer) return TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip(info)) mo = MsgPack() mo.setCmd('change_name') mo.setResult('action', 'try') mo.setResult('userId', userId) mo.setResult('code', code) mo.setResult('reInfo', reInfo) router.sendToUser(mo, userId) if ftlog.is_debug(): ftlog.debug("_doChangeNameTry result",userId, clientId, newName, code, reInfo)
def doFriendCall(self, gameId, userId): ftlog.debug('doFriendCall...') cmd = runcmd.getMsgPack() # router.sendToUser(mo, userId) # clientId = runcmd.getClientId(cmd) action = cmd.getParam('action') if action == 'invite_to_game': # 邀请好友牌桌游戏 enterParams = cmd.getParam('enterParams') note = cmd.getParam('note') invitees = cmd.getParam('invitees') self.processInvitees(enterParams, note, invitees, userId, gameId) return elif action == 'answer_to_invite': # 对好友邀请的应答 inviter = cmd.getParam('inviter') answer = cmd.getParam('answer') self.processInviteAnswser(inviter, answer, userId, gameId) return elif action in [ 'get_friends_rank', 'get_friend_tip_info', 'praise_friend' ]: from hall.entity import hallvip try: vip = hallvip.userVipSystem.getUserVip(userId).vipLevel.level except: vip = 0 cmd.setParam('vip', vip) elif action == 'add_friend': if self._isObserver(userId): show_info_task = TodoTaskShowInfo("对不起,旁观时不能加好友哦~") TodoTaskHelper.sendTodoTask(gameId, userId, show_info_task) return # if not clientId: # clientId = sessiondata.getClientId(userId) params = cmd._ht['params'] tcp_params = strutil.cloneData(params) del tcp_params['authorCode'] del params['action'] del params['gameId'] params['appId'] = gameId # params['from_tcp'] = 1 import json params['tcp_params'] = json.dumps(tcp_params) url = self.action_urls[action] ftlog.debug('handleFriendCall post', url, params) sdkclient._requestSdk(url, params, needresponse=False)
def doBuyProduct(self, gameId, userId, prodId): try: clientId = sessiondata.getClientId(userId) orderId = self._makeOrderId(gameId, userId, prodId) orderDeliveryResult = hallstore.exchangeProduct( gameId, userId, clientId, orderId, prodId, 1) mo = StoreHelper.makeProductDeliveryResponse( userId, orderDeliveryResult) router.sendToUser(mo, userId) except TYBizException, e: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message))
def handleException(self, itemId, gameId, userId, clientId, e): if ftlog.is_debug(): ftlog.debug('ItemTcpHandler.handleException itemId=', itemId, 'gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'e=', e) if isinstance(e, TYItemActionConditionNotEnoughException): self.handleItemActionConditionException(itemId, gameId, userId, clientId, e) elif isinstance(e, TYItemBindingsException): self.handleItemBindingsException(itemId, gameId, userId, clientId, e) else: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message))
def doFriendCall(self, gameId, userId): ftlog.debug('doFriendCall...') cmd = runcmd.getMsgPack() # router.sendToUser(mo, userId) # clientId = runcmd.getClientId(cmd) action = cmd.getParam('action') if action == 'invite_to_game': # 邀请好友牌桌游戏 enterParams = cmd.getParam('enterParams') note = cmd.getParam('note') invitees = cmd.getParam('invitees') self.processInvitees(enterParams, note, invitees, userId, gameId) return elif action == 'answer_to_invite': # 对好友邀请的应答 inviter = cmd.getParam('inviter') answer = cmd.getParam('answer') self.processInviteAnswser(inviter, answer, userId, gameId) return elif action in ['get_friends_rank', 'get_friend_tip_info', 'praise_friend']: from hall.entity import hallvip try: vip = hallvip.userVipSystem.getUserVip(userId).vipLevel.level except: vip = 0 cmd.setParam('vip', vip) elif action == 'add_friend': if self._isObserver(userId): show_info_task = TodoTaskShowInfo("对不起,旁观时不能加好友哦~") TodoTaskHelper.sendTodoTask(gameId, userId, show_info_task) return # if not clientId: # clientId = sessiondata.getClientId(userId) params = cmd._ht['params'] tcp_params = strutil.cloneData(params) del tcp_params['authorCode'] del params['action'] del params['gameId'] params['appId'] = gameId # params['from_tcp'] = 1 import json params['tcp_params'] = json.dumps(tcp_params) url = self.action_urls[action] ftlog.debug('handleFriendCall post', url, params) sdkclient._requestSdk(url, params, needresponse=False)
def handleItemBindingsException(self, itemId, gameId, userId, clientId, e): showInfo = TodoTaskShowInfo(e.message) payOrder = e.itemBindings.getParam('payOrder') if payOrder: product, shelves = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder) if product: showInfo.setSubCmd(TodoTaskGotoShop(shelves.name)) else: todotask = e.itemBindings.getParam('todotask') if todotask: todotask = TodoTaskRegister.decodeFromDict(todotask).newTodoTask(gameId, userId, clientId) TodoTaskHelper.sendTodoTask(gameId, userId, todotask) return TodoTaskHelper.sendTodoTask(gameId, userId, showInfo)
def processInviteAnswser(self, inviter, answer, userId, gameId): ''' 对邀请游戏的应答 userId - 当前用户 inviter - 邀请者 向邀请者发送回应 ''' uds = userdata.getAttrs(userId, ['name']) response = '' if answer: response = '您的好友 ' + uds[0] + ' 同意了您的游戏邀请' else: response = '您的好友 ' + uds[0] + ' 拒绝了您的游戏邀请' TodoTaskHelper.sendTodoTask(gameId, inviter, TodoTaskPopTip(response))
def _doNewVipGift(cls, gameId, userId, level): try: userVip, _giftStates, gotVipGiftResult = hallvip.userVipSystem.gainUserVipGift(gameId, userId, level) ftlog.debug('VipTcpHandler._doNewVipGift userId=', userId, 'gameId=', gameId, 'giftVipLevel=', gotVipGiftResult.vipGiftState.vipLevel.level) giftInfo = VipHelper.buildGiftInfo(userVip, gotVipGiftResult.vipGiftState) getGiftTodoTask = TodoTaskVipGotGift(gotVipGiftResult.vipGiftState.vipLevel.level, gotVipGiftResult.vipGiftState.vipLevel.vipExp, gotVipGiftResult.vipGiftState.vipLevel.name, gotVipGiftResult.vipGiftState.vipLevel.desc, giftInfo) todotasks = [getGiftTodoTask] needGoldRain = TYAssetUtils.getAssetCount(gotVipGiftResult.giftItemList, hallitem.ASSET_CHIP_KIND_ID) > 0 if needGoldRain: todotasks.append(TodoTaskGoldRain(VipHelper.buildGotGiftDesc(gotVipGiftResult))) else: todotasks.append(TodoTaskPopTip(VipHelper.buildGotGiftDesc(gotVipGiftResult))) mo = TodoTaskHelper.sendTodoTask(gameId, userId, todotasks) # 通知客户端变化 if gotVipGiftResult.giftItemList: datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(gotVipGiftResult.giftItemList)) return mo except TYBizException, e: return cls.sendErrorResponse(userId, 'newvip', e.errorCode, e.message)
def queryFangKaBuyInfo(gameId, userId, clientId): templateName = hallconf.getFangKaBuyInfoCliengConf(clientId) if templateName: ret = _fbTemplateMap.get(templateName, None) if not ret: return # 执行todotask ftlog.debug('hall_fangka_buy_info.queryFangKaBuyInfo gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'templateName=', templateName, 'tasks=', ret.todotasks) todotasks = TodoTaskRegister.decodeList(ret.todotasks) tasks = TodoTaskHelper.makeTodoTasksByFactory(gameId, userId, clientId, todotasks) TodoTaskHelper.sendTodoTask(gameId, userId, tasks)
def handleItemActionConditionException(self, itemId, gameId, userId, clientId, e): showInfo = TodoTaskShowInfo(e.message) payOrder = e.condition.getParam('payOrder') if payOrder: product, shelves = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder) if product: showInfo.setSubCmd(TodoTaskGotoShop(shelves.name)) else: todotask = e.condition.getParam('todotask') if todotask: factory = hallpopwnd.decodeTodotaskFactoryByDict(todotask) if factory: todotask = factory.newTodoTask(gameId, userId, clientId) TodoTaskHelper.sendTodoTask(gameId, userId, todotask) return TodoTaskHelper.sendTodoTask(gameId, userId, showInfo)
def doGetInviteReward(self, gameId, userId, inviteeId, clientId): """ 获取推荐人奖励 作为上线奖励 """ if (not inviteeId) or (inviteeId <= 0): TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('请输入推荐人ID', True)) return try: timestamp = pktimestamp.getCurrentTimestamp() status = hall_simple_invite.loadStatus(userId, timestamp) inviteeInvitation = status.findInvitee(inviteeId) if not inviteeInvitation: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('没有推荐此人,请重新领取', True)) return if inviteeInvitation.inviterState == Invitation.STATE_REWARDED: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('已经领取推荐奖励', True)) return if hall_simple_invite.getGameCount(inviteeId, clientId) == 0: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('玩家还未进行游戏', True)) return inviteeInvitation.inviterState = Invitation.STATE_REWARDED hall_simple_invite.saveStatus(status) ftlog.info('doGetInviteReward userId=', status.userId, 'invitee=', inviteeId) conf = hall_simple_invite.getSimpleInviteConf(userId, gameId, clientId) mo = MsgPack() mo.setCmd('invite_info') mo.setResult('action', 'get_invite_reward') mo.setResult('gameId', gameId) count = self.getTotalReward(status) if conf.inviteRewardItem: mo.setResult('totalReward', count * conf.inviteRewardItem.count) self.addUserItemByKindId(userId, gameId, clientId, conf.inviteRewardItem.assetKindId, conf.inviteRewardItem.count) userInfo = {} userInfo['userId'] = inviteeId userInfo['rewardState'] = inviteeInvitation.inviterState mo.setResult('updateInfo', userInfo) router.sendToUser(mo, userId) except TYBizException, e: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message, True))
def _doSit(self, msg, userId, seatId, clientId, checkGameStart=True): selectedRoomOptions = msg.getParam("selectedRoomOptions") ftId = msg.getParam("ftId") if ftlog.is_debug(): ftlog.debug(self._baseLogStr("<<", userId), "|selectedRoomOptions, ftId, self.cMaxSeatNum:", selectedRoomOptions, ftId, self.cMaxSeatNum, caller=self) if selectedRoomOptions: self._refreshCustomConf(selectedRoomOptions) self.firstPlayerId = userId # 房主 self.ftId = ftId # 6位自建号 self.createTime = int(time.time()) ftlog.info(self._baseLogStr("_doSit <<", userId), "|selectedRoomOptions, ftId, self.cMaxSeatNum:", selectedRoomOptions, ftId, self.cMaxSeatNum, caller=self) result = super(DiFangCustomTable, self)._doSit(msg, userId, seatId, clientId) if result["reason"] == TYRoom.ENTER_ROOM_REASON_TABLE_FULL: tip = u"您好, 牌桌已满。" TodoTaskHelper.sendTodoTask(self.gameId, userId, TodoTaskShowInfo(tip, True)) return result if result["reason"] != TYRoom.ENTER_ROOM_REASON_OK: return result # 坐下成功, 人满后检查开桌 if ftlog.is_debug(): ftlog.debug(self._baseLogStr(">>", userId), "|self.playersNum, self.cMaxSeatNum:", self.playersNum, self.cMaxSeatNum, caller=self) if selectedRoomOptions: for _ in range(self.cMaxSeatNum - self.playersNum): self.sendRobotNotifyCallUp(None) if self.gamePlay.isWaitingState() and checkGameStart and self.playersNum == self.cMaxSeatNum: func = functools.partial(self.gamePlay.doActionCheckStartGame) msgPackParams = {"seatId": result["seatId"] - 1} self.callLaterFunc(0, func, userId, timer=None, msgPackParams=msgPackParams) # 需要异步锁桌子 return result
def _onEnterRoomFailed(cls, msg, checkResult, userId, gameId, clientId, roomId=0): '''进入房间失败回调函数''' ftlog.warn("|userId, reason, roomId:", userId, checkResult, roomId, caller=cls) # 调用最小房间金币不够充值提醒的todotask if not roomId: roomId = msg.getParam('candidateRoomId', 0) if checkResult == TYRoom.ENTER_ROOM_REASON_LESS_MIN or checkResult == 104: from hall.entity import hallproductselector product, _ = hallproductselector.selectLessbuyProduct(gameId, userId, clientId, roomId) if product: from hall.entity.todotask import TodoTaskOrderShow todotask = TodoTaskOrderShow.makeByProduct("金币不够啦,买一个超值礼包吧!", "", product) if todotask: TodoTaskHelper.sendTodoTask(gameId, userId, todotask) mo = MsgPack() mo.setCmd('quick_start') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('reason', checkResult) router.sendToUser(mo, userId)
def doCheckout(self, gameId, userId, clientId, freeItemId): """ { "cmd": "game", "params": { "action": "free_checkout", "userId": 10856, "gameId": 9999, "freeItemId": 1 } } """ timestamp = pktimestamp.getCurrentTimestamp() freeList = hallfree.getFree(gameId, userId, clientId, timestamp) free = FreeHelper.getFreeById(freeList, freeItemId) if free: curState = FreeHelper.getCurStateOfFreeItem(gameId, userId, clientId, free, timestamp) if curState: todotasks = TodoTaskHelper.makeTodoTasksByFactory(gameId, userId, clientId, curState.todotaskList) if todotasks: TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
def applyDismiss(cls, table, player): userId, seatIndex = player.userId, player.seatIndex if ftlog.is_debug(): ftlog.debug("<<", table.gamePlay.getBasicAttrsLog(), "|", "userId, seatIndex:", userId, seatIndex, caller=cls) nowTime = int(time.time()) tip = u"您好,解散申请冷却中,\n请1分钟后再申请。" if nowTime - player.lastApplyDismissTime < 60: TodoTaskHelper.sendTodoTask(table.gameId, player.userId, TodoTaskShowInfo(tip, True)) return False player.lastApplyDismissTime = nowTime player.isVotedDismiss = True table.firstVotePlayer = player # table.agreeN = 0 func = functools.partial(cls.doAllAgree, table) table.callLaterFunc(table.cVoteDismissTime, func, 0, table.tableTimer, {}) return True
def doSendReward(cls, gameId, userId, clientId, activityId): activities = { 'activity_hall_reward_hszz': { 'url': 'http://apk.dl.tuyoo.com/down/hszz/Clash_Royale.apk', 'rewardChip': 10000, 'goldRain': '恭喜您获得1万金币', 'intActId': 20000 }, 'act_hall_reward_wzry': { 'url': 'http://down.s.qq.com/download/apk/10015420_com.tencent.tmgp.sgame.apk', 'rewardChip': 0, 'goldRain': '恭喜您获得100金币', 'intActId': 20001 }, 'act_hall_reward_cyhx': { 'url': 'http://down.s.qq.com/download/apk/10015420_com.tencent.tmgp.cf.apk', 'rewardChip': 0, 'goldRain': '恭喜您获得100金币', 'intActId': 20002 } } actConf = activities.get(activityId) if actConf: todotasks = [TodoTaskDownloadApkPromote(actConf['url'])] if (actConf['rewardChip'] > 0 and gamedata.setnxGameAttr(userId, gameId, 'act.sendReward:%s' % (activityId), 1) == 1): # 发1完金币 userchip.incrChip(userId, gameId, actConf['rewardChip'], daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 'ACTIVITY_REWARD', actConf['intActId'], clientId) datachangenotify.sendDataChangeNotify(gameId, userId, ['chip']) todotasks.append(TodoTaskGoldRain(actConf['goldRain'])) ftlog.info('ActivitySendReward.doSendReward gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'activityId=', activityId, 'rewardChip=', actConf['rewardChip']) TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
def onFiveStarRated(userId, clientId, timestamp): ver, channelName = _parseClientId(clientId) channel = _channels.get(channelName) if channel: fsRate = _loadFiveStarRate(userId, channel) fsRate.rateTime = timestamp if ver > fsRate.rateVersion: fsRate.rateVersion = ver _saveFiveStarRate(userId, fsRate) count = _incrRateCount(fsRate, timestamp) # 添加好评奖励 if 'appendItems' in channel and _canSendPrize(channel): items = channel.get('appendItems', []) ftlog.debug('fivestarrate.onFiveStarRated appendItems=', items) userAssets = hallitem.itemSystem.loadUserAssets(userId) bSendCoin = False changed = [] for item in items: assetKind = userAssets.addAsset(9999, item["itemId"], item["count"], int(time.time()), 'FIVE_STAR_SEND', 0) changed.append(assetKind) if item['itemId'] == 'user:chip': bSendCoin = True changeNames = TYAssetUtils.getChangeDataNames(changed) changeNames.add('free') datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, changeNames) # 金币雨 if bSendCoin == True: TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskGoldRain(channel.get('feedback', '感谢您的五星好评'))) ftlog.debug('fivestarrate.onFiveStarRated userId=', userId, 'clientId=', clientId, 'timestamp=', timestamp, 'count=', count) return True return False
def doGetBindReward(self, gameId, userId, clientId): """ 获取绑定推荐人奖励 作为下线领取的奖励,只有一次 """ try: timestamp = pktimestamp.getCurrentTimestamp() status = hall_simple_invite.loadStatus(userId, timestamp) if (status.rewardState != Invitation.STATE_REWARDED) and \ status.getRewardState(userId, gameId, clientId) == Invitation.STATE_CAN_GET_REWARD: conf = hall_simple_invite.getSimpleInviteConf(userId, gameId, clientId) status.setRewardState(Invitation.STATE_REWARDED) hall_simple_invite.saveStatus(status) mo = MsgPack() mo.setCmd('invite_info') mo.setResult('action', 'get_bind_reward') mo.setResult('rewardState', status.rewardState) mo.setResult('gameId', gameId) count = self.getTotalReward(status) if conf.inviteRewardItem: if 0 == count: mo.setResult('totalReward', 0) else: total = gamedata.getGameAttrInt(userId, HALL_GAMEID, 'simpleInviteRewardCount') if 0 == total: total = count * conf.inviteRewardItem.count gamedata.incrGameAttr(userId, HALL_GAMEID, 'simpleInviteRewardCount', total) mo.setResult('totalReward', total) self.addUserItemByKindId(userId, gameId, clientId, conf.inviteRewardItem.assetKindId, conf.inviteRewardItem.count) gamedata.incrGameAttr(userId, HALL_GAMEID, 'simpleInviteRewardCount', conf.inviteRewardItem.count) router.sendToUser(mo, userId) else: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('奖励已经领取', True)) except TYBizException, e: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message, True))