class MatchStatusDaoDizhu(MatchStatusDao): def __init__(self, room): self._room = room self._logger = Logger() self._logger.add('roomId', self._room.roomId) def load(self, matchId): ''' 加载比赛信息 @return: MatchStatus ''' key = 'mstatus:%s' % (self._room.gameId) jstr = daobase.executeMixCmd('hget', key, matchId) if jstr: d = json.loads(jstr) return MatchStatus(matchId, d['seq'], d['startTime']) return None def save(self, status): ''' 保存比赛信息 ''' try: key = 'mstatus:%s' % (self._room.gameId) d = {'seq': status.sequence, 'startTime': status.startTime} jstr = json.dumps(d) daobase.executeMixCmd('hset', key, status.matchId, jstr) except: self._logger.error('MatchStatusDaoDizhu.save', 'matchId=', status.matchId, 'instId=', status.instId, 'startTime=', status.startTime)
def __init__(self, table): super(DizhuGroupMatchSender, self).__init__(table) if not self.table : from dizhu.gametable.dizhu_table import DizhuTable self.table = DizhuTable() self._logger = Logger() self._logger.add('roomId', self.table.roomId) self._logger.add('tableId', self.table.tableId)
def __init__(self, room, tableId): super(DizhuGroupMatchTable, self).__init__(room, tableId) self._match_table_info = None self.gamePlay.sender = DizhuGroupMatchSender(self) self._doMatchTableClear() self._logger = Logger() self._logger.add('gameId', self.gameId) self._logger.add('roomId', room.roomId) self._logger.add('tableId', tableId) self._logger.add('matchId', room.bigmatchId)
def __init__(self, roomdefine): super(TYGroupMatchRoom, self).__init__(roomdefine) self.bigmatchId = self.bigRoomId self.matchPlugin = gdata.games()[self.gameId].getGroupMatchPlugin() self.match = None self.matchMaster = None self._logger = Logger() self._logger.add('roomId', self.roomId) self._logger.add('bigmatchId', self.bigmatchId) serverType = gdata.serverType() if serverType == gdata.SRV_TYPE_ROOM: self.initMatch() # 此处会给self.match赋值
def __init__(self, room, tableSeatCount): self._room = room self._tableSeatCount = tableSeatCount self._idleTables = [] self._allTableMap = {} self._roomIds = set() self._logger = Logger() self._logger.add('roomId', self._room.roomId)
class MatchRewardsDizhu(MatchRewards): def __init__(self, room): self._room = room self._logger = Logger() self._logger.add('roomId', self._room.roomId) def sendRewards(self, player, rankRewards): '''给用户发送奖励''' try: self._logger.info('MatchRewardsDizhu.sendRewards', 'groupId=', player.group.groupId if player.group else None, 'score=', player.score, 'rank=', player.rank, 'rankRewards=', rankRewards.rewards) user_remote.addAssets(self._room.gameId, player.userId, rankRewards.rewards, 'MATCH_REWARD', self._room.roomId) if rankRewards.message: pkmessage.sendPrivate(self._room.gameId, player.userId, 0, rankRewards.message) datachangenotify.sendDataChangeNotify(self._room.gameId, player.userId, 'message') except: self._logger.error('MatchRewardsDizhu.sendRewards', 'groupId=', player.group.groupId if player.group else None, 'score=', player.score, 'rank=', player.rank, 'rankRewards=', rankRewards.rewards)
class DizhuGroupMatchTable(DizhuTable): MSTART_SLEEP = 3 def __init__(self, room, tableId): super(DizhuGroupMatchTable, self).__init__(room, tableId) self._match_table_info = None self.gamePlay.sender = DizhuGroupMatchSender(self) self._doMatchTableClear() self._logger = Logger() self._logger.add('gameId', self.gameId) self._logger.add('roomId', room.roomId) self._logger.add('tableId', tableId) self._logger.add('matchId', room.bigmatchId) def _doTableManage(self, msg, action): ''' 处理来自大比赛的table_manage命令 ''' if action == 'm_table_start': self.doMatchTableStart(msg) return if action == 'm_table_info': self.doUpdateMatchTableInfo(msg) return if action == 'm_table_clear': self.doMatchTableClear(msg) return def _checkMNotes(self, mnotes): if not isinstance(mnotes, dict): self._logger.error('GameTable._checkMNotes', 'err=', 'matchTableInfo.mnotes must be dict') return False keyTypeList = [('basescore', (str, unicode)), ('type', (str, unicode)), ('step', (str, unicode)), ('isStartStep', (bool)), ('isFinalStep', (bool)), ('startTime', (str, unicode))] for k, t in keyTypeList: v = mnotes.get(k, None) if not isinstance(v, t): self._logger.error('GameTable._checkMNotes', 'err=', 'matchTableInfo.%s must be %s' % (k, t)) return False return True def _checkSeatInfos(self, seatInfos): if not isinstance(seatInfos, list): self._logger.error('GameTable._checkSeatInfos', 'err=', 'matchTableInfo.seats must be list') return False if len(seatInfos) != len(self.seats): self._logger.error('GameTable._checkSeatInfos', 'seatCount', len(self.seats), 'seatInfoCount=', len(seatInfos), 'err=', 'BadSeatInfoCount') return False for seatInfo in seatInfos: if not isinstance(seatInfo, dict): self._logger.error('GameTable._checkSeatInfos', 'err=', 'seats.item must be dict') return False userId = seatInfo.get('userId') cardCount = seatInfo.get('cardCount') if not isinstance(userId, int): self._logger.error('GameTable._checkSeatInfos', 'err=', 'seats.item.userId must be int') return False if not isinstance(cardCount, int): self._logger.error('GameTable._checkSeatInfos', 'err=', 'seats.item.cardCount must be int') return False return True def _checkMInfos(self, mInfos): if not isinstance(mInfos, dict): self._logger.error('GameTable._checkMInfos', 'err=', 'matchTableInfo.mInfos must be dict') return False return True def _checkRanks(self, ranks): if not isinstance(ranks, list): self._logger.error('GameTable._checkRanks', 'err=', 'matchTableInfo.ranks must be list') return False return True def _checkStepInfo(self, stepInfo): if not isinstance(stepInfo, dict): self._logger.error('GameTable._checkStepInfo', 'err=', 'matchTableInfo.step must be dict') return False name = stepInfo.get('name') playerCount = stepInfo.get('playerCount') riseCount = stepInfo.get('riseCount') cardCount = stepInfo.get('cardCount') if not isstring(name): self._logger.error('GameTable._checkStepInfo', 'err=', 'matchTableInfo.step.name must be str') return False if not isinstance(playerCount, int): self._logger.error('GameTable._checkStepInfo', 'err=', 'matchTableInfo.step.playerCount must be int') return False if not isinstance(riseCount, int): self._logger.error('GameTable._checkStepInfo', 'err=', 'matchTableInfo.step.riseCount must be int') return False if not isinstance(cardCount, int): self._logger.error('GameTable._checkStepInfo', 'err=', 'matchTableInfo.step.cardCount must be int') return False return True def _getUserIdsFromTableInfo(self, tableInfo): userIds = [] for seatInfo in tableInfo['seats']: userIds.append(seatInfo['userId']) return userIds def _checkMatchTableInfo(self, tableInfo): return True if not isinstance(tableInfo, dict): self._logger.error('GameTable._checkMatchTableInfo', 'err=', 'matchTableInfo must be dict') return False roomId = tableInfo.get('roomId') tableId = tableInfo.get('tableId') matchId = tableInfo.get('matchId') if self.roomId != roomId or self.tableId != tableId or self.room.bigmatchId != matchId: self._logger.error('GameTable._checkMatchTableInfo', 'roomIdParam=', roomId, 'tableIdParam=', tableId, 'matchIdParam=', matchId, 'err=', 'diff roomId or tableId or bigmatchId') return False ccrc = tableInfo.get('ccrc') if not isinstance(ccrc, int): self._logger.error('GameTable._checkMatchTableInfo', 'err=', 'ccrc must be int') return False mnotes = tableInfo.get('mnotes') if not self._checkMNotes(mnotes): return False seatInfos = tableInfo.get('seats') if not self._checkSeatInfos(seatInfos): return False mInfos = tableInfo.get('mInfos') if not self._checkMInfos(mInfos): return False ranks = tableInfo.get('ranks') if not self._checkRanks(ranks): return False return True step = tableInfo.get('step') if not self._checkStepInfo(step): return False return True def doMatchTableStart(self, msg): if self._logger.isDebug(): self._logger.debug('GameTable.doMatchTableStart', 'msg=', msg) startTime = int(time.time()) table_info = msg.getKey('params') if self._checkMatchTableInfo(table_info): self._doUpdateTableInfo(table_info) self._doMatchQuickStart() if self._logger.isDebug(): self._logger.debug('GameTable.doMatchTableStart', 'msg=', msg, 'used=', int(time.time()) - startTime) def doUpdateMatchTableInfo(self, msg): if self._logger.isDebug(): self._logger.debug('GameTable.doUpdateMatchTableInfo', 'msg=', msg) table_info = msg.getKey('params') if not self._checkMatchTableInfo(table_info): return if (self._match_table_info and self._match_table_info['ccrc'] != table_info['ccrc']): self._logger.error('GameTable.doUpdateMatchTableInfo', 'msg=', msg, 'ccrc=', self._match_table_info['ccrc'], 'ccrcParam=', table_info['ccrc'], 'err=', 'diff ccrc') return self._doUpdateTableInfo(table_info) for seatInfo in table_info['seats']: clientVer = sessiondata.getClientIdVer(seatInfo['userId']) mnotes = self._match_table_info.get('mnotes', {}) if clientVer < 3.37: mn = MsgPack() mn.setCmd('m_note') mn.setResult('note', mnotes.get('incrnote')) mn.setResult('basescore', mnotes.get('basescore')) mn.setResult('mInfos', self._match_table_info.get('mInfos', {})) router.sendToUser(mn, seatInfo['userId']) else: mn = MsgPack() mn.setCmd('m_note') mn.setResult('note', self._buildNote(seatInfo['userId'], table_info)) mn.setResult('basescore', mnotes.get('basescore')) mn.setResult('mInfos', table_info.get('mInfos', {})) router.sendToUser(mn, seatInfo['userId']) def doMatchTableClear(self, msg): if self._logger.isDebug(): self._logger.debug('GameTable.doMatchTableClear', 'msg=', msg) params = msg.getKey('params') matchId = params.get('matchId', -1) ccrc = params.get('ccrc', -1) if matchId != self.room.bigmatchId: self._logger.error('GameTable.doMatchTableClear', 'msg=', msg, 'err=', 'DiffMatchId') return if not self._match_table_info: self._logger.error('GameTable.doMatchTableClear', 'msg=', msg, 'err=', 'table match is clear') return if ccrc != self._match_table_info['ccrc']: self._logger.error('GameTable.doMatchTableClear', 'msg=', msg, 'ccrc=', self._match_table_info['ccrc'], 'err=', 'diff ccrc') return self._doMatchTableClear() def _doMatchTableClear(self): for seatIndex in xrange(len(self.seats)): uid = self.seats[seatIndex].userId if uid > 0: clientId = sessiondata.getClientId(uid) #比赛阶段清理牌桌时无需刷新客户端 self.gamePlay.doStandUp(uid, seatIndex + 1, TYRoom.LEAVE_ROOM_REASON_MATCH_END, clientId) self.clear(None) self._time_stamp = 0 self._match_table_info = None def _doSit(self, msg, userId, seatId, clientId): ''' 大比赛牌桌只有玩家断线重连时才会触发坐下操作,既重新坐回牌桌 ''' super(DizhuGroupMatchTable, self)._doSit(msg, userId, seatId, clientId) self._sendRank(userId) def _doUpdateTableInfo(self, tableInfo): self._time_stamp = time.time() self._match_table_info = tableInfo def _doMatchQuickStart(self): tableInfo = self._match_table_info seatInfos = tableInfo['seats'] userIds = [] userSeatList = [] for x in xrange(len(seatInfos)): this_seat = self.seats[x] userIds.append(seatInfos[x]['userId']) this_seat.userId = seatInfos[x]['userId'] this_seat.state = TYSeat.SEAT_STATE_WAIT this_seat.call123 = -1 userSeatList.append((seatInfos[x]['userId'], x + 1)) # 初始化用户数据 for x in xrange(len(self.players)): self.players[x].initUser(0, 1) # ctrlRoomId = self.room.ctrlRoomId # ctrlRoomTableId = ctrlRoomId * 10000 for userId, seatId in userSeatList: try: onlinedata.setBigRoomOnlineLoc(userId, self.roomId, self.tableId, seatId) # onlinedata.removeOnlineLoc(userId, ctrlRoomId, ctrlRoomTableId) # onlinedata.addOnlineLoc(userId, self.roomId, self.tableId, seatId) if self._logger.isDebug(): self._logger.debug( 'GameTable._doMatchQuickStart setBigRoomOnlineLoc', 'userId=', userId, 'tableId=', self.tableId, 'seatId=', seatId) except: self._logger.error('GameTable._doMatchQuickStart') # 增加从比赛等待界面到下一局开始时的时间间隔 inter = self.__getWaitToNextMatchInter() ftlog.debug("test __getWaitToNextMatchInter inter = ", inter, 'time = ', time.time(), caller=self) if inter > 0: FTTasklet.getCurrentFTTasklet().sleepNb(inter) ftlog.debug("test __getWaitToNextMatchInter inter 2 = ", inter, 'time = ', time.time(), caller=self) for x in xrange(len(self.seats)): this_seat = self.seats[x] if this_seat.userId > 0: mq = MsgPack() mq.setCmd('quick_start') mq.setResult('userId', this_seat.userId) mq.setResult('gameId', self.gameId) mq.setResult('roomId', self.roomId) mq.setResult('tableId', self.tableId) mq.setResult('seatId', x + 1) # 发送用户的quick_start router.sendToUser(mq, this_seat.userId) # 发送table_info self.gamePlay.sender.sendTableInfoResAll() # 延迟1秒进行animation Info相关处理 FTTasklet.getCurrentFTTasklet().sleepNb(1) playAnmi = self._playAnimationIfNeed(tableInfo) if playAnmi['playAnimation'] and playAnmi['delaySeconds'] > 0: FTTasklet.getCurrentFTTasklet().sleepNb(playAnmi['delaySeconds']) for x in xrange(len(self.players)): self.gamePlay.doReady(self.players[x], False) mnotes = self._match_table_info['mnotes'] mtype = mnotes['type'] isFinalStep = mnotes.get('isFinalStep', False) if isFinalStep: mtype = mtype + u',决胜局!' isStartStep = mnotes.get('isStartStep', False) if isStartStep: for userId in userIds: clientVer = sessiondata.getClientId(userId) if clientVer < 3.37: mn = MsgPack() mn.setCmd('m_note') mn.setResult('note', mtype) mn.setResult('mInfos', self._match_table_info['mInfos']) router.sendToUser(mn, userId) else: mn = MsgPack() mn.setCmd('m_note') mn.setResult('note', self._buildNote(userId, tableInfo)) mn.setResult('mInfos', self._match_table_info['mInfos']) router.sendToUser(mn, userId) bscore = mnotes.get('basescore', '') step = mnotes.get('step', '') note = bscore + u',' + step func = functools.partial(self.sendMNoteMsg, userIds, note) FTTimer(3, func) for userId in userIds: self._sendRank(userId) def sendMNoteMsg(self, userIds, note): if self._match_table_info: for userId in userIds: clientVer = sessiondata.getClientIdVer(userId) if clientVer < 3.37: mnote = MsgPack() mnote.setCmd('m_note') mnote.setResult('note', note) router.sendToUser(mnote, userId) else: mnote = MsgPack() mnote.setCmd('m_note') mnote.setResult( 'note', self._buildNote(userId, self._match_table_info)) router.sendToUser(mnote, userId) def _buildNote(self, userId, tableInfo): ''' Note: DizhuSender.sendTableInfoRes will invoke this func ''' if tableInfo['step']['type'] == StageType.ASS: return u'%s:%s人晋级,低于%s分将被淘汰' % (tableInfo['step']['name'], tableInfo['step']['riseCount'], tableInfo['mInfos']['asslosechip']) else: for seatInfo in tableInfo['seats']: if seatInfo['userId'] == userId: return u'%s:%s人晋级,第%s副(共%s副)' % ( tableInfo['step']['name'], tableInfo['step']['riseCount'], seatInfo['cardCount'], tableInfo['step']['cardCount']) return '' def _buildMatchStepInfo(self, userId, tableInfo): res = {'curCount': -1, 'totoal': -1} for seatInfo in tableInfo['seats']: if seatInfo['userId'] == userId: res['curCount'] = seatInfo['cardCount'] res['totoal'] = tableInfo['step']['cardCount'] return res def _playAnimationIfNeed(self, tableInfo): ret = {'playAnimation': False, 'delaySeconds': 0} # if self._match_table_info['step']['animationType'] != AnimationType.UNKNOWN: for x in xrange(len(self.seats)): this_seat = self.seats[x] if this_seat.userId > 0: clientVer = sessiondata.getClientIdVer(this_seat.userId) animationType = self.__getAnimationType(clientVer) if animationType != AnimationType.UNKNOWN: msg = MsgPack() msg.setCmd('m_play_animation') msg.setResult('gameId', self.gameId) msg.setResult('roomId', self.roomId) msg.setResult('tableId', self.tableId) # msg.setResult('type', self._match_table_info['step']['animationType']) msg.setResult('type', animationType) mnotes = self._match_table_info['mnotes'] isStartStep = mnotes.get('isStartStep', False) # 添加是否是第一个阶段的标志,是的话前端播放开始比赛的动画 msg.setResult('isStartStep', isStartStep) # 组织当前比赛是第几局、共几局的信息 msg.setResult( 'curMatchStep', self._buildMatchStepInfo(this_seat.userId, tableInfo)) router.sendToUser(msg, this_seat.userId) curDelay = self.__getAnimationInter( animationType, isStartStep, clientVer) if curDelay > ret['delaySeconds']: ret['delaySeconds'] = curDelay ret['playAnimation'] = True return ret def __getAnimationType(self, clientVer): try: if clientVer < 3.37: return AnimationType.UNKNOWN if clientVer < 3.77: # 小于3.77版本的还是每一个阶段只播一次 return self._match_table_info['step']['animationType'] # >=3.77版本动画每次都播放 rawAnimationTypeInfo = self._match_table_info['step'][ 'rawAnimationType'] # if rawAnimationTypeInfo['type']==AnimationType.VS and rawAnimationTypeInfo['totalCardCount']>0: # return self._match_table_info['step']['animationType'] return rawAnimationTypeInfo['type'] except: return self._match_table_info['step']['animationType'] def __getWaitToNextMatchInter(self): mnotes = self._match_table_info['mnotes'] isStartStep = mnotes.get('isStartStep', False) if isStartStep: # 第一个阶段不做延迟 return 0 delayConf = dizhuconf.getPublic().get('matchAnimationDelay', '') return delayConf.get('waitToNextMatch', 3) def __getAnimationInter(self, AnimationType, isStartStep, clientVer): if str(clientVer) < 3.77: return self.MSTART_SLEEP delayConf = dizhuconf.getPublic().get('matchAnimationDelay', '') if not delayConf: if isStartStep: return 5 return 3 valKey = 'startStep' if not isStartStep: valKey = 'type' + str(AnimationType) return delayConf.get(valKey, 3) def _findMatchSeatInfoByUserId(self, userId): if self._match_table_info: for seatInfo in self._match_table_info['seats']: if seatInfo['userId'] == userId: return seatInfo return None def _sendRank(self, userId): _, clientVer, clientChannel, _ = sessiondata.getClientIdInfo(userId) ranks = self._match_table_info['ranks'] if not ranks: self._logger.warn( 'GameTable._sendRank', 'TODO the _match_table_info[\'ranks\'] is empty why !!') return mrank = MsgPack() mrank.setCmd('m_rank') if clientVer >= 3.37: seatInfo = self._findMatchSeatInfoByUserId(userId) ranktops = [] if seatInfo: ranktops.append({ 'userId': userId, 'name': seatInfo['userName'], 'score': seatInfo['score'], 'rank': seatInfo['chiprank'] }) for i, r in enumerate(ranks): ranktops.append({ 'userId': r[0], 'name': str(r[1]), 'score': r[2], 'rank': i + 1 }) if "momo" in clientChannel: # 解决 momo3.372客户端bug:等待页面JS错误 for _ in xrange(i + 1, 10): ranktops.append({ 'userId': 0, 'name': "", 'score': "", 'rank': 0 }) mrank.setResult('mranks', ranktops) else: ranktops = [] for r in ranks: ranktops.append((r[0], r[1], r[2])) mrank.setResult('mranks', ranktops) router.sendToUser(mrank, userId)
class TYGroupMatchRoom(TYRoom): def __init__(self, roomdefine): super(TYGroupMatchRoom, self).__init__(roomdefine) self.bigmatchId = self.bigRoomId self.matchPlugin = gdata.games()[self.gameId].getGroupMatchPlugin() self.match = None self.matchMaster = None self._logger = Logger() self._logger.add('roomId', self.roomId) self._logger.add('bigmatchId', self.bigmatchId) serverType = gdata.serverType() if serverType == gdata.SRV_TYPE_ROOM: self.initMatch() # 此处会给self.match赋值 def initMatch(self): assert (self.matchPlugin.getMatch(self.roomId) is None) self._logger.info('TYGroupMatchRoom.initMatch ...') conf = MatchConfig.parse(self.gameId, self.roomId, self.bigmatchId, self.roomConf['name'], self.matchConf) conf.tableId = self.roomId * 10000 # 用来表示玩家在房间队列的特殊tableId conf.seatId = 1 tableManager = TableManager(self, conf.tableSeatCount) shadowRoomIds = self.roomDefine.shadowRoomIds self._logger.info('TYGroupMatchRoom.initMatch', 'shadowRoomIds=', list(shadowRoomIds)) for roomId in shadowRoomIds: count = self.roomDefine.configure['gameTableCount'] baseid = roomId * 10000 self._logger.info('TYGroupMatchRoom.initMatch addTables', 'shadowRoomId=', roomId, 'tableCount=', count, 'baseid=', baseid) tableManager.addTables(roomId, baseid, count) random.shuffle(tableManager._idleTables) match, master = self.matchPlugin.buildMatch(conf, self) match.tableManager = tableManager if gdata.mode() == gdata.RUN_MODE_ONLINE: playerCapacity = int(tableManager.allTableCount * tableManager.tableSeatCount * 0.9) if playerCapacity <= conf.start.userMaxCountPerMatch: self._logger.error('TYGroupMatchRoom.initMatch', 'allTableCount=', tableManager.allTableCount, 'tableSeatCount=', tableManager.tableSeatCount, 'playerCapacity=', playerCapacity, 'userMaxCount=', conf.start.userMaxCount, 'confUserMaxCountPerMatch=', conf.start.userMaxCountPerMatch, 'err=', 'NotEnoughTable') assert (playerCapacity > conf.start.userMaxCountPerMatch) self.match = match self.matchMaster = master self.matchPlugin.setMatch(self.roomId, match) if master: master.start() match.start() def doEnter(self, userId): if self._logger.isDebug(): self._logger.debug('TYGroupMatchRoom.doEnter', 'userId=', userId) mo = MsgPack() mo.setCmd('m_enter') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.roomId) mo.setResult('userId', userId) try: self.match.enter(userId) except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo) router.sendToUser(mo, userId)
def __init__(self, room): self._room = room self._logger = Logger()
class PlayerNotifierDizhu(PlayerNotifier): def __init__(self, room): self._room = room self._logger = Logger() def notifyMatchCancelled(self, signer, reason, message=None): ''' 通知用户比赛由于reason取消了 ''' try: msg = MsgPack() msg.setCmd('m_over') msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('reason', reason) msg.setResult('info', message or MatchFinishReason.toString(reason)) router.sendToUser(msg, signer.userId) mo = MsgPack() mo.setCmd('m_signs') mo.setResult('gameId', self._room.gameId) mo.setResult('roomId', self._room.bigRoomId) mo.setResult('userId', signer.userId) mo.setResult('signs', {self._room.bigRoomId: 0}) router.sendToUser(mo, signer.userId) except: self._logger.error('PlayerNotifierDizhu.notifyMatchCancelled', 'userId=', signer.userId, 'instId=', signer.instId, 'reason=', reason, 'message=', message) def notifyMatchOver(self, player, 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, player.group.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: self._logger.error('PlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'groupId=', player.group.groupId, 'reason=', reason, 'rankRewards=', rankRewards.rewards) # 比赛记录保存 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: self._logger.error('PlayerNotifierDizhu.notifyMatchOver', 'gameId=', self._room.gameId, 'userId=', player.userId, 'reason=', reason, 'matchId=', self._room.match.matchId, 'rank=', player.rank) msg = MsgPack() msg.setCmd('m_over') 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) try: msg.setResult('beatDownUser', player.beatDownUserName) except: ftlog.debug('NobeatDownUser group match') ftlog.exception() if rankRewards or reason == MatchFinishReason.USER_WIN: msg.setResult('info', buildWinInfo(self._room, player, rankRewards)) if rankRewards.todotask: msg.setResult('todotask', rankRewards.todotask) else: msg.setResult('info', buildLoserInfo(self._room, player)) msg.setResult( 'mucount', player.group.startPlayerCount if player.group.isGrouping else player.group.totalPlayerCount) 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: 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', getMatchName(self._room, player)) 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 }) try: # 设置奖状分享的todotask diplomaShare shareTodoTask = dizhudiplomashare.buildDiplomaShare( player.userName, getMatchName(self._room, player), player.rank, rewardDesc, player.userId) if shareTodoTask: msg.setResult('shareTodoTask', shareTodoTask) except: ftlog.debug('NobeatDownUser group match') ftlog.exception() router.sendToUser(msg, player.userId) if reason in (MatchFinishReason.USER_NOT_ENOUGH, MatchFinishReason.RESOURCE_NOT_ENOUGH): mo = MsgPack() mo.setCmd('m_signs') mo.setResult('gameId', self._room.gameId) mo.setResult('roomId', self._room.bigRoomId) mo.setResult('userId', player.userId) mo.setResult('signs', {self._room.bigRoomId: 0}) router.sendToUser(mo, 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(player.group.instId.split('.')[1]) self.report_bi_game_event("MATCH_FINISH", player.userId, player.group.matchId, 0, sequence, 0, 0, 0, [], 'match_end') #_stage.matchingId except: self._logger.error('PlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'groupId=', player.group.groupId, 'reason=', reason, 'rankRewards=', rankRewards.rewards if rankRewards else None) def notifyMatchGiveupFailed(self, player, message): ''' 通知用户不能放弃比赛 ''' try: msg = MsgPack() msg.setCmd('room') msg.setError(-1, message) router.sendToUser(msg, player.userId) except: self._logger.error('PlayerNotifierDizhu.notifyMatchGiveupFailed', 'userId=', player.userId, 'groupId=', player.group.groupId, 'message=', message) def notifyMatchUpdate(self, player): ''' 通知比赛更新 ''' from dizhu.groupmatch.match import GroupMatch try: msg = MsgPack() msg.setCmd('m_update') msg.setResult('_debug_user_%d_' % (1), player.userId) GroupMatch.getMatchStates(self._room, player.userId, msg) router.sendToUser(msg, player.userId) except: self._logger.error('PlayerNotifierDizhu.notifyMatchUpdate', 'userId=', player.userId, 'groupId=', player.group.groupId) def report_bi_game_event(self, eventId, userId, roomId, tableId, roundId, detalChip, state1, state2, cardlist, tag=''): try: finalUserChip = userchip.getChip(userId) finalTableChip = 0 clientId = sessiondata.getClientId(userId) bireport.reportGameEvent(eventId, userId, 6, roomId, tableId, roundId, detalChip, state1, state2, cardlist, clientId, finalTableChip, finalUserChip) self._logger.debug('PlayerNotifierDizhu.report_bi_game_event tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', 6, 'roomId=', roomId, 'tableId=', tableId, 'roundId=', roundId) except: self._logger.error( 'PlayerNotifierDizhu.report_bi_game_event error tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', 6, 'roomId=', roomId, 'tableId=', tableId, 'roundId=', roundId) def _notifyMatchRank(self, player): msg = MsgPack() msg.setCmd('m_rank') msg.setResult('mranks', player.group.ranktops) router.sendToUser(msg, player.userId) def _notifyMatchRank2(self, player): msg = MsgPack() msg.setCmd('m_rank') ranktops = [] ranktops.append({ 'userId': player.userId, 'name': player.userName, 'score': player.score, 'rank': player.scoreRank }) for i, r in enumerate(player.group.ranktops): ranktops.append({ 'userId': r[0], 'name': r[1], 'score': r[2], 'rank': i + 1 }) if 'momo' in player.clientId: # 解决 momo3.372客户端bug:比赛等待页面JS错误 for _ in xrange(len(ranktops), 10): ranktops.append({ 'userId': 0, 'name': '', 'score': '', 'rank': 0 }) msg.setResult('mranks', ranktops) router.sendToUser(msg, player.userId) def notifyMatchRank(self, player): ''' 通知比赛排行榜 ''' try: _, clientVer, _ = strutil.parseClientId(player.clientId) if self._logger.isDebug(): self._logger.debug('PlayerNotifierDizhu.notifyMatchRank', 'userId=', player.userId, 'groupId=', player.group.groupId, 'clientId=', player.clientId) if clientVer >= 3.37: self._notifyMatchRank2(player) else: self._notifyMatchRank(player) except: self._logger.error('PlayerNotifierDizhu.notifyMatchRank', 'userId=', player.userId, 'groupId=', player.group.groupId, 'clientId=', player.clientId) def _notifyMatchWait(self, player, step=None): self.notifyMatchUpdate(player) self._notifyMatchRank(player) msg = MsgPack() msg.setCmd('m_wait') msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('tableId', player.group.area.tableId) msg.setResult('mname', self._room.roomConf["name"]) msg.setResult('riseCount', player.group.stageConf.riseUserCount) if step != None: msg.setResult('step', 0) # 0 - 请稍后 1- 晋级等待 router.sendToUser(msg, player.userId) def _notifyMatchWait2(self, player, step=None): self.notifyMatchUpdate(player) self._notifyMatchRank2(player) msg = MsgPack() msg.setCmd('m_wait') msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('tableId', player.group.area.tableId) msg.setResult('mname', self._room.roomConf['name']) steps = [] for i, stageConf in enumerate(player.group.matchConf.stages): isCurrent = True if i == player.group.stageIndex else False if stageConf.groupingType != GroupingType.TYPE_NO_GROUP: des = '每组%s人晋级' % (stageConf.riseUserCount) else: des = '%s人晋级' % (stageConf.riseUserCount) stepInfo = {'des': des} if isCurrent: stepInfo['isCurrent'] = 1 stepInfo['name'] = stageConf.name steps.append(stepInfo) msg.setResult('steps', steps) router.sendToUser(msg, player.userId) def notifyMatchWait(self, player, step=None): ''' 通知用户等待 ''' try: self._logger.debug('PlayerNotifierDizhu.notifyMatchWait userId=', player.userId, 'clientId=', player.clientId, 'groupId=', player.group.groupId) _, clientVer, _ = strutil.parseClientId(player.clientId) if clientVer >= 3.37: self._notifyMatchWait2(player, step) else: self._notifyMatchWait(player, step) except: self._logger.error('PlayerNotifierDizhu.notifyMatchRank', 'userId=', player.userId, 'groupId=', player.group.groupId, 'clientId=', player.clientId) def notifyMatchStart(self, instId, signers): ''' 通知用户比赛开始 ''' try: self._logger.info('PlayerNotifierDizhu.notifyMatchStart', 'instId=', instId, 'userCount=', len(signers)) mstart = MsgPack() mstart.setCmd('m_start') mstart.setResult('gameId', self._room.gameId) mstart.setResult('roomId', self._room.bigRoomId) userIds = [p.userId for p in signers] self._logger.info( 'PlayerNotifierDizhu.notifyMatchStart begin send tcp m_start' 'instId=', instId, 'userCount=', len(signers)) if userIds: router.sendToUsers(mstart, userIds) self._logger.info( 'PlayerNotifierDizhu.notifyMatchStart end send tcp m_start' 'instId=', instId, 'userCount=', len(signers)) self._logger.info( 'PlayerNotifierDizhu.notifyMatchStart begin send bi report' 'instId=', instId, 'userCount=', len(signers)) sequence = int(instId.split('.')[1]) datas = { 'userIds': userIds, 'roomId': self._room.roomId, 'sequence': sequence, 'index': 0 } FTTimer(2, self.notifyMatchStartDelayReport_, datas) self._logger.info( 'PlayerNotifierDizhu.notifyMatchStart begin send bi report async' 'instId=', instId, 'userCount=', len(signers)) except: self._logger.error( 'PlayerNotifierDizhu.notifyMatchStart' 'instId=', instId, 'userCount=', len(signers)) def _notifyStageStart(self, player): if player.group.stageIndex == 0: self._notifyMatchWait(player, None) def _notifyStageStart2(self, player): if player.group.stageIndex == 0: if player.waitReason == WaitReason.BYE: self._notifyMatchWait2(player, 0) else: mo = MsgPack() mo.setCmd('m_play_animation') mo.setResult('gameId', self._room.gameId) mo.setResult('roomId', self._room.bigRoomId) mo.setResult('type', AnimationType.ASSIGN_TABLE) router.sendToUser(mo, player.userId) else: mo = MsgPack() mo.setCmd('m_rise') mo.setResult('gameId', self._room.gameId) mo.setResult('roomId', self._room.bigRoomId) router.sendToUser(mo, player.userId) def notifyStageStart(self, player): ''' 通知用户正在配桌 ''' try: if self._logger.isDebug(): self._logger.debug('PlayerNotifierDizhu.notifyStageStart', 'userId=', player.userId, 'clientId=', player.clientId, 'groupId=', player.group.groupId) _, clientVer, _ = strutil.parseClientId(player.clientId) if clientVer >= 3.37: self._notifyStageStart2(player) else: self._notifyStageStart(player) except: self._logger.error('PlayerNotifierDizhu.notifyStageStart', 'userId=', player.userId, 'clientId=', player.clientId, 'groupId=', player.group.groupId) def notifyMatchStartDelayReport_(self): argl = FTTasklet.getCurrentFTTasklet().run_argl datas = argl[0] userIds = datas['userIds'] roomId = datas['roomId'] sequence = datas['sequence'] index = datas['index'] self._logger.info('PlayerNotifierDizhu.notifyMatchStartDelayReport_', 'index=', index, 'total=', len(userIds)) nindex = self.notifyMatchStartDelayReport(userIds, roomId, sequence, index) if nindex < 0: self._logger.info( 'PlayerNotifierDizhu.notifyMatchStartDelayReport_ end') else: datas['index'] = nindex FTTimer(0.1, self.notifyMatchStartDelayReport_, datas) def notifyMatchStartDelayReport(self, userIds, roomId, sequence, index): ulen = len(userIds) blockc = 0 while index < ulen: userId = userIds[index] self.report_bi_game_event('MATCH_START', userId, roomId, 0, sequence, 0, 0, 0, [], 'match_start') # _stage.matchingId index += 1 blockc += 1 if blockc > 10: return index return -1
class TableControllerDizhu(TableController): def __init__(self, room): self._room = room self._logger = Logger() self._logger.add('roomId', self._room.roomId) def startTable(self, table): ''' 让player在具体的游戏中坐到seat上 ''' try: self._logger.info('TableControllerDizhu.startTable', 'groupId=', table.group.groupId, 'tableId=', table.tableId, 'userIds=', table.getUserIdList()) # 发送tableStart message = buildTableStartMessage(table) router.sendTableServer(message, table.roomId) except: self._logger.error('TableControllerDizhu.startTable', 'groupId=', table.group.groupId, 'tableId=', table.tableId, 'userIds=', table.getUserIdList()) def clearTable(self, table): ''' 清理桌子 ''' # 发送tableClear try: tableClearMessage = buildTableClearMessage(table) router.sendTableServer(tableClearMessage, table.roomId) except: self._logger.error('TableControllerDizhu.clearTable', 'groupId=', table.group.groupId, 'tableId=', table.tableId, 'userIds=', table.getUserIdList()) def updateTableInfo(self, table): ''' 桌子信息变化 ''' # 发送tableInfo try: tableInfoMessage = buildTableInfoMessage(table) router.sendTableServer(tableInfoMessage, table.roomId) except: self._logger.error('TableControllerDizhu.updateTableInfo', 'groupId=', table.group.groupId, 'tableId=', table.tableId, 'userIds=', table.getUserIdList()) def userReconnect(self, table, seat): ''' 用户坐下 ''' try: msg = MsgPack() msg.setCmd('table_manage') msg.setParam('action', 'm_user_reconn') msg.setParam('gameId', table.gameId) msg.setParam('matchId', table.group.area.matchId) msg.setParam('roomId', table.roomId) msg.setParam('tableId', table.tableId) msg.setParam('userId', seat.player.userId) msg.setParam('seatId', seat.seatId) msg.setParam('ccrc', table.ccrc) router.sendTableServer(msg, table.roomId) except: self._logger.error('TableControllerDizhu.userReconnect', 'groupId=', table.group.groupId, 'tableId=', table.tableId, 'userId=', seat.player.userId if seat.player else 0, 'userIds=', table.getUserIdList())
def __init__(self, room, tableId, seatId): self._room = room self._tableId = tableId self._seatId = seatId self._logger = Logger() self._logger.add('roomId', room.roomId)
class SignIFDizhu(SignIF): def __init__(self, room, tableId, seatId): self._room = room self._tableId = tableId self._seatId = seatId self._logger = Logger() self._logger.add('roomId', room.roomId) def signin(self, userId, matchId, ctrlRoomId, instId, fee): ''' 报名接口,如果不成功抛异常 ''' # 去UT收取报名费,并记录用户所在房间为ctrlRoomId # 记录用户报名记录 contentItem = { 'itemId': fee.assetKindId, 'count': fee.count } if fee else None ec, result = match_remote.signinMatch(DIZHU_GAMEID, userId, contentItem, self._room.bigRoomId, instId, self._room.roomId) if ec == 0: try: daobase.executeTableCmd(ctrlRoomId, 0, 'sadd', 'signs:' + str(ctrlRoomId), userId) key = 'msignin3:%s:%s:%s' % (self._room.gameId, instId, ctrlRoomId) daobase.executeMixCmd('zadd', key, pktimestamp.getCurrentTimestamp(), userId) except: self._logger.error() self._logger.info('SignIFDizhu.signin ok', 'userId=', userId, 'instId=', instId, 'fee=', contentItem) return if ec == match_remote.ERR_ALREADY_IN_MATCH: self._logger.warn('SignIFDizhu.signin fail', 'userId=', userId, 'instId=', instId, 'fee=', contentItem, 'err=', 'ERR_ALREADY_IN_MATCH') raise AlreadyInMatchException() elif ec == match_remote.ERR_ALREADY_SIGNIN: self._logger.warn('SignIFDizhu.signin fail', 'userId=', userId, 'instId=', instId, 'fee=', contentItem, 'err=', 'ERR_ALREADY_SIGNIN') raise AlreadySigninException() elif ec == match_remote.ERR_FEE_NOT_ENOUGH: self._logger.warn('SignIFDizhu.signin fail', 'userId=', userId, 'instId=', instId, 'fee=', contentItem, 'result=', result, 'err=', 'ERR_FEE_NOT_ENOUGH') raise SigninFeeNotEnoughException(fee) self._logger.warn('SignIFDizhu.signin fail', 'userId=', userId, 'instId=', instId, 'fee=', contentItem, 'err=', 'Unknown') raise SigninException('报名失败') def moveTo(self, userId, matchId, ctrlRoomId, instId, toInstId): ''' 移动玩家到下一场比赛 ''' try: if match_remote.moveTo(DIZHU_GAMEID, userId, self._room.bigRoomId, instId, ctrlRoomId, toInstId): daobase.executeTableCmd(ctrlRoomId, 0, 'sadd', 'signs:' + str(ctrlRoomId), userId) key = 'msignin3:%s:%s:%s' % (self._room.gameId, toInstId, ctrlRoomId) daobase.executeMixCmd('zadd', key, pktimestamp.getCurrentTimestamp(), userId) except: self._logger.error() def signout(self, userId, matchId, ctrlRoomId, instId, feeContentItem): ''' ''' # 去UT退报名费,并删除用户报名记录 # 删除用户报名记录 contentItem = { 'itemId': feeContentItem.assetKindId, 'count': feeContentItem.count } if feeContentItem else None try: key = 'msignin3:%s:%s:%s' % (self._room.gameId, instId, ctrlRoomId) daobase.executeMixCmd('zrem', key, userId) daobase.executeTableCmd(self._room.roomId, 0, 'SREM', 'signs:' + str(self._room.roomId), userId) except: self._logger.error('SignIFDizhu.signout error', 'userId=', userId, 'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId, 'instId=', instId, 'fee=', contentItem) try: match_remote.signoutMatch(DIZHU_GAMEID, userId, contentItem, self._room.bigRoomId, instId, self._room.roomId) self._logger.info('SignIFDizhu.signout ok', 'userId=', userId, 'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId, 'instId=', instId, 'fee=', contentItem) except: self._logger.error('SignIFDizhu.signout fail', 'userId=', userId, 'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId, 'instId=', instId, 'fee=', contentItem) def _loadSigninFee(self, matchId, ctrlRoomId, instId, userId): try: info = match_remote.loadUserMatchInfo(self._room.gameId, userId, self._room.bigRoomId) if info: return info.feeItem except: self._logger.error('SignIFDizhu._loadSigninFee fail', 'userId=', userId, 'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId, 'instId=', instId) return None def loadAllUsers(self, matchId, ctrlRoomId, instId): ''' ''' # 加载所有用户报名记录 ret = [] key = 'msignin3:%s:%s:%s' % (self._room.gameId, instId, ctrlRoomId) datas = daobase.executeMixCmd('zrange', key, 0, -1, 'WITHSCORES') if datas: i = 0 while (i + 1 < len(datas)): userId = int(datas[i]) signinTime = int(datas[i + 1]) signer = Signer(userId, instId, signinTime) signer.feeItem = self._loadSigninFee(matchId, ctrlRoomId, instId, userId) ret.append(signer) i += 2 return ret def removeAllUsers(self, matchId, ctrlRoomId, instId): key = 'msignin3:%s:%s:%s' % (self._room.gameId, instId, ctrlRoomId) daobase.executeMixCmd('del', key) daobase.executeTableCmd(self._room.roomId, 0, 'del', 'signs:' + str(ctrlRoomId)) def lockUser(self, matchId, ctrlRoomId, instId, userId, clientId=None): ''' ''' try: if match_remote.lockUserForMatch(DIZHU_GAMEID, userId, self._room.bigRoomId, instId, self._room.roomId, self._tableId, self._seatId, clientId): return True return False except: self._logger.error('SignIFDizhu.lockUser fail', 'userId=', userId, 'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId, 'instId=', instId) return False def unlockUser(self, matchId, ctrlRoomId, instId, userId, feeContentItem): ''' ''' contentItem = { 'itemId': feeContentItem.assetKindId, 'count': feeContentItem.count } if feeContentItem else None try: match_remote.unlockUserForMatch(DIZHU_GAMEID, userId, self._room.bigRoomId, instId, self._room.roomId, self._tableId, self._seatId, contentItem) except: self._logger.error('SignIFDizhu.unlockUser fail', 'userId=', userId, 'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId, 'instId=', instId)
class TYGroupMatchRoom(TYRoom): def __init__(self, roomdefine): super(TYGroupMatchRoom, self).__init__(roomdefine) self.bigmatchId = self.bigRoomId self.matchPlugin = gdata.games()[self.gameId].getGroupMatchPlugin() self.match = None self.matchMaster = None self._logger = Logger() self._logger.add('roomId', self.roomId) self._logger.add('bigmatchId', self.bigmatchId) serverType = gdata.serverType() if serverType == gdata.SRV_TYPE_ROOM: self.initMatch() # 此处会给self.match赋值 def initMatch(self): assert (self.matchPlugin.getMatch(self.roomId) is None) self._logger.info('TYGroupMatchRoom.initMatch ...') conf = MatchConfig.parse(self.gameId, self.roomId, self.bigmatchId, self.roomConf['name'], self.matchConf) conf.tableId = self.roomId * 10000 # 用来表示玩家在房间队列的特殊tableId conf.seatId = 1 tableManager = TableManager(self, conf.tableSeatCount) shadowRoomIds = self.roomDefine.shadowRoomIds self._logger.info('TYGroupMatchRoom.initMatch', 'shadowRoomIds=', list(shadowRoomIds)) for roomId in shadowRoomIds: count = self.roomDefine.configure['gameTableCount'] baseid = roomId * 10000 self._logger.info('TYGroupMatchRoom.initMatch addTables', 'shadowRoomId=', roomId, 'tableCount=', count, 'baseid=', baseid) tableManager.addTables(roomId, baseid, count) random.shuffle(tableManager._idleTables) match, master = self.matchPlugin.buildMatch(conf, self) match.tableManager = tableManager if gdata.mode() == gdata.RUN_MODE_ONLINE: playerCapacity = int(tableManager.allTableCount * tableManager.tableSeatCount * 0.9) if playerCapacity <= conf.start.userMaxCountPerMatch: self._logger.error( 'TYGroupMatchRoom.initMatch', 'allTableCount=', tableManager.allTableCount, 'tableSeatCount=', tableManager.tableSeatCount, 'playerCapacity=', playerCapacity, 'userMaxCount=', conf.start.userMaxCount, 'confUserMaxCountPerMatch=', conf.start.userMaxCountPerMatch, 'err=', 'NotEnoughTable') assert (playerCapacity > conf.start.userMaxCountPerMatch) self.match = match self.matchMaster = master self.matchPlugin.setMatch(self.roomId, match) if master: master.start() match.start() def doEnter(self, userId): if self._logger.isDebug(): self._logger.debug('TYGroupMatchRoom.doEnter', 'userId=', userId) mo = MsgPack() mo.setCmd('m_enter') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.roomId) mo.setResult('userId', userId) try: self.match.enter(userId) except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo) router.sendToUser(mo, userId)
class TableManager(object): def __init__(self, room, tableSeatCount): self._room = room self._tableSeatCount = tableSeatCount self._idleTables = [] self._allTableMap = {} self._roomIds = set() self._logger = Logger() self._logger.add('roomId', self._room.roomId) @property def tableSeatCount(self): return self._tableSeatCount @property def roomCount(self): return len(self._roomIds) @property def gameId(self): return self._room.gameId @property def allTableCount(self): return len(self._allTableMap) @property def idleTableCount(self): return len(self._idleTables) @property def busyTableCount(self): return max(0, self.allTableCount - self.idleTableCount()) def getTableCountPerRoom(self): return len(self._allTableMap) / max(1, self.roomCount) def addTables(self, roomId, baseId, count): if count > 0: self._roomIds.add(roomId) for i in xrange(count): tableId = baseId + i + 1 # 新框架里tableId 从 1开始计数, 0表示队列。 table = Table(self.gameId, roomId, tableId, self._tableSeatCount) self._idleTables.append(table) self._allTableMap[tableId] = table def borrowTables(self, count): assert (self.idleTableCount >= count) ret = self._idleTables[0:count] self._idleTables = self._idleTables[count:] self._logger.info('TableManager.borrowTables', 'count=', count, 'idleTableCount=', self.idleTableCount, 'allTableCount=', self.allTableCount) return ret def returnTables(self, tables): for table in tables: assert (self._allTableMap.get(table.tableId, None) == table) assert (not table.getPlayerList()) self._idleTables.append(table) self._logger.info('TableManager.returnTables', 'count=', len(tables), 'idleTableCount=', self.idleTableCount, 'allTableCount=', self.allTableCount) def findTable(self, roomId, tableId): return self._allTableMap.get(tableId, None)
def __init__(self, room): self._room = room self._logger = Logger() self._logger.add('roomId', self._room.roomId)
class DizhuGroupMatchSender(DizhuSender): def __init__(self, table): super(DizhuGroupMatchSender, self).__init__(table) if not self.table : from dizhu.gametable.dizhu_table import DizhuTable self.table = DizhuTable() self._logger = Logger() self._logger.add('roomId', self.table.roomId) self._logger.add('tableId', self.table.tableId) def sendTableInfoRes(self, userId, clientId, isrobot): if self._logger.isDebug(): self._logger.debug('DizhuGroupMatchSender.sendTableInfoRes', 'userId=', userId, 'clientId=', clientId, 'isrobot=', isrobot) tableInfo = self.table._match_table_info if not tableInfo: self._logger.error('DizhuGroupMatchSender.sendTableInfoRes NoMatchTableInfo', 'userId=', userId, 'clientId=', clientId, 'isrobot=', isrobot) return player = self.table.getPlayer(userId) if not player: self._logger.error('DizhuGroupMatchSender.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('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) if self._logger.isDebug(): self._logger.debug('DizhuGroupMatchSender.sendTableInfoRes before getMatchTableInfo', 'mo=', mo) self.getMatchTableInfo(userId, tableInfo, mo) if self._logger.isDebug(): self._logger.debug('DizhuGroupMatchSender.sendTableInfoRes after getMatchTableInfo', 'mo=', mo) for i in xrange(len(self.table.seats)): seat = self.table.seats[i] oseat = seat.toInfoDict() 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 getMatchTableInfo(self, userId, tableInfo, mo): mo.setResult('mnotes', tableInfo['mnotes']) mo.setResult('mInfos', tableInfo['mInfos']) mo.setResult('step', { 'name':tableInfo['step']['name'], 'des':'%s人参赛,%s人晋级' % (tableInfo['step']['playerCount'], tableInfo['step']['riseCount']), 'playerCount':tableInfo['step']['playerCount'], 'note':self.table._buildNote(userId, tableInfo) }) def getMatchUserInfo(self, userId, tableInfo, oseat): oseat['mscore'] = 0 oseat['mrank'] = 0 try: for userInfo in tableInfo['seats']: if userInfo['userId'] == userId: oseat['mscore'] = userInfo['score'] oseat['mrank'] = userInfo['rank'] record = MatchRecord.loadRecord(self.table.gameId, userId, tableInfo.get('recordId', tableInfo['matchId'])) if record: oseat['mrecord'] = { 'bestRank':record.bestRank, 'crownCount':record.crownCount, 'playCount':record.playCount } except: self._logger.error('DizhuGroupMatchSender.getMatchUserInfo', 'userId=', userId, 'tableInfo=', tableInfo, 'oseat=', oseat)