def unlockMatchUser(gameId, userId, bigRoomId, instId, ctrlRoomId, tableId, seatId): if ftlog.is_debug(): ftlog.debug('match_remote.unlockMatchUser gameId=', gameId, 'userId=', userId, 'bigRoomId=', bigRoomId, 'instId=', instId, 'ctrlRoomId=', ctrlRoomId, 'tableId=', tableId, 'seatId=', seatId) if _removeMatchUser(gameId, userId, bigRoomId, instId, ctrlRoomId): try: onlinedata.removeOnlineLoc(userId, ctrlRoomId, tableId) except: ftlog.error('match_remote.unlockMatchUser gameId=', gameId, 'userId=', userId, 'bigRoomId=', bigRoomId, 'instId=', instId, 'ctrlRoomId=', ctrlRoomId, 'tableId=', tableId, 'seatId=', seatId) ftlog.info('match_remote.unlockMatchUser ok gameId=', gameId, 'userId=', userId, 'bigRoomId=', bigRoomId, 'instId=', instId, 'ctrlRoomId=', ctrlRoomId, 'tableId=', tableId, 'seatId=', seatId)
def switchFile(self, data_dir, _type, _group, rec_id, record_count): file_index = rec_id / record_count data_path = "%s/%s/%s/bidata_%s_%s_%d.data" % \ (data_dir, _type, _group, _type, _group, file_index) key = _type + _group fTuple = self.FILE_INFO.get(key) try: if fTuple: fIndex = fTuple[0] if file_index > fIndex: fTuple[1].close() fhandle = open(data_path, 'r+') self.FILE_INFO[key] = (file_index, fhandle) return fhandle elif file_index == fIndex: return fTuple[1] else: return None else: fhandle = open(data_path, 'r+') if fhandle: self.FILE_INFO[key] = (file_index, fhandle) return fhandle except: ftlog.error("open bi file error!", data_path) return None
def _doClearPlayers(self): try: if ftlog.is_debug(): ftlog.debug(self._baseLogStr("<<"), "|gameSeq, agreeN:", self.gamePlay.gameSeq, self.agreeN, caller=self) needSendRes = False if self.agreeN == self.cMaxSeatNum: needSendRes = True if self.gamePlay.gameSeq == 0: needSendRes = True TYPluginCenter.event(TYPluginUtils.updateMsg(cmd=PluginEvents.EV_BEFORE_TABLE_CLEAR_PLAYERS, params={ 'table': self}), self.gameId) # tip = u"您好,此牌桌已解散。" sitUserIds = DiFangPlayersHelper.getSitPlayerIds(self) for userId in sitUserIds: self.sendRoomLeaveReq(userId, TYRoom.LEAVE_ROOM_REASON_SYSTEM, needSendRes=needSendRes) # TodoTaskHelper.sendTodoTask(self.gameId, userId, TodoTaskShowInfo(tip, True)) self.clear() return {"isOK": True} except Exception, e: ftlog.error(e) return {"isOK": False}
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 doSomeLogic(self): if not startup.IS_INIT_OK: print 'not init OK !!' try: self.finish() except: pass return try: taskarg = ftsvr.getTaskRunArg() heads = str(taskarg["userheader1"]) ftlog.debug('WriteTcpRequest 1->', taskarg, heads) _type, _group, rec_id = heads.split('_') global_conf = ftcon.getConf("freetime:global") data_dir = global_conf["data_path"] type_conf = ftcon.getConf("freetime:log_type") log_conf = type_conf[_type] rec_type = int(log_conf["rec_type"]) reserved_size = int(log_conf["reserved_size"]) log_size = int(log_conf["record_size"]) + reserved_size + self.EXTRA_SIZE record_count = log_conf["single_file_record_count"] body = base64.b64decode(taskarg["pack"]) ftlog.debug('WriteTcpRequest 2->', body) cur_time = int(time.time()) record = "tu" + struct.pack("<BIQ", rec_type, cur_time, int(rec_id)) + body + struct.pack( "<%ds" % reserved_size, str()) + "yo" self.writeFile(data_dir, _type, _group, int(rec_id), record_count, log_size, record) except: ftlog.error() finally: try: self.finish() except: pass
def getWinNodesByDropTile(self, dropTile): tingInfos = None if self.TING in self.__extend: tingInfos = self.__extend[self.TING] if self.GRAB_CHI_TING in self.__extend: tingInfos = self.__extend[self.GRAB_CHI_TING][0][self.TING] if self.GRAB_PENG_TING in self.__extend: tingInfos = self.__extend[self.GRAB_PENG_TING][0][self.TING] if self.GRAB_GANG_TING in self.__extend: tingInfos = self.__extend[self.GRAB_GANG_TING][0][self.TING] if self.GRAB_ZHAN_TING in self.__extend: tingInfos = self.__extend[self.GRAB_ZHAN_TING][0][self.TING] if not tingInfos: ftlog.error('getWinNodesByDropTile tingInfos is None, need check:', self.__extend) return None ftlog.debug('getWinNodesByDropTile tingInfos:', tingInfos) for tingSolution in tingInfos: if tingSolution['dropTile'] == dropTile: return tingSolution['winNodes'] return None
def enter(self, userId): '''玩家进入队列''' if self.users.get(userId) != None: ftlog.error(getMethodName(), "already in queue!", self.baseLogStr(None, userId)) return False onlinedata.addOnlineLoc(userId, self.room.roomId, self.room.roomId * 10000, 1) cardLevel, isWinner, isToBeBanker = \ gamedata.getGameAttrs(userId, self.room.gameId, ["cardLevel", "isWinner", "isToBeBanker"]) if cardLevel == None: # 新玩家, 必须初始化cardLevel cardLevel, isWinner, isToBeBanker = 2, False, False gamedata.setGameAttrs(userId, self.room.gameId, ["cardLevel", "isWinner", "isToBeBanker"], [2, False, False]) # 修改users数据的代码段中不允许有异步操作 self.users[userId] = {"enterTime": time.time()} self.users[userId]["cardLevel"], self.users[userId]["isWinner"], self.users[userId]["isToBeBanker"] = \ cardLevel, isWinner, isToBeBanker self.matchTeamMate(userId) if ftlog.is_debug(): ftlog.debug(">>", self.baseLogStr(None, userId), "|self.users[userId]:", self.users[userId], "|locList:", onlinedata.getOnlineLocList(userId), caller=self) return True
def onTimer(self, event): if self.isbusy == 0: # 已经关闭 return dws = [] dwq = [] for x in xrange(len(self._delayWrite)): dw = self._delayWrite[x] dw[0] = dw[0] - 1 if dw[0] <= 0: dws.append(dw[1]) else: dwq.append(dw) self._delayWrite = dwq self._onTimer(event) # 执行延迟时间到时的发送消息 for msg in dws: try: self.writeMsg(msg) except: ftlog.error() self.stop() return # 执行延迟时间到时的事件 mqueue = self._msgQueue ftlog.debug('timer hc=', event.count, 'len(mqueue)=', len(mqueue)) if len(mqueue) > 0: self._msgQueue = [] for msg in mqueue: self.onMsg(msg) if not self.isbusy: return
def _checkAdapter(adapterKey, newAdapters, newConfig, oldAdapters, oldConfig, checkcount): if _DEBUG: debug('_checkAdapter', adapterKey, checkcount) isOK = 1 for ad in newAdapters: if not ad.isOK(): isOK = 0 if _DEBUG: debug('_checkAdapter isOK=', isOK, adapterKey) if isOK: if _DEBUG: debug('all Adapter isOK !!, checkcount=', checkcount, adapterKey) _clietnsmap[adapterKey] = {'config': newConfig, 'adapters': newAdapters, 'sendcount': 0} _closeAllAdapter(oldAdapters) else: if checkcount > 5: _closeAllAdapter(newAdapters) ftlog.error('new Adapters timeout !!!', adapterKey) # FTLoopTimer(1, 0, _startAdapter, adapterKey, newAdapters, newConfig, oldAdapters, oldConfig).start() else: if _DEBUG: debug('not all Adapter isOK, checkcount=', checkcount, adapterKey) FTLoopTimer(1, 0, _checkAdapter, adapterKey, newAdapters, newConfig, oldAdapters, oldConfig, checkcount + 1).start()
def loadStatus(userId, timestamp): ''' 加载用户推广状态 麻将先于大厅做过邀请有礼,从麻将merge数据 ''' d = None status = None try: # 优先迁移跑胡子的配置 ftlog.debug('hall_simple_invite.loadStatus try load from paohuzi...') d = gamedata.getGameAttrJson(userId, 21, NeituiguangSimpleStatus.OLD_KEY) gamedata.delGameAttr(userId, 21, NeituiguangSimpleStatus.OLD_KEY) if not d: # 其次迁移麻将的配置 ftlog.debug('hall_simple_invite.loadStatus try load from majiang...') d = gamedata.getGameAttrJson(userId, 7, NeituiguangSimpleStatus.OLD_KEY) gamedata.delGameAttr(userId, 7, NeituiguangSimpleStatus.OLD_KEY) if not d: # 使用大厅数据 ftlog.debug('hall_simple_invite.loadStatus try load from hall at last...') d = gamedata.getGameAttrJson(userId, HALL_GAMEID, NeituiguangSimpleStatus.NEW_KEY) ftlog.debug('hall_simple_invite.loadStatus status:', d) if d: status = NeituiguangSimpleStatus(userId, timestamp).decodeFromDict(d) except: ftlog.error('invite.loadStatus userId=', userId, 'd=', d) if not status: status = NeituiguangSimpleStatus(userId, timestamp) return status
def handleTableCallChi(self, userId, seatId, message): """处理吃消息 { "clientId": "Android_3.90_360.360,yisdkpay.0-hall6.360.win", "cmd": "table_call", "params": { "gameId": 7, "clientId": "Android_3.90_360.360,yisdkpay.0-hall6.360.win", "userId": 10788, "roomId": 75041001, "tableId": 750410010200, "seatId": 0, "action": "chi", "action_id": 34, "tile": 19, "pattern": [17, 18, 19] } } """ actionId = self.getActionIdFromMessage(message) if actionId == self.table.actionID: chi = message.getParam('tile') chiResult = message.getParam('pattern', None) if not chiResult: ftlog.error('handleTableCallChi pattern is None') self.table.chiTile(seatId, chi, chiResult, MTableState.TABLE_STATE_CHI) else: ftlog.info('wrong actionId:', actionId, ' now table actionId:', self.table.actionID, ' message:', message)
def onHeartBeat(self, event): # 检索延迟时间到时的事件 evts = [] ques = [] for x in xrange(len(self.eventQueue)): evt = self.eventQueue[x] evt.delayTime = evt.delayTime - 1 if evt.delayTime <= 0: evts.append(evt) else: ques.append(evt) self.eventQueue = ques # 执行延迟时间到时的事件 for x in xrange(len(evts)): try: self._processRobotEvent(evts[x]) except: ftlog.error() # 触发所有的机器人的timer事件 for ru in self.busyRobotUsers: try: ru.onTimer(event) except: ftlog.error() # 回收所有已经释放的机器人实例 for x in xrange(len(self.busyRobotUsers) - 1, -1, -1): ru = self.busyRobotUsers[x] if not ru.isbusy: del self.busyRobotUsers[x] self.freeRobotUsers.append(ru)
def onMsg(self): pack = stackless.getcurrent()._fttask.pack ftlog.debug('A2AProtocol->', FTTasklet.concurrent_task_count, '[' + pack + ']') src, dst, queryid, userheader1, userheader2, message = agentmsg.unpack(pack) if src == None or dst == None: ftlog.info("ERROR, recive a error format message") return if self.peer_id == 0: self.peer_id = src ftcon.serverid_protocol_map[self.peer_id] = self ftlog.info("Receive other agent register, agentid=", self.peer_id) return # 处理agent服务自身的命令 if dst == ftcon.global_config["server_id"] and A2AProtocol.onCommand != None: # ftlog.debug('A2AProtocol-> it self command !!') A2AProtocol.onCommand(self, src, queryid, userheader1, userheader2, message) return try: # 从其他agent过来的数据,转给连接的dst service # ftlog.debug('A2AProtocol->send to target->', dst) protocol = ftcon.serverid_protocol_map[dst] if performance.PERFORMANCE_NET: pack = performance.linkMsgTime('LW', pack) protocol.transport.write(pack + '\r\n') except: ftlog.error('msg route error, dst_server_id=', dst)
def _ppsCounter(): if _ppsFunCounts: for fun in _ppsFunCounts: try: fun() except: ftlog.error()
def _reloadConfigLocked(keylist, sleepTime=0.01): from poker.entity.configure import configure from poker.entity.events.tyevent import EventConfigure from poker.entity.events.tyeventbus import globalEventBus ftlog.info('_syncConfigure._reloadConfig keylist=', keylist) if 'all' in keylist: keylist = ['all'] configure.reloadKeys(keylist) _sleepnb(sleepTime) eventErrors = [] datas = {'errorLogGroup': 'configure', 'errorLogParams': keylist } try: _updateRoomDefine(keylist, sleepTime) except: ftlog.error(**datas) eventErrors.append(ftlog.errorInfo()) return eventErrors ftlog.info('_syncConfigure._triggerCnfigureChangedEvent in') globalEventBus.publishEvent(EventConfigure(keylist, []), sleepTime, eventErrors, **datas) ftlog.info('_syncConfigure._triggerCnfigureChangedEvent out') ftlog.info('_syncConfigure finis erros len=', len(eventErrors)) return eventErrors
def getGaoFangIp2(userId, clientId): ip, port = '', 0 try: gaofangConfs = configure.getJson('poker:map.gaofangip.2', {}) policy = gaofangConfs.get('policy') if policy == 'defence2': intClientId = sessiondata.getClientIdNum(userId, clientId) clientIds = gaofangConfs['clientIds'] areaId = clientIds.get(intClientId) if not areaId: areaId = clientIds.get(str(intClientId)) if not areaId: areaId = clientIds.get('default') if not areaId: areaId = gaofangConfs['areas'].keys()[0] ftlog.warn('ERROR, getGaoFangIp2 not found area id of ', intClientId, clientId, 'use default !') clientIds[intClientId] = areaId entrys = gaofangConfs['areas'][areaId] ipPorts = random.choice(entrys) # 切换不同的端口接入 ipPort = ipPorts[userId % len(ipPorts)] # 使用相对固定的IP地址接入 ip, port = ipPort[0], ipPort[1] except: ftlog.error() ftlog.info('getGaoFangIp2->', ip, port, userId, clientId) return ip, port
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 handleRequest(self): if not startup.IS_INIT_OK: print 'not init OK !!' try: self.finish() except: pass return request = None try: taskarg = ftsvr.getTaskRunArg() request = taskarg['data'] heads = request.getAllHeaders() if not "log-type" in heads: return self._doHttpManager(request) _type = heads["log-type"] _group = heads["log-group"] body = request.content.read() pbody = self.parseBody(body, _type) if pbody: logid = ftsvr.doRedis(_group, "INCR", "global:logid:%s:%s" % (_group, _type)) _date = time.strftime("%Y%m%d", time.localtime(int(time.time()))) ftsvr.doRedis(_group, "HSETNX", "day1st:%s:%s" % (_group, _type), _date, logid) self.updateIndex(_type, _group, logid, pbody) self.sendToWriter(_type, _group, logid, body) except: ftlog.error() finally: try: request.finish() except: pass
def _redisCmdPps(group, cmds): global _REDIS_CMDS_, _REDIS_COUNT_, _REDIS_COUNT_TIME_ try: if not group in _REDIS_CMDS_: _REDIS_CMDS_[group] = {} rgroup = _REDIS_CMDS_[group] rcmd = str(cmds[0]).upper() if len(cmds) > 1: rkey = str(cmds[1]).split(':', 1)[0] if rkey not in rgroup: rgroup[rkey] = {} rcmds = rgroup[rkey] if rcmd in rcmds: rcmds[rcmd] += 1 else: rcmds[rcmd] = 1 _REDIS_COUNT_ += 1 # if _REDIS_COUNT_ % _REDIS_COUNT_BLOCK_ == 0: # ct = datetime.now() # dt = ct - _REDIS_COUNT_TIME_ # dt = dt.seconds + dt.microseconds / 1000000.0 # pps = '%0.2f' % (_REDIS_COUNT_BLOCK_ / dt) # _REDIS_COUNT_TIME_ = ct # ftlog.info("REDIS_PPS", pps, 'CMDCOUNT', _REDIS_COUNT_, 'DT %0.2f' % (dt), 'CMDS', json.dumps(_REDIS_CMDS_)) # _REDIS_CMDS_ = {} except: ftlog.error()
def getHallHtmlsInfo(clientId): try: gameId = strutil.getGameIdFromHallClientId(clientId) intClientId = pokerconf.clientIdToNumber(clientId) return configure.getGameTemplateInfo(gameId, 'htmls.info', intClientId, _adjustHallHtmlsInfo) except: ftlog.error('ERROR getHallHtmlsInfo clientId=', clientId)
def mainloop(): if REACTOR_RUN_NORMAL: ftlog.info('Main loop begin. REACTOR_RUN_NORMAL') stackless.tasklet(reactor.run)() reactor.callLater(0, stackless.schedule) stackless.run() ftlog.info('Main loop over. REACTOR_RUN_NORMAL') return loopcount = 0 # 测试代码, 有时接到tcp消息, 却不处理, log也不出, 为何? r = reactor # escape eclipse error r.startRunning() while r._started: try: while r._started: loopcount += 1 if loopcount > 1000000000: loopcount = 0 if loopcount % 100 == 0: ftlog.debug("Main loop 100!") # Advance simulation time in delayed event processors. r.runUntilCurrent() _schedule_reactor() t2 = r.timeout() t = r.running and t2 r.doIteration(t) _schedule_reactor() except: ftlog.error("Main loop error!") else: ftlog.info('Main loop terminated.') finally: _schedule_reactor() ftlog.info('Main loop over.') sys.exit(0)
def getChoosedInfo(self, state): if not state: ftlog.error('MTableStateExtendInfo.getChoosedInfo state error!') if (state & MTableState.TABLE_STATE_CHI) and (state & MTableState.TABLE_STATE_GRABTING): return self.__extend[self.GRAB_CHI_TING][0] if (state & MTableState.TABLE_STATE_PENG) and (state & MTableState.TABLE_STATE_GRABTING): return self.__extend[self.GRAB_PENG_TING][0] if (state & MTableState.TABLE_STATE_GANG) and (state & MTableState.TABLE_STATE_GRABTING): return self.__extend[self.GRAB_GANG_TING][0] if (state & MTableState.TABLE_STATE_ZHAN) and (state & MTableState.TABLE_STATE_GRABTING): return self.__extend[self.GRAB_ZHAN_TING][0] if state & MTableState.TABLE_STATE_HU: return self.__extend[self.WIN][0] if state & MTableState.TABLE_STATE_TING: return self.__extend[self.TING][0] if state & MTableState.TABLE_STATE_GANG: ftlog.debug('MTableStateExtendInfo.getChoosedInfo gangs:', self.__extend[self.GANG] , ' choosed:', self.__extend[self.GANG][0]) return self.__extend[self.GANG][0] if state & MTableState.TABLE_STATE_PENG: return self.__extend[self.PENG][0] if state & MTableState.TABLE_STATE_CHI: return self.__extend[self.CHI][0] if state & MTableState.TABLE_STATE_QIANGGANG: return self.__extend[self.QIANG_GANG_HU][0]
def getWeixinRedEnvelopePassword(gameId, userId, itemId, amount): redenvlopeConf = hallconf.getPublicConf('weixin_redenvlope', {}) if not redenvlopeConf: return -1, '红包系统忙,请稍后再试' response = None try: params = { 'gameId': str(gameId), 'userId': str(userId), 'itemId': str(itemId), 'amount': str(amount) } params['code'] = _signForWeixin(params) response, _ = webpage.webget(redenvlopeConf['url'], postdata_=params, needresponse=True) ftlog.debug('sdkclient.getWeixinRedEnvelopePassword gameId=', gameId, 'userId=', userId, 'itemId=', itemId, 'amount=', amount, 'response=', response) return checkResponse(redenvlopeConf, response) except: ftlog.error('sdkclient.getWeixinRedEnvelopePassword Exception gameId=', gameId, 'userId=', userId, 'itemId=', itemId, 'amount=', amount, 'response=', response) return -1, redenvlopeConf.get('errorInfo')
def getParamsByPlayer(player, timestamp): try: m360kpParams = player.getSigninParam('m360kp') if not m360kpParams: return None gkey = m360kpParams.get('gkey') if not gkey or not isstring(gkey): return None snsId = player.snsId if not snsId or not snsId.startswith('360:'): return None return { 'time': timestamp, 'gkey': gkey, 'uid': snsId[4:], 'matchid': player.matchId, 'skey': 1 } except: ftlog.error('match360kp.getParamsByPlayer userId=', player.userId, 'signinParams=', player.signinParams, 'snsId=', player.snsId) return None
def addPlayerToGroup(serverId, roomId, masterRoomId, groupId, playerList): startTime = time.time() _area, group = findGroup(roomId, groupId) if not group: ftlog.error('group_match_remote.addPlayerToGroup serverId=', serverId, 'roomId=', roomId, 'masterRoomId=', masterRoomId, 'groupId=', groupId, 'playerCount=', len(playerList), 'err=', 'NotFoundGroup') return playerList = decodePlayerList(playerList) for player in playerList: group.addPlayer(player) if ftlog.is_debug(): ftlog.info('group_match_remote.addPlayerToGroup serverId=', serverId, 'roomId=', roomId, 'masterRoomId=', masterRoomId, 'groupId=', groupId, 'userIds=', [p.userId for p in playerList]) ftlog.info('group_match_remote.addPlayerToGroup OK serverId=', serverId, 'roomId=', roomId, 'masterRoomId=', masterRoomId, 'groupId=', groupId, 'playerCount=', len(playerList), 'usedTime=', time.time() - startTime)
def doOldUserGetPrize(cls, gameId, userId, friendId, clientId, action): ''' 老用户领奖接口 ''' conf = hallconf.getNeiTuiGuangConf(clientId) if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo = MsgPack() mpush = None userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state) bindmobile = userdata.getAttr(userId, 'bindMobile') if userstate == 2: if cls.bindOk(bindmobile): prizeGet = cls.sendOldUserPrize(userId, friendId, gameId, conf) NeiTuiGuangProtocolBuilder.buildOldUserPrize(0, action, cls.getprize(gameId, 0, prizeGet), friendId, mo) ##### 推一条用户奖励信息 mpush = cls.doQueryPrize(gameId, userId, clientId, action) else: NeiTuiGuangProtocolBuilder.buildBindPrize(1, action, cls.getprize(gameId, 2), friendId, mo) else: NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, 'user state error: not support', mo) return mo, mpush
def doPromoteCodeCheck(cls, gameId, userId, clientId, action, promoteCode): ''' 验证兑换码ID,有效则获取用户手机绑定信息,若绑定手机,则发送奖励,并更新用户状态。若未绑定手机,则更新用户状态,返回未绑定手机code ''' conf = hallconf.getNeiTuiGuangConf(clientId) if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo = MsgPack() userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state) if userstate == 2: NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '已经领奖成功', mo) else: promoteCode = cls.intPromoteCode(promoteCode) if promoteCode == -1 or userId == promoteCode: NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo) else: userdata.checkUserData(promoteCode) createTime = userdata.getAttr(promoteCode, 'createTime') if createTime == None: NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo) else: olduser = cls.isOldUser(promoteCode, gameId, createTime, conf) if not olduser: NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo) else: gamedata.setGameAttr(userId, gameId, cls.attrname_promotecode, promoteCode) # 记录兑换码 gamedata.setGameAttr(userId, gameId, cls.attrname_state, 1) # 已输入兑换码 bindmobile = userdata.getAttr(userId, 'bindMobile') if cls.bindOk(bindmobile): NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '验证成功', mo) else: NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, cls.getprize(gameId, 2, conf), mo) return mo
def _doGetGameInfoForSdk(self, uidlist, gameIds, for_level_info, for_winchip, for_online_info): users = [] if _USE_FUTURE: fulist = [] for userId in uidlist: if userId: fu = user_remote.getFriendGameInfoFuture(userId, gameIds, for_level_info, for_winchip, for_online_info) fulist.append(fu) for fu in fulist: ret = fu.getResult() if ret != None: users.append(ret) else: users.append({}) else: for userId in uidlist: if userId: try: data = user_remote.getFriendGameInfo(userId, gameIds, for_level_info, for_winchip, for_online_info) except: data = {} ftlog.error() users.append(data) return json.dumps(users)
def onMsg(self): pack = stackless.getcurrent()._fttask.pack ftlog.debug('A2SProtocol->[' + pack + ']') src, dst, queryid, userheader1, userheader2, message = agentmsg.unpack(pack) if src == None or dst == None: ftlog.info("ERROR, recive a error format message") return if self.peer_id == 0: self.peer_id = src ftcon.serverid_protocol_map[self.peer_id] = self ftlog.info("Receive service register, serverid=", self.peer_id, self) return # 处理agent服务自身的命令 if dst == ftcon.global_config["server_id"] and A2SProtocol.onCommand != None: # ftlog.debug('A2SProtocol-> it self command !!') A2SProtocol.onCommand(self, src, queryid, userheader1, userheader2, message) return if dst.find('AG') == 0: # 如果是直接发送给另外的一个AGENT, 那器agent就是其本身 agent_id = dst else: server_conf = ftcon.getServerConf(dst) agent_id = server_conf['agent'] try: # 从src发过来的数据,转给dst所在的agent # 如果是agent所属内部进程过来的数据, 直接转发至dst进程 if agent_id == ftcon.global_config["server_id"]: agent_id = dst # ftlog.debug('A2SProtocol->send to agentid->', agent_id, 'dst=', dst) protocol = ftcon.serverid_protocol_map[agent_id] protocol.transport.write(pack + '\r\n') except: ftlog.error('msg route error, not found agent protocol, dst_server_id=', dst, 'agend=', agent_id)
def tasklet(self): global DEBUG_TASK_MAIN_TIME, DEBUG_TASK_MAP, DEBUG_TASK_SCHEDULE, SLOW_TASK_TIMES self._return_channel = FTChannel() self._me = stackless.getcurrent() if DEBUG_TASK_SCHEDULE: tkey = repr(self._me) DEBUG_TASK_MAP[tkey].insert(0, (self.run_args['creattime'], "create")) DEBUG_TASK_MAP[tkey].append((time(), "run")) self._timeocall = None self._me._fttask = self ctn = time() try: self.handle() ct = time() rtime = ct - ctn time_recv = self.run_args.get('time_recv', 0) if time_recv: time_recv = ctn - time_recv if rtime > SLOW_TASK_TIMES or time_recv > SLOW_TASK_TIMES: ftlog.warn('TASKLET TOO SLOW !! runtime=%0.6f' % (rtime), 'schedule=%0.6f' % (time_recv), 'ct=', ct, 'args=', self.run_args) except: ftlog.error('tasklet handle error', self.run_args) FTTasklet.concurrent_task_count -= 1 if DEBUG_TASK_SCHEDULE: del DEBUG_TASK_MAP[tkey]
'unlockEndGameCount', 'lastIsFirst', 'chessRecord') VALUES = [ 0, 0, 0, '六级棋士', 0, 1400, 0, 0, 0, 0, None] def creat_gamedata(uid, chessExp, totalNum, winNum, loseNum, drawNum): rs = {"totalNum":totalNum, "winNum":winNum, "loseNum":loseNum, "drawNum":drawNum, "escapeNum":0, "singleWinNum":0, "singleLoseNum":0, "initiativeNum":0, "passiveNum":0, "initiativeWinNum":0, "passiveWinNum":0} VALUES[-1] = json.dumps(rs) ftlog.info('PCXQ_USER', 'creat new gamedata of->', uid, VALUES) gamedata.setGameAttrs(uid, 3, DATAKEYS, VALUES) esnsids = [] sid = gdata.serverNum() f = open('/home/tyhall/hall37/pcdatas/d'+str(int(sid)-1)+'.data', 'r') x = 0 for l in f.readlines() : ftlog.info('PCXQ_USER readline ', x, l) x += 1 if l : l = l.strip() snsid, chessExp, totalNum, winNum, loseNum, drawNum = l.split(' ') try: do_xq_user(snsid, int(chessExp), int(totalNum), int(winNum), int(loseNum), int(drawNum)) except: ftlog.error() esnsids.append([snsid, chessExp, totalNum, winNum, loseNum, drawNum]) break ftlog.info('PCXQ_USER ERRSNSIDS=', esnsids)
def doLottery(userId, gameId): ''' 用户抽奖 :param userId: :param gameId: :param clientId: ''' config = _getConfig(gameId) if not config: return nowLevel, _, _ = getNowAndNextLevel(userId, gameId) if nowLevel == 0: ftlog.warn('doLottery error, nowLevel = 0', 'userId =', userId, 'gameId =', gameId) _doLotteryFailed(userId, gameId, 'doLottery error, nowLevel = 0') return nowItems = config['lotteryInfos'][nowLevel - 1]['items'] length = len(nowItems) if length <= 0: ftlog.error('doLottery error, items is []') _doLotteryFailed(userId, gameId, 'doLottery error, items is []') return nowItems = copy.deepcopy(nowItems) nowItems.sort(key=lambda x: x['value']) pool = int( getPool(userId, gameId) * config['lotteryInfos'][nowLevel - 1]['times']) poolUsed = pool if pool < nowItems[0]['value']: pool = nowItems[0]['value'] if pool > nowItems[-1]['value']: pool = nowItems[-1]['value'] intervals = [] if length == 1: intervals.append((nowItems[0], nowItems[0])) else: for i in range(length - 1): for j in range(i + 1, length): if pool >= nowItems[i]['value'] and pool <= nowItems[j][ 'value']: intervals.append((nowItems[i], nowItems[j])) interval = random.choice(intervals) randValue = random.randint(interval[0]['value'], interval[1]['value']) if randValue > pool: selected = interval[0] else: selected = interval[1] ftlog.debug('doLottery success, userId =', userId, 'gameId =', gameId, 'selected =', selected['index'], 'randValue =', randValue, 'pool =', getPool(userId, gameId)) # 重置奖池,添加奖品 _resetPoolAndWinCount(userId, gameId, nowLevel, poolUsed, selected['value']) util_user.addAssetNotify(hallconf.HALL_GAMEID, userId, selected['itemId'], selected['count'], 'HALL_LOTTERY_TASK_REWARD', 0) # 给客户端发中奖消息 mo = MsgPack() mo.setCmd('lotteryTask') mo.setResult('userId', userId) mo.setResult('gameId', gameId) mo.setResult('reward', selected['index']) router.sendToUser(mo, userId) # 发邮件提示 mailInfo = config.get('mail', None) if mailInfo: mail = mailInfo[0] % (time.strftime(mailInfo[1]), selected['fullname']) pkmessage.send(hallconf.HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail)
def __leaveMatch(self, userId, tableId=0, needSendRewardTodoTask=True): playingLen, rankingLen, enterMatchTotal, isSuccess = daobase.executeRankCmd("EVALSHA", self.userLeaveLuaSha, 0, userId) ftlog.hinfo("__leaveMatch remove user from playingRanking", "|roomId, userId, state", self.roomId, userId, self.getStateStr(), "|playingLen, rankingLen, enterMatchTotal, isSuccess", playingLen, rankingLen, enterMatchTotal, isSuccess, "|tableId, needSendRewardTodoTask", tableId, needSendRewardTodoTask, caller=self) # isSuccess 表示成功从 ranking 中删除。加这个检查是为了避免玩家被动离开的同时主动离开,导致二次发奖 if not isSuccess: return if playingLen + rankingLen != enterMatchTotal: ftlog.error(getMethodName(), "playingLen + rankingLen != enterMatchTotal", "|roomId, playingLen, rankingLen:", self.roomId, playingLen, rankingLen, "|enterMatchTotal:", enterMatchTotal) ftlog.hinfo("__leaveMatch |roomId, playingLen, rankingLen:", self.roomId, enterMatchTotal - rankingLen, rankingLen, caller=self) playingLen = enterMatchTotal - rankingLen if ftlog.is_debug(): ftlog.debug("|roomId, playingLen:", self.roomId, playingLen, caller=self) func = functools.partial(self.ranking.sendToAll) FTTimer(1, func) if playingLen < 1: # 第一名离桌 return # 奖励2到n名 rankingOrder = playingLen + 1 self.matchPlugin.rewardWinner(None, self, userId, rankingOrder, self.matchPlugin.rankingKey(self.bigRoomId), self.matchCounter, tableId, needSendRewardTodoTask) TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_USER_MATCH_END', params={ 'userId': userId, 'room': self, 'rankingOrder': rankingOrder}), self.gameId) mconf = self.matchPlugin.match_room_confs[self.bigRoomId] day1EndConf = mconf.get('day1EndConf') if day1EndConf: endPlayerN = day1EndConf.get("endPlayerN", 1) if (self.state == self.MTT_STATE_QUALIFIER and playingLen <= endPlayerN and mconf['betConfIndex'] >= mconf.get("delaySigninBlindBetPoint", 0)): self.state = self.MTT_STATE_DAY1_END ftlog.hinfo("__leaveMatch turn to MTT_STATE_DAY1_END |roomId, playingLen, state:", self.roomId, playingLen, self.getStateStr(), caller=self) self.scheduler.cancelLoop() self.matchPlugin.notifyDay1MatchEndWithPlayerN(self) else: if self.state == self.MTT_STATE_QUALIFIER and playingLen <= self.tableConf["maxSeatN"]: self.state = self.MTT_STATE_PREFINALS ftlog.hinfo("__leaveMatch turn to MTT_STATE_PREFINALS |roomId, playingLen, state:", self.roomId, playingLen, self.getStateStr(), caller=self) self.scheduler.cancelLoop() if playingLen > 1: return # 奖励第一名 userId = daobase.executeRankCmd("ZRANGE", self.matchPlugin.playingRankingKey(self.bigRoomId), -1, -1)[0] daobase.executeRankCmd("EVALSHA", self.userLeaveLuaSha, 0, userId) # 要让第一名leave,否则拆桌时会被加回队列,如果玩家强退并等到loc清除后上线,就会导致下一场比赛人数多出1人 func = functools.partial(self._leave, userId, TYRoom.LEAVE_ROOM_REASON_MATCH_END, needSendRes=False) FTTimer(0, func) # 异步执行,否则GT会死锁 ftlog.hinfo("__leaveMatch remove user from playingRanking,", "|roomId, userId", self.roomId, userId, caller=self) rankingOrder = 1 self.matchPlugin.rewardWinner(None, self, userId, rankingOrder, self.matchPlugin.rankingKey(self.bigRoomId), self.matchCounter, tableId=0) TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_USER_MATCH_END', params={ 'userId': userId, 'room': self, 'rankingOrder': rankingOrder}), self.gameId) self.state = self.MTT_STATE_IDLE func2 = functools.partial(self.__onMatchEnd) FTTimer(0, func2) # 异步执行,否则GT会死锁
def doMasterGetRank(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doMasterGetRank, msg=', msg) return runcmd.newOkMsgPack(code=1)
def doHallLoginReward(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doHallLoginReward, msg=', msg) return runcmd.newOkMsgPack(code=1)
def handleEvent(self, event): ''' 当收到每局结束发送的event时,在activity.py中调用该方法 处理前台活动返回的配置包括客户端配置和服务器配置 ''' ftlog.debug("TYActivityPlayGamePresentGift handleEvent123:", event.role, event.roomLevel, event.roundNum, event.gameId, event.userId, event.clientId) gameId = event.gameId userId = event.userId activityId = self._clientConf.get("id") if not activityId: ftlog.debug("TYActivityPlayGamePresentGift handleEvent not find adtivityId") return if not self.checkOperative(): ftlog.debug("activity expired:", activityId) return # 对_config开始解析配置,conditions玩的局数,默认为1 for cond in self._serverConf["conditions"]: if cond == self._serverConf['accumulateField']: continue condValue = event.get(cond) if isinstance(self._serverConf[cond], list): if condValue not in self._serverConf[cond]: ftlog.debug("TYActivityPlayGamePresentGift handleEvent, condValue not match,cond:", cond) return else: if condValue != self._serverConf[cond]: ftlog.debug("TYActivityPlayGamePresentGift handleEvent, condValue not match,cond:", cond) return # 有效时间 if "dayTimeLimit" in self._serverConf: if not self._checkDayTime(): ftlog.debug("TYActivityPlayGamePresentGift handleEvent, dayTimeLimit not match") return # 所在房间等级 if "presentBased" in self._serverConf: presentBasedValue = event.get(self._serverConf["presentBased"]) presentBasedValue = gdata.getBigRoomId(presentBasedValue) ftlog.debug("TYActivityPlayGamePresentGift handleEvent11:", presentBasedValue) if not presentBasedValue: ftlog.debug("TYActivityPlayGamePresentGift handleEvent, presentBasedvalue not find, presentBased:", self._serverConf["presentBased"]) return else: if (not isinstance(presentBasedValue, int)) or str(presentBasedValue) not in self._serverConf[ "presentConfig"]: ftlog.debug("TYActivityPlayGamePresentGift handleEvent, presentBasedValue not match:", presentBasedValue) return presentNum = self._serverConf["presentConfig"][str(presentBasedValue)] else: presentNum = self._serverConf["presentNum"] # 是否可连续,1表示1天内连续、0表示可连续 accumulateType = self._serverConf["accumulateType"] # 需要领取奖励的局数 rewardNeedNum = self._serverConf["rewardNeedNum"] accumulateKey = "accumulate" hasRewardedKey = "hasRewarded" if accumulateType == 1: accumulateKey = "%s:%s" % (accumulateKey, time.strftime('%Y-%m-%d', time.localtime(time.time()))) hasRewardedKey = "%s:%s" % (hasRewardedKey, time.strftime('%Y-%m-%d', time.localtime(time.time()))) accumulateValue = event.get(self._serverConf["accumulateField"]) if not accumulateValue: ftlog.debug("TYActivityPlayGamePresentGift handleEvent, accumulateValue not find:", self._serverConf["accumulateField"]) return mustContinuous = 0 maxInterval = 0 accumulateIdentiferValue = "noidentifer" nowTimeStamp = int(time.time()) if 'accumulateMustContinuous' in self._serverConf: if self._serverConf["accumulateMustContinuous"] == 1: mustContinuous = 1 maxInterval = self._serverConf.get("accumulateMaxInterval", 300) # 判定是否是同一房间 if "accumulateIdentifer" in self._serverConf: accumulateIdentifer = self._serverConf["accumulateIdentifer"] accumulateIdentiferValue = event.get(accumulateIdentifer) accumulateIdentiferValue = gdata.getBigRoomId(accumulateIdentiferValue) ftlog.debug("this accumulateIdentiferValue bigRoomId is", accumulateIdentiferValue) if not accumulateIdentiferValue: ftlog.debug("TYActivityPlayGamePresentGift handleEvent, accumulateIdentiferValue not find:", accumulateIdentifer) return else: ftlog.error("TYActivityPlayGamePresentGift handleEvent, accumulateIdentifer not find") return userActivityKey = "TYActivity:%d:%d:%s" % (gameId, userId, activityId) ftlog.debug("playGamePresentGift handleEvent:", presentNum, accumulateKey, accumulateValue, accumulateType, accumulateIdentiferValue, mustContinuous, maxInterval, userActivityKey, rewardNeedNum, nowTimeStamp, hasRewardedKey) ret = daobase.executeUserLua(userId, self.HANDLE_EVENT_SCRIPT, 11, presentNum, accumulateKey, accumulateValue, accumulateType, accumulateIdentiferValue, mustContinuous, maxInterval, userActivityKey, rewardNeedNum, nowTimeStamp, hasRewardedKey) ftlog.debug("TYActivityPlayGamePresentGift handleEvent, executeUserLua ret:", ret)
def doComplain(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doComplain, msg=', msg) return runcmd.newOkMsgPack(code=1)
def _checkUserLoc(userId, clientId, matchGameId=0): '''Why: 玩家断线重连时,loc的信息可能与table不一致,conn server需要与table server通讯检查一致性; 导致不一致的原因:服务端重启(特别是roomId、tableId变更) 如果玩家在队列房间或者比赛房间的等待队列中, 此处不做一致性检查,等玩家发起quick_start时由room server检查 What: 与table server通讯检查桌子对象里是否有这个玩家的数据 如果不一致,则回收牌桌金币并清空loc; Return: 如果玩家在房间队列里,返回gameId.roomId.roomId*10000.1 如果玩家在座位上,返回gameId.roomId.tableId.seatId 如果玩家在旁观,返回gameId.roomId.tableId.0 玩家不在table对象里,返回0.0.0.0 ''' truelocs = [] loclist = _getOnlineLocList(userId) for locs in loclist: rid, tid, sid = locs[0], locs[1], locs[2] gid = strutil.getGameIdFromInstanceRoomId(rid) if gid > 0 and rid > 0 and tid > 0: # 到具体的房间或桌子的服务上去查询, 是否是真的在桌子上 if tid == rid * 10000: # 玩家在队列房间或者比赛房间的等待队列中, 此处不做一致性检查,玩家发起quick_start时检查。 truelocs.append('%d.%d.%d.%d' % (gid, rid, tid, sid)) else: seatId, isObserving = 0, 0 try: seatId, isObserving = roommgr.doCheckUserLoc( userId, gid, rid, tid, clientId) except: ftlog.error() continue ftlog.debug('_checkUserLoc->userId=', userId, 'seatId=', seatId, 'isObserving=', isObserving) if seatId > 0 or isObserving == 1: # 还在桌子上游戏, 返回断线重连的信息 if matchGameId > 0: if matchGameId == gid: truelocs.append('%d.%d.%d.%d' % (gid, rid, tid, seatId)) else: truelocs.append('%d.%d.%d.%d' % (gid, rid, tid, seatId)) else: # 已经不再桌子上了, 清理所有的桌子带入金币 if sid > 0: from poker.entity.dao import userchip userchip.moveAllTableChipToChip( userId, gid, 'TABLE_TCHIP_TO_CHIP', 0, clientId, tid) # 清理当前的在线数据 _removeOnlineLoc(userId, rid, tid) else: # 到这儿, 数据是错误的, 删除处理 _removeOnlineLoc(userId, rid, tid) ftlog.debug('_checkUserLoc->', userId, clientId, truelocs) if pokerconf.isOpenMoreTable(clientId): # 新的客户端协议, 对于断线重连支持的时列表格式, 即客户端可以进行多开 return strutil.dumps(truelocs) else: # 老的客户端, 只支持一个桌子 if truelocs: return truelocs[0] return '0.0.0.0'
def doCreateTable(self, userId, gameId, clientId, roomId0, tableId0, playMode): """ 房主创建牌桌 """ if not playMode: ftlog.error('game_handler, cat not create table without playMode...') loc = onlinedata.checkUserLoc(userId, clientId, gameId) lgameId, lroomId, ltableId, lseatId = loc.split('.') lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId) if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >= 0: ftlog.warn('create_table error, user in table', lgameId, lroomId, ltableId, lseatId) sendPopTipMsg(userId, "请稍候,正在进桌...") config = { "type": "quickstart", "pluginParams": { "roomId": lroomId, "tableId": ltableId, "seatId": lseatId } } todotask = TodoTaskEnterGameNew(lgameId, config) mo = MsgPack() mo.setCmd('todo_tasks') mo.setResult('gameId', gameId) mo.setResult('pluginId', lgameId) mo.setResult('userId', userId) mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask)) router.sendToUser(mo, userId) elif self._canEnterGame(userId, gameId): # 保存建桌时间戳 gamedata.setGameAttr(userId, gameId, 'createTableTime', pktimestamp.getCurrentTimestamp()) msg = runcmd.getMsgPack() itemParams = msg.getParam("itemParams") # cardCount为总局数 if "cardCount" in itemParams: cardCountId = itemParams.get('cardCount', 0) cardCountConfig = majiang_conf.getCreateTableConfig(gameId, playMode, 'cardCount', cardCountId) fangka_count = cardCountConfig.get('fangka_count', 1) ftlog.debug('MajiangCreateTable.create_table fangka_count:', fangka_count) playerCount = 4 playerTypeId = itemParams.get('playerType', 1) if playerTypeId: playerTypeConfig = majiang_conf.getCreateTableConfig(gameId, playMode, 'playerType', playerTypeId) playerCount = playerTypeConfig.get('count', 4) ftlog.debug('MajiangCreateTable.create_table playerCount:', playerCount) msg.setParam('isCreateTable', 1) # 标记创建的桌子是 自建桌 from poker.entity.game.rooms.room import TYRoom roomId, checkResult = MajiangCreateTable._chooseCreateRoom(userId, gameId, playMode, playerCount) ftlog.debug('MajiangCreateTable._chooseCreateRoom roomId:', roomId, ' checkResult:', checkResult) if checkResult == TYRoom.ENTER_ROOM_REASON_OK: msg = runcmd.getMsgPack() msg.setCmdAction("room", "create_table") msg.setParam("roomId", roomId) msg.setParam("itemParams", itemParams) msg.setParam('needFangka', fangka_count) ftlog.debug('MajiangCreateTable._chooseCreateRoom send message to room:', msg) router.sendRoomServer(msg, roomId) else: sendPopTipMsg(userId, "暂时无法创建请稍后重试") else: sendPopTipMsg(userId, "暂时无法创建请稍后重试") if router.isQuery(): mo = runcmd.newOkMsgPack(1) router.responseQurery(mo, '', str(userId)) else: ftlog.info('majiang2 game_handler, ignore enter game request...')
def _processRanking(self, rankingDefine, timestamp): if _DEBUG: debug('TYRankingSystemImpl._processRanking rankingId=', rankingDefine.rankingId, 'timestamp=', timestamp) try: status, changed = self._loadOrCreateRankingStatus( rankingDefine, timestamp) if not status: return lastItem = status.getLastItem() # 检查是否没有下一期了 timeCycle = rankingDefine.getCurrentCycle(timestamp) if not timeCycle: if lastItem and lastItem.state == TYRankingStatus.STATE_NORMAL: if _DEBUG: debug( 'TYRankingSystemImpl._processRanking Finished rankingId=', rankingDefine.rankingId, 'issueNumber=', lastItem.issueNumber, 'timestamp=', timestamp) lastItem.state = TYRankingStatus.STATE_FINISH changed = True else: issueNumber = timeCycle.buildIssueNumber() if lastItem and issueNumber > lastItem.issueNumber: if lastItem.state == TYRankingStatus.STATE_NORMAL: lastItem.state = TYRankingStatus.STATE_FINISH changed = True if _DEBUG: debug( 'TYRankingSystemImpl._processRanking Finished rankingId=', rankingDefine.rankingId, 'issueNumber=', lastItem.issueNumber, 'timestamp=', timestamp) if not lastItem or issueNumber > lastItem.issueNumber: if (status.rankingDefine.maxIssueNumber <= 0 or status.totalNumber < status.rankingDefine.maxIssueNumber): status.addItem(issueNumber, timeCycle) status.totalNumber += 1 if _DEBUG: debug( 'TYRankingSystemImpl._processRanking Create rankingId=', rankingDefine.rankingId, 'issueNumber=', issueNumber, 'totalNumber=', status.totalNumber, 'timestamp=', timestamp) changed = True # 检查需要发奖的所有榜单 for item in status.historyList: if item.state == TYRankingStatus.STATE_FINISH: changed = True self._doReward(status, item) while status.count() > status.rankingDefine.keepNumbers: item = status.removeFront() self._rankingDao.removeRankingList( status.rankingDefine.rankingId, item.issueNumber) changed = True if changed: self._saveRankingStatus(status) except: ftlog.error()
def doPromoteQueryState(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doPromoteQueryState, msg=', msg) return runcmd.newOkMsgPack(code=1)
def doHallMatchRoomList(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doHallMatchRoomList, msg=', msg) return runcmd.newOkMsgPack(code=1)
def doPromoteCodeCheck(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doPromoteCodeCheck, msg=', msg) return runcmd.newOkMsgPack(code=1)
def doPromoteGetFriendPrize(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doPromoteGetFriendPrize, msg=', msg) return runcmd.newOkMsgPack(code=1)
def setTipCount(userId, tipModuleName, count, gameId): tipModule = findTipModule(tipModuleName) if not tipModule: ftlog.error("not find tipModule:", tipModuleName) return pkgamedata.setGameAttr(userId, 9999, _buildModuleTipKey(tipModule, gameId, userId), count)
def _timeout(self, d): ftlog.error("Tasklet.waitDefer timeout!!!", d) d.cancel()
def messageReceived(self, channel, message): ftlog.debug('messageReceived->', channel, message) try: funOnMessage(channel, message) except: ftlog.error()
def doGoldLottery(userId, gameId, clientId, number): ''' 金盘抽奖 ''' if number <= 0 or number > 50: ftlog.error( 'doGoldLottery number best be > 0 or <= 50, the msg is fake') return if ftlog.is_debug(): ftlog.debug('hallroulette.doGoldLottery userId:', userId, ' gameId:', gameId, ' clientId:', clientId, ' number:', number) # 添加关于部分情况下每日抽奖次数限制的功能 addLottoryNum = 0 # 0:初始值 1:增加数量1或者隔天后重新开始,初值设置为1 #add50LottoryOrReset = 0 # 0:初始值 1:增加数量1或者隔天后重新开始,初值设置为1 now_time = pktimestamp.getCurrentTimestamp() isSuitableClient = isSuitableClientID(userId, gameId, clientId) if isSuitableClient: tempResult = getWeightConfTemplate(userId, gameId, clientId) lastDoLottoryTime = pkgamedata.getGameAttrInt(userId, HALL_GAMEID, 'LastDoLottoryTime') if not pktimestamp.is_same_day(now_time, lastDoLottoryTime): resetDailyRouletteData(userId, now_time) if 10 == number: dailyDo10LottoryNum = pkgamedata.getGameAttrInt( userId, HALL_GAMEID, 'Do10LottoryNum') do10LottoryMaxTimes = tempResult.get('roulette_10_max_daily_num', 1000) if dailyDo10LottoryNum >= do10LottoryMaxTimes: ftlog.debug( 'hallroulette.doGoldLottery dailyDo10LottoryNum >= do10LottoryMaxTimes, beyond max limit', 'dailyDo10LottoryNum', dailyDo10LottoryNum, 'do10LottoryMaxTimes', do10LottoryMaxTimes) return reach10MaxTimes() else: addLottoryNum = 1 if 50 == number: dailyDo50LottoryNum = pkgamedata.getGameAttrInt( userId, HALL_GAMEID, 'Do50LottoryNum') do50LottoryMaxTimes = tempResult.get('roulette_50_max_daily_num', 1000) if dailyDo50LottoryNum >= do50LottoryMaxTimes: ftlog.debug( 'hallroulette.doGoldLottery dailyDo50LottoryNum >= do50LottoryMaxTimes, beyond max limit', 'dailyDo50LottoryNum', dailyDo50LottoryNum, 'do50LottoryMaxTimes', do50LottoryMaxTimes) return reach50MaxTimes() else: addLottoryNum = 1 # 减少钻石 result = {} count = -(number * 20) trueDelta, _finalCount = userchip.incrDiamond( userId, gameId, count, daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 'HALL_ROULETTE', 0, 0) if not trueDelta: # 消费失败 return toShop() #在扣除砖石后做每日抽奖次数限制的功能的数值设定0 if isSuitableClient: tempResult = getWeightConfTemplate(userId, gameId, clientId) if 1 == addLottoryNum: if 10 == number: pkgamedata.incrGameAttr(userId, HALL_GAMEID, 'Do10LottoryNum', 1) pkgamedata.setGameAttr(userId, HALL_GAMEID, 'LastDoLottoryTime', now_time) if 50 == number: pkgamedata.incrGameAttr(userId, HALL_GAMEID, 'Do50LottoryNum', 1) pkgamedata.setGameAttr(userId, HALL_GAMEID, 'LastDoLottoryTime', now_time) result['10lottoryNum'] = pkgamedata.getGameAttrInt( userId, HALL_GAMEID, 'Do10LottoryNum') result['50lottoryNum'] = pkgamedata.getGameAttrInt( userId, HALL_GAMEID, 'Do50LottoryNum') result['10MaxNum'] = tempResult.get('roulette_10_max_daily_num', 1000) result['50MaxNum'] = tempResult.get('roulette_50_max_daily_num', 1000) ftlog.debug('after change diamond, roulette limit data, 10lottoryNum', result['10lottoryNum'], '50lottoryNum', result['50lottoryNum'], '10MaxNum', result['10MaxNum'], '50MaxNum', result['50MaxNum']) #将抽奖数进行存储,满足bigRewardNumber,使用大奖概率,否则使用小奖概率 addBigRewardToPool(userId, gameId, clientId, number) # 抽奖 items = [] for _num in range(0, number): items.append(doRouletteLottery(userId, gameId, clientId)) result['items'] = items #对抽奖进行修改,连抽的话进行统一的数据库操作 sendGiftsToUser(userId, gameId, clientId, items) #更新钻石 datachangenotify.sendDataChangeNotify(gameId, userId, ['udata']) #抽奖成功,进行小兵的下发 for _ in range(0, number): daobase.executeMixCmd('RPUSH', CURKEY, userId) #统计需求 ftlog.hinfo('doGoldLottery.userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'number=', number, 'rouletteType=', 2, 'rewardItem=', items) TGHall.getEventBus().publishEvent( TYEventRouletteDiamond(userId, gameId, number)) return result
def _sendReward(gameId, activityId, quizResult): if not quizResult in ('l', 'm', 'r'): ftlog.warn('hotfix_match_quiz._sendReward BadQuizResult gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult) return actConf = _getActivityConf() if not actConf: ftlog.warn('hotfix_match_quiz._sendReward NotActConf gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult) return serverConf = actConf.get('serverConf') if not serverConf: ftlog.warn('hotfix_match_quiz._sendReward NotActServerConf gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult) return oddsMap = { 'l': serverConf['leftOdds'], 'm': serverConf['middleOdds'], 'r': serverConf['rightOdds'], } odds = oddsMap.get(quizResult) gameId = int(serverConf['gameId']) intActId = int(serverConf['intActId']) chipAssetId = serverConf['chipAssetId'] ftlog.info('hotfix_match_quiz._sendReward sending... gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult, 'intActId=', intActId, 'chipAssetId=', chipAssetId, 'odds=', odds, 'oddsMap=', oddsMap) totalBet = 0 totalReward = 0 needTotalReward = 0 userIds = _getActUsers(gameId, activityId) for userId in userIds: # class UserQuizStatus(object): # def __init__(self, userId): # self._userId = userId # self._betMap = {} # self._totalBet = 0 status = activity_match_quiz.loadUserQuizStatus( gameId, userId, activityId) betAmount = status.getBet(quizResult, 0) totalBet += status.totalBet if betAmount > 0: rewardCount = betAmount * odds needTotalReward += rewardCount addState = 2 if _setAlreadySentReward(gameId, activityId, userId): try: # 给用户发奖 addOk = user_remote.addAssets(gameId, userId, [{ 'itemId': chipAssetId, 'count': rewardCount }], 'ACTIVITY_CONSUME', intActId) except: ftlog.error( 'hotfix_match_quiz._sendReward RewardUser gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult, 'intActId=', intActId, 'chipAssetId=', chipAssetId, 'odds=', odds, 'oddsMap=', oddsMap, 'userId=', userId, 'rewardCount=', rewardCount, 'status=', status.toDict()) addOk = False addState = 1 if addOk else 0 if addOk: totalReward += rewardCount ftlog.info('hotfix_match_quiz._sendReward RewardUser gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult, 'intActId=', intActId, 'chipAssetId=', chipAssetId, 'odds=', odds, 'oddsMap=', oddsMap, 'userId=', userId, 'rewardCount=', rewardCount, 'addState=', addState, 'status=', status.toDict()) else: ftlog.info('hotfix_match_quiz._sendReward NotRewardUser gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult, 'intActId=', intActId, 'chipAssetId=', chipAssetId, 'odds=', odds, 'oddsMap=', oddsMap, 'userId=', userId, 'status=', status.toDict()) ftlog.info('hotfix_match_quiz._sendReward sent gameId=', gameId, 'activityId=', activityId, 'quizResult=', quizResult, 'intActId=', intActId, 'chipAssetId=', chipAssetId, 'odds=', odds, 'oddsMap=', oddsMap, 'totalBet=', totalBet, 'totalReward=', totalReward, 'needTotalReward=', needTotalReward)
def doQuickStart(self, msg): """ Note: 1> 由于不同游戏评分机制不同,例如德州会根据游戏阶段评分,所以把桌子评分存到redis里,方便各游戏服务器自由刷新。 2> 为了防止同一张桌子同时被选出来分配座位,选桌时会把tableScore里选出的桌子删除,玩家坐下成功后再添加回去,添回去之前无需刷新该桌子的评分。 3> 玩家自选桌时,可能选中一张正在分配座位的桌子,此时需要休眠后重试,只到该桌子完成分配或者等待超时。 """ assert self.roomId == msg.getParam("roomId") userId = msg.getParam("userId") shadowRoomId = msg.getParam("shadowRoomId") tableId = msg.getParam("tableId") clientId = msg.getParam("clientId") ftlog.hinfo(getMethodName(), "->|userId, clientId, roomId, shadowRoomId, tableId:", userId, clientId, self.roomId, shadowRoomId, tableId) if self.runStatus != self.ROOM_STATUS_RUN: FishQuickStart.onQuickStartFailed( FishQuickStart.ENTER_ROOM_REASON_MAINTENANCE, userId, clientId, self.roomId) return if tableId == 0: # 服务器为玩家选择桌子并坐下 _, _, details = bireport.getRoomOnLineUserCount(FISH_GAMEID, True) complete = False roomIds = self.roomDefine.shadowRoomIds # 按VIP等级分桌 vipRoomConf = OrderedDict({6: -3, 3: -6, 1: -8, 0: -10}) vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) index = 0 for level in vipRoomConf: if vipLevel >= level: index = vipRoomConf[level] break for roomId in roomIds[index:]: tableCount = self.roomDefine.configure["gameTableCount"] maxSeatN = self.tableConf["maxSeatN"] if details.get(str(roomId)) < int(tableCount * maxSeatN * 0.9): shadowRoomId = roomId complete = True break if not complete: shadowRoomId = choice(self.roomDefine.shadowRoomIds) tableId = self.getBestTableId(userId, shadowRoomId) else: # 玩家自选桌子坐下 assert isinstance(shadowRoomId, int) and gdata.roomIdDefineMap( )[shadowRoomId].bigRoomId == self.roomDefine.bigRoomId tableId = self.enterOneTable(userId, shadowRoomId, tableId) if not tableId: ftlog.error(getMethodName(), "getFreeTableId timeout", "|userId, roomId, tableId:", userId, self.roomId, tableId) return if ftlog.is_debug(): ftlog.info(getMethodName(), "after choose table", "|userId, shadowRoomId, tableId:", userId, shadowRoomId, tableId) extParams = msg.getKey("params") self.querySitReq(userId, shadowRoomId, tableId, clientId, extParams)
def notifyMatchOver(self, player, group, reason, rankRewards): ''' 通知用户比赛结束了 ''' try: if (reason == MatchFinishReason.USER_WIN or reason == MatchFinishReason.USER_LOSER): try: event_remote.publishMatchWinloseEvent( self._room.gameId, player.userId, self._room.match.matchId, reason == MatchFinishReason.USER_WIN, player.rank, group.stage.matching.startPlayerCount, rankRewards.conf if rankRewards else None) from dizhu.entity.matchhistory import MatchHistoryHandler MatchHistoryHandler.onMatchOver( player.userId, player.group.matchConf.recordId, player.rank, reason == MatchFinishReason.USER_WIN, rankRewards.conf if rankRewards else None, player.group.isGrouping) except: ftlog.error() # 比赛记录保存 try: event = { 'gameId': self._room.gameId, 'userId': player.userId, 'matchId': self._room.match.matchId, 'rank': player.rank, 'isGroup': 1 if player.group.isGrouping else 0 } MatchRecord.updateAndSaveRecord(event) except: ftlog.error() msg = MsgPack() msg.setCmd('m_over') msg.setResult('gameId', group.match.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('reason', reason) msg.setResult('rank', player.rank) try: msg.setResult('beatDownUser', player.beatDownUserName) except: ftlog.debug('NobeatDownUser big match') ftlog.exception() if rankRewards or reason == MatchFinishReason.USER_WIN: msg.setResult( 'info', buildWinInfo(self._room, group, player, rankRewards)) else: msg.setResult('info', buildLoserInfo(self._room, group, player)) msg.setResult('mucount', group.getStartPlayerCount()) msg.setResult('date', str(datetime.now().date().today())) msg.setResult('time', time.strftime('%H:%M', time.localtime(time.time()))) msg.setResult('addInfo', '') if rankRewards: from dizhu.bigmatch.match import BigMatch msg.setResult('reward', BigMatch.buildRewards(rankRewards)) rewardDesc = BigMatch.buildRewardsDesc(rankRewards) if rewardDesc: msg.setResult('rewardDesc', rewardDesc) msg.setResult('mname', self._room.roomConf["name"]) 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': 1 if player.group.isGrouping else 0, 'crownCount': 1 if player.rank == 1 else 0, 'playCount': 1 }) router.sendToUser(msg, player.userId) if player.rank == 1 and self._room.roomConf.get('championLed'): ledtext = '玩家%s在斗地主"%s"中过五关斩六将夺得冠军,获得%s!' % ( player.userName, self._room.roomConf['name'], rewardDesc) user_remote.sendHallLed(DIZHU_GAMEID, ledtext, 1, 'global', []) sequence = int(group._stage.instId.split('.')[1]) self.report_bi_game_event("MATCH_FINISH", player.userId, group.match.matchId, 0, sequence, 0, 0, 0, [], 'match_end') #_stage.matchingId except: ftlog.error()
def doUserToDoTask(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doUserToDoTask, msg=', msg) return runcmd.newOkMsgPack(code=1)
def lineLengthExceeded(self, line): super(FTTCPServerProtocol, self).lineLengthExceeded(line) ftlog.error('the FTTCPServerProtocol lineLengthExceeded ERROR !!')
def process(self): try: _countProtocolPack(2, self, 1000) except: ftlog.error()
def __init__(self, config_json): self._timelist = [] self._dayslist = [] try: if isinstance(config_json, basestring): self._config = json.loads(config_json) else: self._config = config_json # 整理一天内的时间点列表 if "list" in self._config["times_in_day"]: lt = self._config["times_in_day"]["list"] for l in lt: lg = l.split(":") hour = int(lg[0]) minu = int(lg[1]) self._timelist.append(datetime.time(hour, minu, 0)) else: first = self._config["times_in_day"]["first"] inter = int(self._config["times_in_day"]["interval"]) count = self._config["times_in_day"]["count"] lg = first.split(":") hour = int(lg[0]) minu = int(lg[1]) ftime = datetime.time(hour, minu, 0) self._timelist.append(ftime) dtime = datetime.timedelta(minutes=inter) for x in xrange(count): ftime = (datetime.datetime.combine(datetime.date(1, 1, 1), ftime) + dtime).time() if ftime > self._timelist[0]: self._timelist.append(ftime) else: ftlog.debug("warning!!! times_in_day count too large!!!", x) break # 整理天列表 if "list" in self._config["days"]: ld = self._config["days"]["list"] for d in ld: self._dayslist.append(datetime.datetime.strptime(d, "%Y%m%d")) else: first = self._config["days"]["first"] inter = self._config["days"]["interval"] ninter = int(inter[0]) iinter = inter[1] if iinter == 'd': intdelta = relativedelta(days=ninter) if iinter == 'w': intdelta = relativedelta(weeks=ninter) if iinter == 'm': intdelta = relativedelta(months=ninter) if iinter == 'y': intdelta = relativedelta(years=ninter) count = self._config["days"]["count"] if count > self.MAX_DAY_COUNT: count = self.MAX_DAY_COUNT ftlog.debug("warning!!! days count too large!!!", count) firsts=[] if not first: firsts.append(first) elif isinstance(first, (unicode, str)): firsts.append(first) elif isinstance(first, list): firsts=first for first in firsts: if first: fday = datetime.datetime.strptime(first, "%Y%m%d") else: fday = datetime.datetime.now() self._dayslist.append(fday) for x in xrange(count): fday = fday + intdelta self._dayslist.append(fday) self._dayslist.sort() self._timelist.sort() except: ftlog.error("parse config json error:", config_json) self._config = None
def tcp(cls, p): try: p.MAX_LENGTH = _SocketOpt.TCP_LINE_MAX_LENGTH except: ftlog.error() try: p.transport.setTcpNoDelay(1) except: ftlog.error() try: p.transport.setTcpKeepAlive(1) except: ftlog.error() try: p.transport.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 180) except: ftlog.error() try: p.transport.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 30) except: ftlog.error() try: p.transport.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 10) # p.transport.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 128*1024) except: ftlog.error()
def _addBoss(self, isSysTimerCall=True, nextStage=0x1000): """ 添加宝箱boss """ if nextStage != self._isBossShowTimeStage: self._removeBossShowTimeStage(self._isBossShowTimeStage) self._addBossShowTimeStage(nextStage) stage = 0x1000 if self._isBossShowTimeStage == 0x1000: # 出生鱼阵 有保护罩. fishType = self._maskFishType _bossGroupIds = self.table.runConfig.allSuperBossBornGroupIds[ fishType] stage = 0x1 elif self._isBossShowTimeStage == 0x1: # 第一阶段 有保护罩. fishType = self._maskFishType _bossGroupIds = self.random_boss_groupid(fishType) if not isSysTimerCall: stage = 0x1 else: stage = 0x10 elif self._isBossShowTimeStage == 0x10: # 受伤鱼阵 无保护罩. fishType = self._fishType _bossGroupIds = self.table.runConfig.allSuperBossBornGroupIds[ fishType] stage = 0x100 elif self._isBossShowTimeStage == 0x100: # 第二阶段 无保护罩. fishType = self._fishType _bossGroupIds = self.random_boss_groupid(fishType) stage = 0x100 else: return # nowTime = int(time.time()) # boss超出最大存在时间后不再出现. # if nowTime >= self._startTS + self.queenConf["maxAliveTime"]: # self._removeBossShowTimeStage(self._isBossShowTimeStage) # return if self._autofillTimer: self._autofillTimer.cancel() self._autofillTimer = None # 处理冰冻自动填充时机延后逻辑. if self._group and not isSysTimerCall and self._group.extendGroupTime > 0: # 该鱼群冰冻延长的时间 self._autofillTimer = FTLoopTimer(self._group.extendGroupTime, 0, self._addBoss, False, stage) self._autofillTimer.start() self._group.extendGroupTime = 0 return _bossGroupId = random.choice(_bossGroupIds) if not _bossGroupId: return self._group = self.table.insertFishGroup(_bossGroupId) if self._group: # 龙女王的离场时间 interval = self._group.getFishExitTime(fishType) self._autofillTimer = FTLoopTimer(interval, 0, self._addBoss, False, stage) # 自动填充下一阶段的鱼阵 self._autofillTimer.start() if ftlog.is_debug(): ftlog.debug("QueenFishGroup _addBoss", self.table.tableId, _bossGroupId, stage, interval) else: ftlog.error("QueenFishGroup _addBoss error", _bossGroupId)
def doTaskChange(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doTaskChange, msg=', msg) return runcmd.newOkMsgPack(code=1)
def _getFriendGameInfo(userId, gameIds, for_level_info, for_winchip, for_online_info=1): uid = int(userId) datas = {} gid, rid, tid, sid = 0, 0, 0, 0 state = daoconst.OFFLINE if for_online_info: loclist = onlinedata.getOnlineLocList(uid) state = onlinedata.getOnlineState(uid) if len(loclist) > 0: _rid, _tid, _sid = loclist[0] # gid表示用户在哪个游戏中 gid = strutil.getGameIdFromInstanceRoomId(_rid) # 检查是否可加入游戏 if TYGame(gid).canJoinGame(userId, _rid, _tid, _sid): # rid/tid/sid表示用户所在的游戏是否可加入游戏 # 分享出来的都是可以加入游戏的牌桌信息 rid = _rid tid = _tid sid = _sid if ftlog.is_debug(): ftlog.debug('getFriendGameInfo userId:', userId, ' gameId:', gid, ' roomId:', _rid, ' tableId:', _tid, ' seatId:', _sid, ' can not join game....') if state == daoconst.OFFLINE: offline_time = gamedata.getGameAttr(uid, HALL_GAMEID, 'offlineTime') if not offline_time: # 取不到离线时间,取上线时间 offline_time = userdata.getAttr(uid, 'authorTime') if offline_time: offline_time = pktimestamp.parseTimeMs(offline_time) delta = datetime.now() - offline_time delta = delta.days * 24 * 60 + delta.seconds / 60 # 分钟数 else: # 异常情况 delta = 24 * 60 datas['offline_time'] = delta if delta > 0 else 1 if rid > 0: try: room = gdata.roomIdDefineMap().get(rid, None) if room: datas['room_name'] = room.configure['name'] except: ftlog.error() # 构造回传给SDK的游戏数据 datas.update({ 'uid': uid, 'gid': gid, 'rid': rid, 'tid': tid, 'sid': sid, 'state': state }) if for_level_info: datas['level_game_id'] = 0 datas['level'] = 0 datas['level_pic'] = '' try: for gameId in gameIds: if gameId not in gdata.games(): continue dashifen_info = gdata.games()[gameId].getDaShiFen(uid, '') if dashifen_info: level = dashifen_info['level'] if level > 0 and level > datas['level']: datas['level_game_id'] = gameId datas['level'] = level level_pic = dashifen_info.get('picbig') datas[ 'level_pic'] = level_pic if level_pic else dashifen_info.get( 'pic') except: ftlog.error() if for_winchip: datas['winchip'] = 0 datas['winchips'] = 0 try: for gameId in gameIds: winchips, todaychips = gamedata.getGameAttrs( userId, gameId, ['winchips', 'todaychips'], False) winchips = strutil.parseInts(winchips) yest_winchip = 0 todaychips = strutil.loads(todaychips, ignoreException=True) if todaychips and 'today' in todaychips and 'chips' in todaychips and 'last' in todaychips: if pktimestamp.formatTimeDayInt() == todaychips['today']: yest_winchip = todaychips['last'] elif pktimestamp.formatTimeYesterDayInt( ) == todaychips['today']: yest_winchip = todaychips['chips'] datas['winchip'] += yest_winchip datas['winchips'] += winchips except: ftlog.error() return datas
def doProductDelivery(self): msg = runcmd.getMsgPack() ftlog.error('NotImplementedError, doProductDelivery, msg=', msg) return runcmd.newOkMsgPack(code=1)