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 enterFriendTable(self, userId, gameId, clientId, ftId): """进入自建桌,插件实现具体功能""" if ftlog.is_debug(): ftlog.debug('MAJIANG enterFriendTable userId:', userId , ' gameId:', gameId , ' clientId:', clientId , ' ftId:', ftId) tableId0, roomId0 = CreateTableData.getTableIdByCreateTableNo(ftId) if ftlog.is_debug(): ftlog.debug('MAJIANG enterFriendTable ftId:', ftId , ' roomId:', roomId0 , ' tableId:', tableId0) if not tableId0 or not roomId0: from difang.majiang2.entity.util import sendPopTipMsg sendPopTipMsg(userId, '您要进入的朋友场房间不存在,请核对房间号') return config = { "type": "game", "pluginParams": { "gameType": 11, "ftId": ftId } } todotask = TodoTaskEnterGameNew(GAMEID, config) mo = MsgPack() mo.setCmd('todo_tasks') mo.setResult('gameId', gameId) mo.setResult('pluginId', GAMEID) mo.setResult('userId', userId) mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask)) router.sendToUser(mo, userId)
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 sendMasterGiftTodoTask(userId, gameId, clientId, pic, pay_order, roomId): """ 推送高手礼包弹窗 @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 todotask = TodoTaskPayOrder(product) task = { 'action': 'cache_wnd_gaoshou', 'params': { 'pic': pic, 'tasks': [todotask.toDict()] } } mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('tasks', [task]) router.sendToUser(mo, userId)
def getUpdateInfo(gameId, userId, clientId, version, updateVersion): global _updatesMap mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'get_game_update_info') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('clientId', clientId) updates = [] strGameId = str(gameId) if strGameId in _updatesMap: gUpdates = _updatesMap[strGameId] if version in gUpdates: vUpdates = gUpdates[version] for u in vUpdates: if updateVersion < int(u['updateVersion']): updates.append(u) if ftlog.is_debug(): ftlog.debug('hall_game_update.getUpdateInfo gameId:', gameId , ' userId:', userId , ' clientId:', clientId , ' version:', version , ' updateVersion:', updateVersion , ' updates:', updates ) mo.setResult('updates', updates) router.sendToUser(mo, userId) return updates
def doActivityExchangeOld(self, gameId, userId, clientId, activityId, action): msg = runcmd.getMsgPack() ftlog.debug('doActivityExchangeOld msg=', msg) result = activity.activitySystem.handleActivityRequest(userId, gameId, clientId, msg) mo = ActivityTcpHelper.getOldResponseMsg(result, gameId, userId, activityId, action) ftlog.debug('doActivityExchangeOld res=', mo) router.sendToUser(mo, userId)
def sendFreeChipTodoTask(userid, gameId, cache = False, direct = True): """ 推送 免费金币 added by nick.kai.lee Args: userid: 玩家userid cache: action命名是否是缓存形式,默认不缓存 direct: 是否直接发送,False则return dict """ if not TYPlayer.isHuman(userid): return False, None ftlog.debug('sendFreeChipTodoTask:', userid) from majiang2.entity.todotasks_builder.todotasks_builder import MahjongTodoTaskBuilder task = MahjongTodoTaskBuilder.dict_free_chip(userid, cache) if not task: return False, None ftlog.debug('sendFreeChipTodoTask:', task) if False == direct: return True, task mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userid) mo.setResult('tasks', [task]) router.sendToUser(mo, userid) return True, None
def sendFriendInviteTodotask(userId, invite_uid, gameId, play_mode, roomId, tableId, info_str, purl): """ 推送牌桌好友邀请的todotask * 版本 3.732 之后,改为麻将自己的todotask """ todotask = TodoTaskQuickStart(gameId, roomId, tableId) todotask.setParam('play_mode', play_mode) client_ver = sessiondata.getClientIdVer(userId) if client_ver < 3.732: show_info_ = TodoTaskShowInfo(info_str, True) show_info_.setSubCmd(todotask) msg = TodoTaskHelper.makeTodoTaskMsg(gameId, userId, show_info_) router.sendToUser(msg, userId) else: task = { 'action': 'pop_wnd_invite', 'params': { 'tasks': [todotask.toDict()], 'invite_uid': invite_uid, 'purl': purl, 'info_str': info_str } } mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('tasks', [task]) router.sendToUser(mo, userId)
def doGetDescription(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) mo = MsgPack() mo.setCmd('m_des') mo.setResult('gameId', self.gameId) self.matchPlugin.getMatchInfo(self, userId, mo) router.sendToUser(mo, userId)
def doDeliveryProduct(self, uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error): ftlog.info('doDeliveryProduct->', uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error) userdata.clearUserCache(uid) mo = MsgPack() mo.setCmd('prod_delivery') mo.setParam('userId', uid) mo.setParam('orderId', orderId) mo.setParam('prodId', prodId) mo.setParam('orderPrice', orderPrice) mo.setParam('orderPlatformId', platformOrder) if isError == 'true': mo.setResult('ok', '0') mo.setResult('info', error) mo.setError(1, error) router.sendToUser(mo, uid) return 'success' else: mo.setParam('ok', '1') isSub = runhttp.getParamInt('is_monthly', 0) if isSub: mo.setParam('isSub', isSub) ret = router.queryUtilServer(mo, uid) ftlog.info('doDeliveryProduct->', uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error, 'result=', ret) if isinstance(ret, (str, unicode)) and ret.find('error') < 0: return 'success' return 'error'
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 doExchange(self, gameId, userId): try: msg = runcmd.getMsgPack() couponId = msg.getParam('id') phone = msg.getParam('phone') if not phone: phone = msg.getParam('phoneNumber') if not phone: pp = msg.getParam('params', {}) if isinstance(pp, dict): phone = pp.get('phoneNumber') if not phone: if ftlog.is_debug(): ftlog.debug('ExchangeHandler.doExchange gameId=', gameId, 'userId=', userId, 'couponId=', couponId, 'phone=', phone) raise TYBizException(-1, 'Please input phone number') _trueDelta, final = self._getCouponService().exchangeCouponItem(userId, couponId, phone=phone) mo = MsgPack() mo.setCmd('exchange') mo.setResult('action', 'exchange') mo.setResult('id', couponId) mo.setResult('info', '兑换请求处理成功') mo.setResult('quan_left', final) router.sendToUser(mo, userId) except TYBizException, e: mo = MsgPack() mo.setCmd('exchange') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId)
def doReceiveSdkNotify(self): """ action: add_friend accept_friend """ paramsDict = runhttp.getDict() ftlog.debug("doReceiveSdkNotify:", paramsDict) appId = paramsDict.get('appId', 0) userId = int(paramsDict.get('userId', 0)) actionType = paramsDict.get('type', '') ext = paramsDict.get('ext', None) msg = paramsDict.get('message', '') mo = MsgPack() mo.setCmd('friend_notify') mo.setResult('gameId', appId) mo.setResult('userId', userId) mo.setResult('action', actionType) mo.setResult('info', msg) if ext != None: try: extjson = json.loads(ext) for k in extjson: mo.setResult(k, extjson[k]) except: pass userdata.clearUserCache(userId) router.sendToUser(mo, userId) # if actionType == 'add_friend': # from poker.entity.biz.message import message # message.send(int(appId), message.MESSAGE_TYPE_SYSTEM, int(userId), msg) return 'success'
def sendBigMatchBackToListTodoTask(userid, gameId, cache = False, direct=True): """比赛结算界面返回按钮返回时 """ from majiang2.entity.todotasks_builder.todotasks_builder import MahjongTodoTaskBuilder msg = "比赛已结束,点击离开按钮返回比赛列表" task = MahjongTodoTaskBuilder.dict_general_box(userid, msg, cache) retTask = strutil.cloneData(task) buttonLeaveTask = { "content":"离开", "tasks":[ { "action":"trigger_notify", "params":{ "eventName":"UPDATE_MATCH_BACK_TO_LIST" } } ] } retTask['params']['buttons'] = [buttonLeaveTask] mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userid) mo.setResult('tasks', [retTask]) router.sendToUser(mo, userid) return True, None
def doUserSetStarId(self, userId, gameId, clientId, starId): userdata.setAttr(userId, 'starid', starId) mo = MsgPack() mo.setCmd('set_star_id') mo.setResult('gameId', gameId) mo.setResult('starId', starId) router.sendToUser(mo, userId)
def sendPingRes(self, userId, pingDelays, timeStamp): """下发玩家网络状况 """ mpRes = self.createMsgPackRes("table_call", 'ping') mpRes.setResult('timeStamp', timeStamp) mpRes.setResult('pingDelays', pingDelays) # [10,100,20,10] router.sendToUser(mpRes, userId)
def sendNotifyMsg(cls, gameId, uid, showTime, content): """ { "cmd": "notifyMsg", "result": { "showTime": 0.5, "content": [{ "color": "RRGGBB", "text": "bababababa" }, { "color": "RRGGBB", "text": "bababababa" }] } } """ msg_content = [dict(zip(("color", "text"), segment)) for segment in content] message = MsgPack() message.setCmd('notifyMsg') message.setResult("userId", uid) message.setResult("gameId", gameId) message.setResult("showTime", showTime) message.setResult("content", msg_content) router.sendToUser(message, uid)
def doPutMessage(self, gameId, fromUid, toUid, mtype, msg, ismgr, scope, clientIds): button = runhttp.getParamStr('button', None) button = strutil.loads(button, ignoreException=True) data = None mo = MsgPack() if mtype == 0 and len(msg) > 0 and toUid > 0 and gameId >= 0: # 发送私人消息 # 必须参数 # 1)msg - 消息 # 2)toUid - 接收消息的userId # 3)gameId data = pkmessage.sendPrivate(gameId, toUid, fromUid, msg, button) elif mtype == 1 and len(msg) > 0 and gameId >= 0: # 发送站内消息到全体用户 # 必选参数 # msg - 消息 # gameId data = pkmessage.sendGlobal(gameId, msg, button) elif mtype == 2 and gameId > 0 and len(msg) > 0: # 发送LED # TODO 当前Game服务为4,5,6号 , 每个服务都发送 mo.setCmd('send_led') mo.setParam('msg', msg) mo.setParam('gameId', gameId) mo.setParam('ismgr', 1) router.sendToAll(mo, gdata.SRV_TYPE_UTIL) data = True elif mtype == 3 and gameId > 0 and toUid > 0 and len(msg) > 0: # 封装popwnd # 必选参数 # gameId # toUid 接收弹窗的userId # msg 弹窗消息内容 task = TodoTaskShowInfo(msg, True) mo = TodoTaskHelper.makeTodoTaskMsg(gameId, toUid, task) # 将消息发送给此人 router.sendToUser(mo, toUid) data = True elif mtype == 4 and gameId > 0 and len(msg) > 0 and len(scope) > 0: mo.setCmd('send_led') mo.setParam('msg', msg) ftlog.info('send_led new msg=', msg) mo.setParam('gameId', gameId) ftlog.info('send_led new gameId=', gameId) mo.setParam('ismgr', ismgr) ftlog.info('send_led new ismgr=', ismgr) mo.setParam('scope', scope) ftlog.info('send_led new scope=', scope) mo.setParam('clientIds', clientIds) ftlog.info('send_led new clientIds=', clientIds) router.sendToAll(mo, gdata.SRV_TYPE_UTIL) data = True if data == None: mo.setError(1, 'params error') else: mo.setResult('ok', 'true') return mo
def doRouletteBeforeReward(self, userId, gameId, clientId): ''' 客户端点击事件 获取整体金盘小兵的历史中奖信息 ''' result = hallroulette.doGetBeforeReward(userId, gameId, clientId) mo = rouletteHelper.makeRouletteQueryResponse(gameId, userId, clientId, 'roulette_beforeReward', result) router.sendToUser(mo, userId)
def doGetRoulletGoldUpdate(self, userId, gameId, clientId): ''' 客户端自动获取(金银转换时1次) 获取金盘配置信息 ''' result = hallroulette.doGetGoldUpdate(userId, gameId, clientId) mo = rouletteHelper.makeRouletteQueryResponse(gameId, userId, clientId, 'roulette_goldUpdate', result) router.sendToUser(mo, userId)
def doHallGameList(self, userId, gameId, clientId): pages = hallgamelist.getGameList(gameId, userId, clientId) mo = MsgPack() mo.setCmd('hall_game_list') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('pages', pages) router.sendToUser(mo, userId)
def doGetLiveShowTableList(self, userId, clientId): '''为了效率,贵宾室所有桌子放在一个GT进程里, 在此进程中通过遍历来获取每张桌子的状态 ''' msgRes = MsgPack() msgRes.setCmd("game") msgRes.setResult("action", "live_show_table_list") msgRes.updateResult(self._getVipTableList(userId, clientId, tag="", isLiveShowRoom=True)) router.sendToUser(msgRes, userId)
def doHallInfo(self, userId, gameId, clientId): roominfos = hallconf.getHallSessionInfo(gameId, clientId) msg = MsgPack() msg.setCmd('hall_info') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('sessions', roominfos) router.sendToUser(msg, userId)
def doHallHtmlsInfo(self, userId, gameId, clientId): roominfos = hallconf.getHallHtmlsInfo(clientId) msg = MsgPack() msg.setCmd('htmls_info') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('htmls', roominfos) router.sendToUser(msg, userId)
def sendItemListResponse(cls, gameId, userId, tabs): mo = MsgPack() mo.setCmd('user') mo.setResult('action', 'majiang_item') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('items', cls.queryUserItemTabsV3_7(gameId, userId)) router.sendToUser(mo, userId)
def doHallLocalNotification(self, userId, gameId, clientId): lnConfig = halllocalnotification.queryLocalNotification(gameId, userId, clientId) mo = MsgPack() mo.setCmd('hall_local_notification') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('notifies', lnConfig) router.sendToUser(mo, userId)
def doUpdateItem(self, gameId, userId): mo = MsgPack() mo.setCmd('exchange') mo.setResult('action', 'update_item') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('item_list', ExchangeHelper.encodeCouponItemList(self._getCouponService().couponItems)) router.sendToUser(mo, userId)
def doGiveup(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) if not self.match.giveup(userId): mo = MsgPack() mo.setCmd('room') mo.setError(-1, '不能退出比赛') router.sendToUser(mo, userId)
def doGetDescription(self, userId): if ftlog.is_debug(): ftlog.debug('TYRelaxationMatchRoom.doGetDescription', 'userId=', userId) mo = MsgPack() mo.setCmd('m_des') mo.setResult('gameId', self.gameId) self.matchPlugin.getMatchInfo(self, userId, mo) router.sendToUser(mo, userId)
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 doSegmentRankList(self, userId, gameId, clientId, start, stop, preIssue): msg = self._get_segment_rank_list(userId, gameId, clientId, start, stop, preIssue) router.sendToUser(msg, userId)
def queryExitRemind(gameId, userId, clientId): global _ordersMap exitSDK = queryExitSDK(gameId, userId, clientId) if ftlog.is_debug(): ftlog.debug('queryExitRemind exitSDK:', exitSDK) gameIdInClientId = strutil.getGameIdFromHallClientId(clientId) if ftlog.is_debug(): ftlog.debug('hall_exit_remind.queryExitRemind gameIdInClientId', gameIdInClientId) strGameId = str(gameIdInClientId) if strGameId not in _ordersMap: if ftlog.is_debug(): ftlog.debug( 'hall_exit_remind.queryExitRemind no this game exit remind config....' ) return orders = _ordersMap[strGameId] if ftlog.is_debug(): ftlog.debug('hall_exit_remind.queryExitRemind orders:', orders) for order in orders: if ftlog.is_debug(): ftlog.debug('hall_exit_remind.queryExitRemind order:', order) conds = UserConditionRegister.decodeList(order.get('conditions', [])) if ftlog.is_debug(): ftlog.debug('hall_exit_remind.queryExitRemind conds:', conds) bCondsOK = False if len(conds) == 0: bCondsOK = True for cond in conds: if cond.check(HALL_GAMEID, userId, clientId, pktimestamp.getCurrentTimestamp()): if ftlog.is_debug(): ftlog.debug('hall_exit_remind.queryExitRemind cond ok: ', cond) bCondsOK = True break if bCondsOK: todotasksDict = order.get('todotasks', []) todotasks = TodoTaskRegister.decodeList(todotasksDict) if ftlog.is_debug(): ftlog.debug('hall_exit_remind.queryExitRemind todotasks:', todotasks) todos = TodoTaskHelper.makeTodoTasksByFactory( HALL_GAMEID, userId, clientId, todotasks) tasks = TodoTaskHelper.encodeTodoTasks(todos) if ftlog.is_debug(): ftlog.debug( 'hall_exit_remind.queryExitRemind build tasks ok: ', tasks) mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'get_exit_remind') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('button', order.get('button', '')) mo.setResult('tips', order.get('tips', '')) mo.setResult('tasks', tasks) mo.setResult('exitSDK', exitSDK) router.sendToUser(mo, userId) if ftlog.is_debug(): ftlog.debug('hall_exit_remind.queryExitRemind userId:', userId, ' clientId:', clientId, ' msg:', mo) return
def notifyMatchOver(self, player, reason, rankRewards): ''' 通知用户比赛结束了 ''' try: exchangeMoney = rankRewards.conf.get('exchangeMoney', None) if rankRewards else None exchangeCode = None if exchangeMoney: exchangeCode = RedEnvelopeHelper.getRedEnvelopeCode( player.userId, self._room.gameId, exchangeMoney, self._room.roomId, self._room.match.matchId, player.rank) ftlog.info('MatchPlayerNotifierDizhu.notifyMatchOver matchId=', player.matchInst.matchId, 'instId=', player.matchInst.instId, 'userId=', player.userId, 'signinParams=', player.signinParams, 'stageIndex=', player.stage.index, 'rank=', player.rank, 'reason=', reason, 'rankRewards=', rankRewards, 'exchangeCode=', exchangeCode) lastBestRank = None record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: lastBestRank = record.bestRank # 获取房间名 roomName = player.matchInst.matchConf.getRoomName(player.mixId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(player.mixId) if player.mixId else self._room.bigRoomId, None) if arenaContent: roomName = arenaContent.get('showName') or roomName rewardId = None if (reason == MatchFinishReason.USER_WIN or reason == MatchFinishReason.USER_LOSER): try: if player.isQuit: rankRewards = None event_remote.publishMatchWinloseEvent( self._room.gameId, player.userId, self._room.match.matchId, reason == MatchFinishReason.USER_WIN, player.rank, player.matchInst.matchConf.stages[0].totalUserCount, rankRewards.conf if rankRewards else None) tempGameResult = 1 if reason == MatchFinishReason.USER_WIN else -1 hall51event.sendToHall51MatchOverEvent( player.userId, self._room.gameId, self._room.bigRoomId, tempGameResult, -1, -1) if rankRewards: from dizhu.entity.matchhistory import MatchHistoryHandler MatchHistoryHandler.onMatchOver( player.userId, player.matchInst.matchConf.recordId, player.rank, reason == MatchFinishReason.USER_WIN, rankRewards.conf if rankRewards else None, False, player.mixId, exchangeCode=exchangeCode) matchRewardSwitch = WxShareControlHelper.getMatchRewardSwitch( ) if matchRewardSwitch: from dizhu.game import TGDizhu rewardId = RewardAsyncHelper.genRewardId() rewards = [] for rewardInfo in rankRewards.rewards: rewards.append({ 'itemId': rewardInfo['itemId'], 'count': rewardInfo['count'] }) playerMixId = int( player.mixId) if player.mixId else None TGDizhu.getEventBus().publishEvent( UserRewardAsyncEvent( DIZHU_GAMEID, player.userId, REWARD_ASYNC_TYPE_AS_ARENA_MATCH, rewardId, rewards, matchId=playerMixId or player.matchInst.matchId, mixId=playerMixId or 0, rank=player.rank, sequence=int( player.matchInst.instId.split('.')[1]), roomName=roomName)) if not rankRewards: matchutil.report_bi_game_event( 'MATCH_REWARD', player.userId, player.matchInst.matchId, 0, int(player.matchInst.instId.split('.')[1]), 0, 0, 0, [ 0, 0, 0, player.rank, int(player.mixId) if player.mixId else 0, 0 ], 'match_reward') except: ftlog.error() # 比赛记录保存 try: event = { 'gameId': self._room.gameId, 'userId': player.userId, 'matchId': self._room.match.matchId, 'rank': player.rank, 'isGroup': 0, 'mixId': player.mixId } MatchRecord.updateAndSaveRecord(event) except: ftlog.error() msg = MsgPack() msg.setCmd('m_over') msg.setResult('rewardId', rewardId) msg.setResult('mixId', player.mixId) msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('reason', reason) msg.setResult('rank', player.rank) msg.setResult('exchangeCode', exchangeCode) if rankRewards: msg.setResult('info', self.buildWinInfo(player, rankRewards)) else: msg.setResult('info', self.buildLoserInfo(player)) msg.setResult('mucount', player.matchInst.matchConf.stages[0].totalUserCount) msg.setResult('date', str(datetime.now().date().today())) msg.setResult('time', time.strftime('%H:%M', time.localtime(time.time()))) msg.setResult('addInfo', '') rewardDesc = '' if rankRewards: msg.setResult('reward', matchutil.buildRewards(rankRewards)) rewardDesc = matchutil.buildRewardsDesc(rankRewards) if rewardDesc: msg.setResult('rewardDesc', rewardDesc) msg.setResult('mname', roomName) clientId = sessiondata.getClientId(player.userId) # 微信分享 money = 0 if rankRewards: for r in rankRewards.rewards: if r['itemId'] == 'user:coupon': assetKind = hallitem.itemSystem.findAssetKind( 'user:coupon') displayRate = assetKind.displayRate money = round(r['count'] * 1.0 / displayRate, 2) kwargs = {'matchRank': {'money': money % 100, 'stop': player.rank}} shareInfo = commconf.getNewShareInfoByCondiction( self._room.gameId, clientId) msg.setResult( 'shareInfo', {'erweima': shareInfo['erweima'] if shareInfo else {}}) try: # 玩家红包记录 dizhushare.addMatchHistoryCount(self._room.bigRoomId, player.rank) userShareInfo = rankRewards.conf.get( 'shareInfo', {}) if rankRewards else {} rewardType, shareInfoNew = dizhushare.getArenaShareInfoNew( player.userId, player.matchInst.matchConf.feeRewardList, arenaContent, userShareInfo) if shareInfoNew: msg.setResult('shareInfoNew', shareInfoNew) # 设置奖状分享的todotask diplomaShare matchShareType = 'arena' if rewardType == 'redEnvelope' else 'group' shareTodoTask = commconf.getMatchShareInfo( player.userName, roomName, player.rank, rewardDesc, player.userId, matchShareType, clientId) if shareTodoTask: msg.setResult('shareTodoTask', shareTodoTask) if rankRewards: bigImg = rankRewards.conf.get('bigImg', '') if bigImg: msg.setResult('bidImg', bigImg) msg.setResult('beatDownUser', player.beatDownUserName) if rankRewards and rankRewards.todotask: msg.setResult('todotask', rankRewards.todotask) # 微信公众号消息 if player.rank == 1: from hall.game import TGHall msgParams = {'reward': rewardDesc, 'roomName': roomName} TGHall.getEventBus().publishEvent( OfficialMessageEvent(DIZHU_GAMEID, player.userId, RED_ENVELOPE, msgParams, mixId=player.mixId)) if ftlog.is_debug(): ftlog.debug( 'MatchPlayerNotifierDizhu.notifyMatchOver.redEnvelopeEvent userId=', player.userId, 'reward=', rewardDesc, 'rank=', player.rank, 'roomName=', roomName) # 冠军触发抽奖逻辑 match_lottery = MatchLottery() ret = match_lottery.checkMatchRank(player.userId, self._room.match.matchId, player.rank) if ret: msg.setResult('match_lottery', 1) # 局间奖励总数 if player.stageRewardTotal: msg.setResult('stageReward', {'count': player.stageRewardTotal}) if ftlog.is_debug(): ftlog.debug( 'MatchPlayerNotifierDizhu.notifyMatchOver userId=', player.userId, 'roomId=', self._room.roomId, 'rank=', player.rank, 'player=', player, 'stageRewardTotal=', player.stageRewardTotal) except Exception, e: ftlog.error('notifyMatchOver.getArenaShareInfoNew', 'userId=', player.userId, 'matchId=', self._room.match.matchId, 'err=', e.message) record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: msg.setResult( 'mrecord', { 'bestRank': record.bestRank, 'lastBestRank': lastBestRank, 'bestRankDate': record.bestRankDate, 'isGroup': record.isGroup, 'crownCount': record.crownCount, 'playCount': record.playCount }) else: from dizhu.activities.toolbox import Tool msg.setResult( 'mrecord', { 'bestRank': player.rank, 'lastBestRank': lastBestRank, 'bestRankDate': Tool.datetimeToTimestamp( datetime.now()), 'isGroup': 0, 'crownCount': 1 if player.rank == 1 else 0, 'playCount': 1 }) if not player.isQuit: router.sendToUser(msg, player.userId) # 混房冠军LED mixId = player.mixId if mixId: mixConf = MatchPlayerNotifierDizhu.getArenaMixConf( self._room.roomConf, mixId) if player.rank == 1 and mixConf.get('championLed'): arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) if ftlog.is_debug(): ftlog.debug('MatchPlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'roomId=', self._room.roomId, 'mixId=', mixId, 'roomName', mixConf.get('roomName'), 'rewardShow=', mixConf.get('rewardShow', rewardDesc), 'mixConf=', mixConf) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else mixConf.get('roomName'), arenaContent.get('rewardShow') if arenaContent else mixConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') else: if player.rank == 1 and self._room.roomConf.get( 'championLed') and not player.isQuit: arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else roomName, arenaContent.get('rewardShow') if arenaContent else self._room.roomConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') sequence = int(player.matchInst.instId.split('.')[1]) matchutil.report_bi_game_event( 'MATCH_FINISH', player.userId, player.matchInst.matchId, 0, sequence, 0, 0, 0, [int(player.mixId) if player.mixId else 255], 'match_end')
def doGetSegmentMatchRecover(self, userId, gameId, clientId): msg = self._segment_recover(userId, gameId, clientId) router.sendToUser(msg, userId)
def _do_complain(self, userId, gameId, clientId, roomId0, tableId0, gameNum, otherPlayerId1, otherPlayerId2): mo = MsgPack() mo.setCmd('complain') roomId = roomId0 roomId0 = gdata.getBigRoomId(roomId0) complainConf, tips = dizhuconf.getComplainInfo(roomId0) if not complainConf: mo.setError(1, '本房间不支持投诉') router.sendToUser(mo, userId) return mo comMoney = complainConf['fee'] currentUserChip = userchip.getChip(userId) if complainConf['fee'] <= (currentUserChip): trueDelta, _chip = userchip.incrChip( userId, gameId, -complainConf['fee'], daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 'GAME_COMPLAIN_INSURANCE', roomId0, clientId) # 金币不足支付举报的,返回错误。现改为'金币不足扔可继续举报'所以注释掉 if trueDelta != -complainConf['fee']: comMoney = trueDelta # mo.setError(2, tips.get("error", "")) # router.sendToUser(mo, userId) # return mo else: comMoney = 0 if ftlog.is_debug(): ftlog.debug('AccountTcpHandler.doComplain userId=', userId, 'userchip=', currentUserChip, 'fee=', complainConf['fee'], 'comMoney=', comMoney) complain_time = pktimestamp.getCurrentTimestamp() params = { 'act': 'api.getComplaintDetailInfo', 'gameid': gameId, 'playerId': userId, 'comtTime': complain_time, 'roomId': roomId0, 'PlayerOneId': otherPlayerId1, 'PlayerTwoId': otherPlayerId2, 'tableId': tableId0, 'gameSign': gameNum, 'comMoney': complainConf['fee'] } try: roundNum = int(gameNum.split('_')[-1]) except Exception: roundNum = 0 try: ret, complainCodec = normal_table_room_remote.getComplainContent( gameId, userId, roomId, tableId0, gameNum) if ret != 0: mo.setError(3, complainCodec) router.sendToUser(mo, userId) if comMoney > 0: userchip.incrChip(userId, gameId, comMoney, daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 'GAME_COMPLAIN_INSURANCE', roomId0, clientId) datachangenotify.sendDataChangeNotify( gameId, userId, 'chip') ftlog.error('doComplain userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'err=', complainCodec) else: mo.setResult('success', { "code": 1, 'info': tips.get("succ", "") }) pkmessage.sendPrivate(9999, userId, 0, tips.get("succ", "")) router.sendToUser(mo, userId) datachangenotify.sendDataChangeNotify(gameId, userId, ['chip', 'message']) bireport.reportGameEvent( 'GAME_COMPLAIN_INSURANCE', userId, DIZHU_GAMEID, params['roomId'], params['tableId'], roundNum, params['comMoney'], 0, 0, [ params['PlayerOneId'], params['PlayerTwoId'], params['comtTime'], strutil.dumps(complainCodec) ], clientId, 0, 0) ftlog.info('report_bi_game_event', 'eventId=GAME_COMPLAIN_INSURANCE', 'userId=', userId, 'gameId=', DIZHU_GAMEID, 'params=', params) except Exception, e: mo.setError(4, '操作失败') router.sendToUser(mo, userId) if comMoney > 0: userchip.incrChip(userId, gameId, comMoney, daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 'GAME_COMPLAIN_INSURANCE', roomId0, clientId) datachangenotify.sendDataChangeNotify(gameId, userId, 'chip') ftlog.error('doComplain userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'err=', e.message)
def notifyMatchOver(self, player, reason, rankRewards): ''' 通知用户比赛结束了 ''' try: ftlog.info('MatchPlayerNotifierDizhu.notifyMatchOver matchId=', player.matchInst.matchId, 'instId=', player.matchInst.instId, 'userId=', player.userId, 'signinParams=', player.signinParams, 'stageIndex=', player.stage.index, 'rank=', player.rank, 'reason=', reason, 'rankRewards=', rankRewards) if (reason == MatchFinishReason.USER_WIN or reason == MatchFinishReason.USER_LOSER): try: if player.isQuit: rankRewards = None event_remote.publishMatchWinloseEvent( self._room.gameId, player.userId, self._room.match.matchId, reason == MatchFinishReason.USER_WIN, player.rank, player.matchInst.matchConf.stages[0].totalUserCount, rankRewards.conf if rankRewards else None) tempGameResult = 1 if reason == MatchFinishReason.USER_WIN else -1 hall51event.sendToHall51MatchOverEvent(player.userId, self._room.gameId, self._room.bigRoomId, tempGameResult, -1, -1) from dizhu.entity.matchhistory import MatchHistoryHandler MatchHistoryHandler.onMatchOver( player.userId, player.matchInst.matchConf.recordId, player.rank, reason == MatchFinishReason.USER_WIN, rankRewards.conf if rankRewards else None, False, player.mixId) if not rankRewards: matchutil.report_bi_game_event( 'MATCH_REWARD', player.userId, player.matchInst.matchId, 0, int(player.matchInst.instId.split('.')[1]), 0, 0, 0, [ 0, 0, 0, player.rank, int(player.mixId) if player.mixId else 0, 0 ], 'match_reward') except: ftlog.error() # 比赛记录保存 try: event = { 'gameId': self._room.gameId, 'userId': player.userId, 'matchId': self._room.match.matchId, 'rank': player.rank, 'isGroup': 0, 'mixId': player.mixId } MatchRecord.updateAndSaveRecord(event) except: ftlog.error() msg = MsgPack() msg.setCmd('m_over') msg.setResult('mixId', player.mixId) msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('reason', reason) msg.setResult('rank', player.rank) if rankRewards: msg.setResult('info', self.buildWinInfo(player, rankRewards)) else: msg.setResult('info', self.buildLoserInfo(player)) msg.setResult('mucount', player.matchInst.matchConf.stages[0].totalUserCount) msg.setResult('date', str(datetime.now().date().today())) msg.setResult('time', time.strftime('%H:%M', time.localtime(time.time()))) msg.setResult('addInfo', '') rewardDesc = '' if rankRewards: msg.setResult('reward', matchutil.buildRewards(rankRewards)) rewardDesc = matchutil.buildRewardsDesc(rankRewards) if rewardDesc: msg.setResult('rewardDesc', rewardDesc) roomName = player.matchInst.matchConf.getRoomName(player.mixId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(player.mixId) if player.mixId else self._room.bigRoomId, None) if arenaContent: roomName = arenaContent.get('showName') or roomName msg.setResult('mname', roomName) shareInfo = matchutil.buildShareInfo( self._room.gameId, sessiondata.getClientId(player.userId)) msg.setResult('shareInfo', {'erweima': shareInfo['erweima'] if shareInfo else {}}) try: msg.setResult('beatDownUser', player.beatDownUserName) if rankRewards and rankRewards.todotask: msg.setResult('todotask', rankRewards.todotask) # 设置奖状分享的todotask diplomaShare shareTodoTask = dizhudiplomashare.buildDiplomaShare( player.userName, roomName, player.rank, rewardDesc, player.userId) if shareTodoTask: msg.setResult('shareTodoTask', shareTodoTask) if rankRewards: bigImg = rankRewards.conf.get('bigImg', '') if bigImg: msg.setResult('bidImg', bigImg) if ftlog.is_debug(): ftlog.debug( 'MatchPlayerNotifierDizhu.notifyMatchOver userId=', player.userId, 'roomId=', self._room.roomId, 'bigImg=', bigImg, 'rank=', player.rank, 'rankRewards.conf=', rankRewards.conf) except: ftlog.debug('NobeatDownUser arena match') ftlog.exception() # 冠军触发抽奖逻辑 try: from dizhu.games.matchutil import MatchLottery match_lottery = MatchLottery() ret = match_lottery.checkMatchRank(player.userId, self._room.match.matchId, player.rank) if ret: msg.setResult('match_lottery', 1) except: ftlog.debug('MatchLottery arena match') ftlog.exception() ########################### # 玩家红包记录 try: from dizhu.entity import dizhushare shareInfoConf = rankRewards.conf.get('shareInfo', {}) if rankRewards else {} rewardType = shareInfoConf.get('type', '') if shareInfoConf else '' shareNum, shareTotalNum = dizhushare.arenaMatchRewardRecord( player.userId, shareInfoConf) # 常规配置 championRewards = player.matchInst.matchConf.feeRewardList championShareInfo = championRewards[0].rankRewardsList[0].conf.get( 'shareInfo', {}) if arenaContent: # 分ip奖励配置 championRewards = arenaContent.get('rank.rewards', []) if championRewards and championRewards[0].get( 'ranking', {}).get('start', 0) == 1: championShareInfo = championRewards[0].get('shareInfo', {}) rmb = 0 matchShareType = 0 if championShareInfo and championShareInfo.get( 'type', '') == MATCH_REWARD_REDENVELOPE: # 冠军奖励金额 rmb = championShareInfo.get('rmb', 0) matchShareType = 1 if shareInfoConf and str(rewardType) == MATCH_REWARD_REDENVELOPE: rmb = shareInfoConf.get('rmb', 0) shareInfoNew = { "matchShareType": matchShareType, "shareNum": shareNum if shareNum else 0, "shareTotalNum": shareTotalNum if shareTotalNum else 0, "get": 1 if str(rewardType) == MATCH_REWARD_REDENVELOPE else 0, "rmb": '{0:.2f}'.format(rmb) } msg.setResult('shareInfoNew', shareInfoNew) except Exception, e: ftlog.error('MatchPlayerNotifierDizhu.notifyMatchOver', 'gameId=', self._room.gameId, 'userId=', player.userId, 'roomId=', self._room.roomId, 'matchId=', self._room.match.matchId, 'err=', e.message) ########################### record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: msg.setResult( 'mrecord', { 'bestRank': record.bestRank, 'bestRankDate': record.bestRankDate, 'isGroup': record.isGroup, 'crownCount': record.crownCount, 'playCount': record.playCount }) else: from dizhu.activities.toolbox import Tool msg.setResult( 'mrecord', { 'bestRank': player.rank, 'bestRankDate': Tool.datetimeToTimestamp(datetime.now()), 'isGroup': 0, 'crownCount': 1 if player.rank == 1 else 0, 'playCount': 1 }) if not player.isQuit: router.sendToUser(msg, player.userId) # 混房冠军LED mixId = player.mixId if mixId: mixConf = MatchPlayerNotifierDizhu.getArenaMixConf( self._room.roomConf, mixId) if player.rank == 1 and mixConf.get('championLed'): clientId = sessiondata.getClientId(player.userId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) if ftlog.is_debug(): ftlog.debug('MatchPlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'roomId=', self._room.roomId, 'mixId=', mixId, 'roomName', mixConf.get('roomName'), 'rewardShow=', mixConf.get('rewardShow', rewardDesc), 'mixConf=', mixConf) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else mixConf.get('roomName'), arenaContent.get('rewardShow') if arenaContent else mixConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') else: if player.rank == 1 and self._room.roomConf.get( 'championLed') and not player.isQuit: clientId = sessiondata.getClientId(player.userId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else roomName, arenaContent.get('rewardShow') if arenaContent else self._room.roomConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') sequence = int(player.matchInst.instId.split('.')[1]) matchutil.report_bi_game_event( 'MATCH_FINISH', player.userId, player.matchInst.matchId, 0, sequence, 0, 0, 0, [int(player.mixId) if player.mixId else 255], 'match_end')
def doAdInfo(self, userId, gameId, clientId): msg = self._do_ad_info(userId, gameId, clientId) router.sendToUser(msg, userId)
class TYArenaMatchRoom(TYRoom): '''大比赛房间类 Attributes: matchPlugin: 各游戏通过定义自己的BigMatchPlugin,来扩展数据获取、下发协议、异常处理、结算等功能 match: 比赛控制器 bigmatchId: bigRoomId, 兼容老代码 ''' def __init__(self, roomdefine): super(TYArenaMatchRoom, self).__init__(roomdefine) self.bigmatchId = self.bigRoomId self.matchPlugin = gdata.games()[self.gameId].getArenaMatchPlugin() serverType = gdata.serverType() if serverType == gdata.SRV_TYPE_ROOM: self.initMatch() # 此处会给self.match赋值 def initMatch(self): ftlog.info(getMethodName(), '<< |roomId=', self.roomId) assert (self.matchPlugin.getMatch(self.roomId) is None) conf = MatchConf().decodeFromDict(self.matchConf) conf.gameId = self.gameId conf.roomId = self.roomId conf.tableId = self.roomId * 10000 # 用来表示玩家在房间队列的特殊tableId conf.seatId = 1 tableManager = MatchTableManager(self.gameId, conf.tableSeatCount) shadowRoomIds = self.roomDefine.shadowRoomIds ftlog.info(getMethodName(), 'before add IdleTables.', '|roomId=', self.roomId, 'roomIds=', list(shadowRoomIds)) for roomId in shadowRoomIds: count = self.roomDefine.configure['gameTableCount'] baseid = roomId * 10000 ftlog.info(getMethodName(), 'adding IdleTables of one shadowRoom.', '|roomId=', self.roomId, 'shadowRoomId=', roomId, 'tableCount=', count, 'baseid=', baseid) tableManager.addTables(roomId, baseid, count) random.shuffle(tableManager._idleTables) match = self.matchPlugin.buildMatch(conf, self) match.tableManager = tableManager if (gdata.mode() == gdata.RUN_MODE_ONLINE): playerCapacity = int(tableManager.allTableCount * tableManager.tableSeatCount * 0.9) ftlog.info(getMethodName(), '<< |roomId=', self.roomId, 'allTableCount=', tableManager.allTableCount, 'tableSeatCount=', tableManager.tableSeatCount, 'playerCapacity=', playerCapacity, 'matchUserMaxCount=', conf.maxPlayerCount) assert (playerCapacity > conf.maxPlayerCount) match.start() self.match = match self.matchPlugin.setMatch(self.roomId, match) def doEnter(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) mo = MsgPack() mo.setCmd('m_enter') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.roomId) mo.setResult('userId', userId) try: if not self.match.currentInstance: mo.setError(1, u'比赛已经下线') else: if not self.match.enter(userId): mo.setError(1, u'已经在比赛中') except TYBizException, e: self.matchPlugin.handleMatchException(self, e, userId, mo) router.sendToUser(mo, userId)
0, 0, 0, [], 'match_signin') except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo) self._getMatchStatas(userId) signs = {} self._getUserMatchSigns(userId, signs) mo = MsgPack() mo.setCmd('m_signs') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.bigRoomId) mo.setResult('userId', userId) mo.setResult('signs', signs) mo.setResult('isAll', 0) router.sendToUser(mo, userId) def doSignout(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) mo = MsgPack() mo.setCmd('m_signout') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.bigRoomId) mo.setResult('userId', userId) try: if self.match.signout(userId): self.reportBiGameEvent("MATCH_SIGN_OUT", userId, self.roomId, 0, 0, 0, 0, 0, [], 'match_signout') except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo)
def _getMatchStatas(self, userId): mo = MsgPack() mo.setCmd('m_update') player = self.match.findPlayer(userId) self.matchPlugin.getMatchStates(self, userId, player, mo) router.sendToUser(mo, userId)
def sendWinloseRes(self, result): details = self.buildResultDetails(result) mp = self.buildWinloseRes(result, details, 1) from dizhu.game import TGDizhu from dizhu.entity.common.events import ActiveEvent crossPlayCount = configure.getGameJson(DIZHU_GAMEID, 'wx.cross', {}).get('crossPlayCount', 10) crossDelaySeconds = configure.getGameJson(DIZHU_GAMEID, 'wx.cross', {}).get('crossDelaySeconds', 10) authPlayCount = configure.getGameJson(DIZHU_GAMEID, 'authorization', {}).get('authPlayCount', 5) rewards = configure.getGameJson(DIZHU_GAMEID, 'authorization', {}).get('rewards', {}) for index, seat in enumerate(self.table.seats): if seat.player and not seat.isGiveup: if seat.player.isAI: continue ssts = result.seatStatements # 分享时的二维码等信息 mp.setResult('share', commconf.getNewShareInfoByCondiction(self.gameId, seat.player.clientId, 'winstreak')) # 是否达到踢出值 mp.setResult('isKickOutCoin', 0) # 服务费字段 mp.setResult('room_fee', ssts[index].fee + ssts[index].fixedFee) mp.rmResult('segmentInfo') mp.setResult('segmentInfo', details['segmentInfos'][index]) mp.rmResult('gameWinReward') if details['rewardInfos'][index]: mp.setResult('gameWinReward', details['rewardInfos'][index]) # 判断复活条件 mp.rmResult('recover') recover = details['recoverInfos'][index] if recover: mp.setResult('recover', recover) # 连胜任务信息 mp.rmResult('winStreakInfo') mp.setResult('winStreakInfo', details['winStreakRewardInfos'][index]) # 连胜宝箱 mp.rmResult('treasureChestInfo') mp.setResult('treasureChestInfo', details['treasureChestInfos'][index]) # 是否展示交叉导流 dailyPlayCount = new_table_remote.doGetUserDailyPlayCount(seat.userId, DIZHU_GAMEID) mp.setResult('dailyPlay', dailyPlayCount) mp.rmResult('showCross') mp.setResult('showCross', dailyPlayCount > crossPlayCount) mp.setResult('crossDelaySeconds', crossDelaySeconds) if ftlog.is_debug(): ftlog.debug('sendWinloseRes userId=', seat.userId, 'dailyPlayCount=', dailyPlayCount, 'showCross=', dailyPlayCount > crossPlayCount, 'crossDelaySeconds=', crossDelaySeconds) if dailyPlayCount == 3: TGDizhu.getEventBus().publishEvent(ActiveEvent(6, seat.userId, 'playTimes3')) mp.rmResult('auth') if dailyPlayCount == authPlayCount: mp.setResult('auth', {'auth': 1, 'rewards': rewards}) # 每日首胜 if seat.player.isFirstWin(ssts[index].isWin): from dizhu.game import TGDizhu from dizhu.entity.common.events import ActiveEvent import poker.util.timestamp as pktimestamp TGDizhu.getEventBus().publishEvent(ActiveEvent(6, seat.userId, 'dailyFirstWin')) today = pktimestamp.formatTimeDayInt() firstWin = {str(today): 1} gamedata.setGameAttrs(seat.userId, DIZHU_GAMEID, ['firstWin'], [strutil.dumps(firstWin)]) if ftlog.is_debug(): ftlog.debug('DizhuTableProtoSegment.sendWinloseRes userId=', seat.userId, 'mp=', mp._ht) router.sendToUser(mp, seat.userId)
class EndgameTcpHandler(BaseMsgPackChecker): def _check_param_roundNum(self, msg, key, params): roundNum = msg.getParam('roundNum') try: return None, int(roundNum) except: return None, 1 @markCmdActionMethod(cmd='dizhu', action='endgame_start', clientIdVer=0, scope='game') def doEndgameStart(self, userId, roundNum, clientId): msg = runcmd.getMsgPack() isHelp = msg.getParam('isHelp', False) self._doEndgameStart(userId, roundNum, clientId, isHelp) @classmethod def _doEndgameStart(cls, userId, roundNum, clientId, isHelp): # 检查更新赛季 updated = EndgameHelper.updateUserIssueRoundData(userId) # 获取用户当前数据 historyRoundData = None udata = EndgameHelper.getUserCurrentRoundData(userId) # 获取配置关卡牌 config = EndgameHelper.getCurrentIssueConfig() roundNum = min(roundNum, len(config.roundCards)) roundCards = config.roundCards.get(str(roundNum), {}) res = 1 if not roundCards: res = 0 landlordCards, farmerCards = [], [] if res: historyRoundData = EndgameHelper.getUserRoundDataHistory( userId, roundNum) landlordCards, farmerCards = translate_human_card_to_tycard( roundCards.get('landlordCards', []), roundCards.get('farmerCards', [])) player = EndgamePlayer(userId, landlordCards, farmerCards) player.historyRoundData = historyRoundData player.maxRoundNum = len(config.roundCards) player.isHelp = isHelp endgame_player_map[userId] = player # 闯关次数加 1 if not historyRoundData: udata.playCount += 1 EndgameHelper.saveUserCurrentRoundData(userId, udata) if ftlog.is_debug(): from dizhu.games.endgame.engine.utils import card_num_to_human_map ftlog.debug( 'EndgameTcpHandler._doEndgameStart userId=', userId, 'clientId=', clientId, 'roundNum=', roundNum, 'updated=', updated, 'historyRoundData=', historyRoundData, 'udata=', udata.encodeToDict(), 'isHelp=', isHelp, 'roundCards=', roundCards, 'farmerCards=', ''.join([card_num_to_human_map[c] for c in farmerCards]), 'landlordCards=', ''.join([card_num_to_human_map[c] for c in landlordCards])) mo = MsgPack() mo.setCmd('dizhu') mo.setResult('action', 'endgame_start') mo.setResult('farmerCards', farmerCards) mo.setResult('landlordCards', landlordCards) mo.setResult( 'challengeCount', udata.playCount if not historyRoundData else historyRoundData.playCount) mo.setResult('totalRoundCount', len(config.roundCards)) mo.setResult('updated', updated) mo.setResult('ok', res) router.sendToUser(mo, userId) @markCmdActionMethod(cmd='dizhu', action='endgame_card', clientIdVer=0, scope='game') def doEndgameOutCard(self, userId, clientId): msg = runcmd.getMsgPack() self._doEndgameOutCard(msg, userId, clientId) @classmethod def _doEndgameOutCard(cls, msg, userId, clientId): # 出牌 cards = msg.getParam('cards', []) res = 0 player = endgame_player_map.get(userId) robotCards = [] state = None nextRoundNum = 0 isHelp = False reply = [] initLandlordCards = [] initFarmerCards = [] if player: try: ret = player.outCards(cards) robotCards = ret['removeFarmerCards'] state = ret['state'] nextRoundNum = ret['roundNum'] isHelp = ret['isHelp'] reply = ret['reply'] initLandlordCards = ret['initLandlordCards'] initFarmerCards = ret['initFarmerCards'] res = 1 except Exception, e: ftlog.warn('EndgameTcpHandler._doEndgameOutCard userId=', userId, 'err=', e.message) if state != EndgamePlayer.STATE_PLAYING: try: del endgame.endgame_player_map[userId] except: pass mo = MsgPack() mo.setCmd('dizhu') mo.setResult('action', 'endgame_card') mo.setResult('robotCards', robotCards) mo.setResult('state', state) mo.setResult('nextRoundNum', nextRoundNum) mo.setResult('isHelp', isHelp) mo.setResult('reply', reply) mo.setResult('initLandlordCards', initLandlordCards) mo.setResult('initFarmerCards', initFarmerCards) mo.setResult('ok', res) router.sendToUser(mo, userId)
def doSegmentInfo(self, userId, gameId, clientId, issue=''): msg = self._get_segment_info(userId, gameId, clientId, issue) router.sendToUser(msg, userId)
def sendTableInfoRes(self, userId, clientId, isrobot): ftlog.debug('userId', userId, "|clientId", clientId, 'isrobot=', isrobot, caller=self) tableInfo = self.table._match_table_info if not tableInfo: ftlog.error('DizhuArenaSender.sendTableInfoRes NoMatchTableInfo', 'userId=', userId, 'clientId=', clientId, 'isrobot=', isrobot) return player = self.table.getPlayer(userId) if not player: ftlog.error('DizhuArenaSender.sendTableInfoRes NoPlayer', 'userId=', userId, 'clientId=', clientId, 'isrobot=', isrobot) return baseinfo = self.table.buildBasicInfo(False, userId, clientId) _, clientVer, _ = strutil.parseClientId(clientId) mo = self.createMsgPackRes("table_info") playMode = self.table.gamePlay.getPlayMode() if clientVer <= 3.7: if playMode == dizhuconf.PLAYMODE_HAPPY or playMode == dizhuconf.PLAYMODE_123: playMode = 'normal' # FIX, 客户端happy和123都是normal, grab=1就是欢乐 isMatch = self.table.isMatch mo.setResult('isrobot', isrobot) mo.setResult('playMode', playMode) roomLevel = gdata.roomIdDefineMap()[self.table.roomId].configure.get( 'roomLevel', 1) mo.setResult('roomLevel', roomLevel) roomName = self.table.room.roomConf['name'] if self.table.room else '' mo.setResult('roomName', roomName) mo.setResult('isMatch', isMatch) mo.setResult('notShowRank', 1) mo.setResult('info', baseinfo['info']) mo.setResult('config', baseinfo['config']) mo.setResult('stat', self.buildStatusInfoDict(player)) mo.setResult('myCardNote', self.buildCardNote(player.seatIndex)) if self.table.gameRound: mo.setResult('roundId', self.table.gameRound.roundId) if self.table._complain_open: clientIdVer = sessiondata.getClientIdVer(userId) clientIdLimit = dizhuconf.getAllComplainInfo().get( "clientIdLimit", 3.72) if clientIdVer >= clientIdLimit: mo.setResult('complain', self.table._complain) ftlog.debug("before getMatchTableInfo:", mo) self.getMatchTableInfo(userId, tableInfo, mo) ftlog.debug("after getMatchTableInfo:", mo) for i in xrange(len(self.table.seats)): seat = self.table.seats[i] oseat = self.buildSeatInfo(player, seat) seatuid = seat.userId if seatuid: seatPlayer = self.table.players[i] oseat.update(seatPlayer.datas) oseat['cardNote'] = seatPlayer.getCardNoteCount() seatPlayer.cleanDataAfterFirstUserInfo() self.getMatchUserInfo(seatPlayer.userId, tableInfo, oseat) else: oseat['uid'] = 0 mo.setResult('seat' + str(i + 1), oseat) tmpobsr = [] for _, obuser in self.table.observers.items(): if obuser: tmpobsr.append((obuser.userId, obuser.name)) mo.setResult('obsr', tmpobsr) mo.setResult('betpoolClose', 1) if player and player.getCardNoteCount() < 1: tableConf = self.table.room.roomConf.get( 'tableConf') if self.table.room else None cardNoteChip = tableConf.get('cardNoteChip', 0) cardNoteDiamod = tableConf.get('cardNoteDiamond', 0) cardNote = dizhuconf.getCardNoteTips(userId, player.datas.get('chip', 0), clientId, cardNoteChip, cardNoteDiamod) if cardNote: mo.setResult('cardNote', cardNote) # 发送消息至客户端 router.sendToUser(mo, userId)
def doGetCouponWithdraw(self, userId, gameId, clientId): msg = self._withdrawConf(userId, gameId, clientId) router.sendToUser(msg, userId)
def sendPopTip(cls, userId, text): todotask = TodoTaskPopTip(text) mo = TodoTaskHelper.makeTodoTaskMsg(DIZHU_GAMEID, userId, todotask) router.sendToUser(mo, userId)
def doWatchAd(self, userId, gameId, adId, clientId): msg = self._do_watch_ad(userId, gameId, adId, clientId) router.sendToUser(msg, userId)
class SportTcpHandler(BaseMsgPackChecker): def __init__(self): pass @markCmdActionMethod(cmd='game_sport', action="sport_main", clientIdVer=0) def doSportlotteryProduct(self): '''体育竞猜商品''' if ftlog.is_debug(): ftlog.debug('doSportlotteryProduct enter') msg = runcmd.getMsgPack() gameId = msg.getParam("gameId") userId = msg.getParam("userId") productList = hallsportlottery.sportlotteryProduct(userId) msg = MsgPack() msg.setCmd('game_sport') msg.setResult('action', 'sport_main') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('sportMainList', productList) helpDesc = SportlotteryConf.conf().get('helpDesc') msg.setResult('helpDesc', helpDesc) router.sendToUser(msg, userId) if ftlog.is_debug(): ftlog.debug('doSportlotteryProduct', 'userId=', userId, 'productList=', productList) @markCmdActionMethod(cmd='game_sport', action="sport_details", clientIdVer=0) def doSportlotteryDetails(self): '''体育竞猜细节''' if ftlog.is_debug(): ftlog.debug('doSportlotteryDetails enter') msg = runcmd.getMsgPack() gameId = msg.getParam("gameId") date = msg.getParam('date') matchId = msg.getParam('uuid') type = msg.getParam('type') userId = msg.getParam('userId') self.doSportDetail(userId, date, matchId, type, gameId) def doSportDetail(self, userId, date, matchId, type, gameId): details = hallsportlottery.sportlotteryDetail(userId, date, matchId, type) msg = MsgPack() msg.setCmd('game_sport') msg.setResult('action', 'sport_details') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('details', details) router.sendToUser(msg, userId) if ftlog.is_debug(): ftlog.debug('doSportlotteryDetails', 'userId=', userId, 'details=', details) @markCmdActionMethod(cmd='game_sport', action="sport_bet", clientIdVer=0) def doSportlotteryBet(self): '''体育竞猜下注''' if ftlog.is_debug(): ftlog.debug('doSportlotteryBet enter') msg = runcmd.getMsgPack() gameId = msg.getParam("gameId") clientId = msg.getParam("clientId") userId = msg.getParam('userId') date = msg.getParam('date') matchId = msg.getParam('uuid') party = msg.getParam('party') # 1主胜 2 平 3客胜 coin = msg.getParam('coin') type = msg.getParam('type') # 1足球 0篮球 ec = 0 info = '投注成功' userChip = 0 try: userChip = hallsportlottery.sportlotteryBet( gameId, clientId, userId, date, matchId, party, coin) self.doSportDetail(userId, date, matchId, type, gameId) except TYBizException, e: ec = e.errorCode info = e.message ftlog.info('doSportlotteryBet failer', 'userId=', userId, 'date=', date, 'matchId=', matchId, 'party=', party, 'coin=', coin, 'ec=', ec, 'info=', info) msg = MsgPack() msg.setCmd('game_sport') msg.setResult('action', 'sport_bet') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('date', date) msg.setResult('uuid', matchId) msg.setResult('party', party) msg.setResult('coin', coin) msg.setResult('userChip', userChip) msg.setResult('ec', ec) msg.setResult('info', info) router.sendToUser(msg, userId) if ftlog.is_debug(): ftlog.debug('doSportlotteryBet', 'userId=', userId, 'date=', date, 'matchId=', matchId, 'party=', party, 'coin=', coin, 'ec=', ec, 'info=', info)
def doGetSegmentMatchRules(self, userId, gameId, clientId): msg = self._get_segment_rules(userId, gameId, clientId) router.sendToUser(msg, userId)
info = e.message ftlog.info('doSportlotteryLove failer', 'userId=', userId, 'date=', date, 'matchId=', matchId, 'love=', love) msg = MsgPack() msg.setCmd('game_sport') msg.setResult('action', 'sport_love') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('date', date) msg.setResult('uuid', matchId) msg.setResult('love', love) msg.setResult('ec', ec) msg.setResult('info', info) router.sendToUser(msg, userId) if ftlog.is_debug(): ftlog.debug('doSportlotteryLove', 'userId=', userId, 'date=', date, 'matchId=', matchId, 'love=', love) @markCmdActionMethod(cmd='game_sport', action="sport_reward_list", clientIdVer=0) def doSportlotteryRewardList(self): '''我的竞猜''' if ftlog.is_debug(): ftlog.debug('doSportlotteryRewardList enter') msg = runcmd.getMsgPack() gameId = msg.getParam("gameId") userId = msg.getParam('userId')
def _doReport(cls, gameId, userId, otherPlayerId, reasons): mo = MsgPack() mo.setCmd('dizhu') mo.setResult('action', 'user_report') # 检测举报条件 reportDetail = gamedata.getGameAttr(userId, gameId, 'report') reportDetail = strutil.loads(reportDetail) if reportDetail else {} reportCount = reportDetail.setdefault('count', 0) reportTimestamp = reportDetail.setdefault('timestamp', 1356969600) currentTimestamp = pktimestamp.getCurrentTimestamp() if not pktimestamp.is_same_day(currentTimestamp, reportTimestamp): reportDetail['count'] = 0 else: if reportCount >= 10: mo.setError(1, '举报过于频繁,系统正在核实举报信息') router.sendToUser(mo, userId) return if currentTimestamp - reportTimestamp < 180: mo.setError(2, '举报过于频繁,系统正在核实举报信息') mo.setResult('remaining', 180 - (currentTimestamp - reportTimestamp)) router.sendToUser(mo, userId) return # 发送消息给举报者, 增加举报者举报次数 reportDetail['count'] += 1 reportDetail['timestamp'] = currentTimestamp gamedata.setGameAttr(userId, gameId, 'report', strutil.dumps(reportDetail)) reportStr = '' for reason in reasons: reportStr += cls._getTipByReason(reason) tip = '举报反馈:\n 您举报了玩家【%s】。\n 我们会核实原因,进行相应处理。' % ( UserInfo.getNickname(otherPlayerId)) mo.setResult('success', 1) mo.setResult('tip', tip) router.sendToUser(mo, userId) pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, tip) # 发送消息给被举报者,只有在原因①/③的情况下,被举报玩家才会收到信息,若被举报玩家同时因①③被举报,则优先使用①的被举报文本。 # 增加被举报者举报次数 reportedDetail = gamedata.getGameAttr(otherPlayerId, gameId, 'reported') reportedDetail = strutil.loads( reportedDetail) if reportedDetail else {} reportedDetail.setdefault('count', 0) for r in reasons: if r in [UserReportReason.NEGATIVE, UserReportReason.OFFLINE]: reportedDetail['count'] += 1 if not pktimestamp.is_same_day(currentTimestamp, reportTimestamp): reportedDetail.setdefault(str(r), 0) reportedDetail[str(r)] = 0 else: reportedDetail.setdefault(str(r), 0) reportedDetail[str(r)] += 1 gamedata.setGameAttr(otherPlayerId, gameId, 'reported', strutil.dumps(reportedDetail)) tip = '' if UserReportReason.NEGATIVE in reasons: tip = '举报信息:\n 您因<%s>被玩家举报。\n 系统已记录,下次要认真一些喔~' % cls._getTipByReason( UserReportReason.NEGATIVE) if reportedDetail.setdefault(str(UserReportReason.NEGATIVE), 0) > 5: tip = '' if UserReportReason.OFFLINE in reasons: if reportedDetail.setdefault(str(UserReportReason.OFFLINE), 0) > 5: tip = tip else: tip = '举报信息:\n 您因<%s>被玩家举报。\n 快去找一个好的网络环境吧~' % cls._getTipByReason( UserReportReason.OFFLINE) if tip: pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, otherPlayerId, tip)
def doReportOld(self, gameId, userId, modules): msg = runcmd.getMsgPack() ftlog.debug('ModuletipTcpHandler.report msg=', msg) modulesInfo = hallmoduletip.cancelModulesTip(userId, modules, gameId) mo = ModuletipTcpHandlerHelp.buildInfo('report', modulesInfo) router.sendToUser(mo, userId)
def _doAfterGainNsLoginReward(self, gameId, userId, clientId): # todo task # 如果是3.3的新用户则需要发送启动资金 并发送启动资金todotask # 如果是老用户并没有玩过游戏 发送快速游戏提示的todotask # 如果是老用户并且玩过游戏 发送活动弹窗 if ftlog.is_debug(): ftlog.debug('AccountTcpHandler._doAfterGainNsLoginReward gameId=', gameId, 'userId=', userId, 'clientId=', clientId) clientsys, clientVer, _ = strutil.parseClientId(clientId) if clientVer > 3.32 and clientVer < 3.7 or clientsys == CLIENT_SYS_H5: # clist = gamedata.getGameAttr(userId, gameId, 'history_clientids') # try: # clist = json.loads(clist) if clist else [] # except: # clist = [] send, startChip, final = hallstartchip.sendStartChip( userId, gameId, clientId) if send: if ftlog.is_debug(): ftlog.debug( 'AccountTcpHandler._doAfterGainNsLoginReward gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'sendStartChip=', (send, startChip, final)) assetKind = hallitem.itemSystem.findAssetKind( hallitem.ASSET_ITEM_NEWER_GIFT_KIND_ID) pic = assetKind.pic if assetKind else '' TodoTaskHelper.sendTodoTask( gameId, userId, TodoTaskIssueStartChip(startChip, final, pic, '您有一个新手礼包在‘我的道具’里')) else: winrate = gamedata.getGameAttr(userId, gameId, 'winrate') try: winrate = json.loads(winrate) play_count = winrate['pt'] except: return if ftlog.is_debug(): ftlog.debug( 'AccountTcpHandler._doAfterGainNsLoginReward gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'winrate=', winrate, 'playCount=', play_count) if play_count <= 0: mo = TodoTaskHelper.makeTodoTaskMsg( gameId, userId, TodoTaskQuickStartTip()) router.sendToUser(mo, userId) else: conf = dizhuconf.getPopActivityTemplate(clientId) if ftlog.is_debug(): ftlog.debug( 'AccountTcpHandler._doAfterGainNsLoginReward gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'winrate=', winrate, 'popActivityTemplate=', conf) if conf: todotask = dizhutodotask.makeTodoTaskPopActivity( gameId, userId, clientId, conf) if todotask: TodoTaskHelper.sendTodoTask( gameId, userId, todotask)
def doUpdateOld(self, gameId, userId, modules): msg = runcmd.getMsgPack() ftlog.debug('ModuletipTcpHandler.doUpdate msg=', msg) modulesInfo = hallmoduletip.getInfo(userId, modules, gameId) mo = ModuletipTcpHandlerHelp.buildInfo('update', modulesInfo) router.sendToUser(mo, userId)
def doPutMessage(self, gameId, fromUid, toUid, mtype, msg, ismgr, scope, clientIds): button = runhttp.getParamStr('button', None) button = strutil.loads(button, ignoreException=True) data = None mo = MsgPack() if mtype == 0 and len(msg) > 0 and toUid > 0 and gameId >= 0: # 发送私人消息 # 必须参数 # 1)msg - 消息 # 2)toUid - 接收消息的userId # 3)gameId data = pkmessage.sendPublic(gameId, toUid, fromUid, msg, button) #data = pkmessage.sendPrivate(gameId, toUid, fromUid, msg, button) elif mtype == 1 and len(msg) > 0 and gameId >= 0: # 发送站内消息到全体用户 # 必选参数 # msg - 消息 # gameId data = pkmessage.sendGlobal(gameId, msg, button) elif mtype == 2 and gameId > 0 and len(msg) > 0: # 发送LED # TODO 当前Game服务为4,5,6号 , 每个服务都发送 mo.setCmd('send_led') mo.setParam('msg', msg) mo.setParam('gameId', gameId) mo.setParam('ismgr', 1) router.sendToAll(mo, gdata.SRV_TYPE_UTIL) data = True elif mtype == 3 and gameId > 0 and toUid > 0 and len(msg) > 0: # 封装popwnd # 必选参数 # gameId # toUid 接收弹窗的userId # msg 弹窗消息内容 task = TodoTaskShowInfo(msg, True) mo = TodoTaskHelper.makeTodoTaskMsg(gameId, toUid, task) # 将消息发送给此人 router.sendToUser(mo, toUid) data = True elif mtype in (4, 5) and gameId > 0 and len(msg) > 0 and len(scope) > 0: mo.setCmd('send_led') mo.setParam('msg', msg) ftlog.info('send_led new msg=', msg) mo.setParam('gameId', gameId) ftlog.info('send_led new gameId=', gameId) mo.setParam('ismgr', ismgr) ftlog.info('send_led new ismgr=', ismgr) mo.setParam('scope', scope) ftlog.info('send_led new scope=', scope) mo.setParam('clientIds', clientIds) ftlog.info('send_led new clientIds=', clientIds) mo.setParam('isStopServer', True if mtype == 5 else False) router.sendToAll(mo, gdata.SRV_TYPE_UTIL) data = True if data == None: mo.setError(1, 'params error') else: mo.setResult('ok', 'true') return mo
def getSectionStarRewards(userId, clientId, sectionId, star): """ 领取章节星级奖励 """ mo = MsgPack() mo.setCmd("task") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("action", "sectionStarReward") mo.setResult("star", star) code = 1 # honorId = 0 sectionConf = config.getMainQuestSectionConf(clientId, sectionId) currSectionId = gamedata.getGameAttr(userId, FISH_GAMEID, GameData.currSectionId) gotReward = [] # 检查领取的章节是否为当前生效章节. if sectionConf and sectionId == currSectionId: sectionData = getSection(userId, sectionId) # 检查该星级是否已经领取过. star = int(star) if star not in sectionData[SectionIndex.TakenStars]: starRewards = sectionConf["starRewards"] stars = [] for val in starRewards: stars.append(val["star"]) if val["star"] == star: code = 0 rewards = { "name": val["rewards"][0]["itemId"], "count": val["rewards"][0]["count"] } sectionData[SectionIndex.TakenStars].append(star) gotReward = sectionData[SectionIndex.TakenStars] sectionData[SectionIndex.FinishTime] = int(time.time()) kindId = rewards["name"] if util.isChestRewardId(kindId): rewards = chest_system.getChestRewards(userId, kindId) chest_system.deliveryChestRewards( userId, kindId, rewards, "BI_NFISH_MAIN_QUEST_STAR_REWARDS", param01=star) else: util.addRewards(userId, [rewards], "BI_NFISH_MAIN_QUEST_STAR_REWARDS", int(sectionId), star) module_tip.cancelModuleTipEvent(userId, "mainquest", "star_%d" % star) mo.setResult("rewards", rewards) if code == 0: # 章节任务全部完成并且星级奖励全部领取即可跳转章节. finishTaskIds = sectionData[SectionIndex.FinishTasks] if len(set(sectionConf["taskIds"]) - set(finishTaskIds)) == 0 and len( set(stars) - set(sectionData[SectionIndex.TakenStars])) == 0: # honorId = sectionConf["honorId"] sectionData[ SectionIndex.State] = QuestState.Received # 领取星级奖励 module_tip.cancelModuleTipEvent(userId, "mainquest", sectionId) switchToNextSection(userId, clientId, currSectionId) # 解锁下一个章节 from newfish.game import TGFish event = MainQuestSectionFinishEvent( userId, FISH_GAMEID, sectionId, currSectionId) TGFish.getEventBus().publishEvent(event) setSection(userId, sectionId, sectionData) # 保存当前章节数据 mo.setResult("code", code) mo.setResult("gotReward", gotReward) router.sendToUser(mo, userId) pushCurrTask(userId)