def _doStandUp(self, msg, userId, seatId, reason, clientId): ''' 玩家操作, 尝试离开当前的座位 子类需要自行判定userId和seatId是否吻合 ''' if ftlog.is_debug(): ftlog.debug(self._baseLogStr("<<", userId), "|seatId, locList:", seatId, onlinedata.getOnlineLocList(userId), caller=self) seatIndex = seatId - 1 player = self.players[seatIndex] result = {"isOK": True, "userId": userId, "gameId": self.gameId, "roomId": self.roomId, "tableId": self.tableId} if player.userId != userId: ftlog.warn('the seat userId not match userId=', userId, 'seat.userId=', player.userId, caller=self) return result player = self.players[seatId - 1] self._playerStandUp(player) self.onStandUpOk(userId, seatId) mpStandUpRes = self.createMsgPackRes("standup") mpStandUpRes.setResult("reason", reason) mpStandUpRes.setResult("seatId", seatIndex) mpStandUpRes.setResult("userId", userId) self.sendToAllTableUser(mpStandUpRes) if ftlog.is_debug(): ftlog.debug(self._baseLogStr(">>", userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self) return result
def _remoteTableLeave(self, userId, reason=LEAVE_ROOM_REASON_ACTIVE, locList=None): if not locList: locList = onlinedata.getOnlineLocList(userId) if ftlog.is_debug(): ftlog.debug("<< |roomId, userId: ", self.roomId, userId, "|locList:", locList, caller=self) for loc in locList: onlineRoomId, onlineTableId = loc[0], loc[1] if not onlineRoomId in gdata.roomIdDefineMap(): onlinedata.removeOnlineLoc(userId, onlineRoomId, onlineTableId) continue ctrlRoomId = gdata.roomIdDefineMap()[onlineRoomId].parentId if ctrlRoomId == self.roomId: ftlog.hinfo( "table leave |userId, onlineRoomId, onlineTableId:", userId, onlineRoomId, onlineTableId, caller=self) clientId = sessiondata.getClientId(userId) tableLeaveResultStr = self.queryTableManageTableLeaveReq( userId, onlineRoomId, onlineTableId, clientId, {"reason": reason}) if not tableLeaveResultStr: ftlog.warn( "table leave timeout, |userId, onlineRoomId, onlineTableId, reason:", userId, onlineRoomId, onlineTableId, reason, caller=self) # 玩家离开牌桌只返回成功 # tableLeaveResult = json.loads(tableLeaveResultStr) # ftlog.debug("|tableLeaveResult:", tableLeaveResult) # if tableLeaveResult.get("error"): # return False # if not tableLeaveResult["result"]["isOK"]: # return False if ftlog.is_debug(): locList = onlinedata.getOnlineLocList(userId) ftlog.debug(">> |roomId, userId: ", self.roomId, userId, "|locList:", locList, caller=self) # return True return True
def _doSit(self, msg, userId, seatId, clientId): ''' 玩家操作, 尝试在当前的某个座位上坐下 ''' if ftlog.is_debug(): ftlog.info("_doSit << |tableId, userId, seatId:", self.tableId, userId, seatId, caller=self) if ftlog.is_debug(): locList = onlinedata.getOnlineLocList(userId) ftlog.debug(self._baseLogStr("<<", userId), "|locList:", locList, caller=self) result = {"isOK": True, "userId": userId, "gameId": self.gameId, "roomId": self.bigRoomId, "tableId": self.tableId} idleSeatId = self._getValidIdleSeatId(userId, seatId - 1, result) if idleSeatId < 0: # self.room.sendTableClothRes(self.gameId, userId, self.tableType, self.tableTheme) self.sendTableInfoRes(result["seatId"], userId) self._onReSit(userId, -idleSeatId, clientId) return result if idleSeatId == 0: return result # rid, tid, sid = getOnlineLoc(userId, self.gameId) # 为了支持并发坐下,self.getValidIdleSeatId()到此函数执行前,不应该有异步操作 self.onSitOk(userId, idleSeatId, result) # if rid == 0: #旁观坐下时rid!=0 # TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_USER_FIRST_SIT', params={ # 'table': self, 'userId': userId}), self.gameId) player = self.players[idleSeatId - 1] self._playerSit(player) self.sendQuickStartRes(userId, clientId, result) self.sendTableInfoRes(result["seatId"], userId) # 发送 newUser 消息, 客户端通过该协议显示新玩家 mpNewUserRes = self.createMsgPackRes("newUser") playerInfo = player.getInfo() mpNewUserRes.updateResult(playerInfo) self.sendToAllTableUser(mpNewUserRes, exclude=[userId]) # 扩展事件. TYPluginCenter.event(TYPluginUtils.updateMsg(cmd=PluginEvents.EV_AFTER_SITDOWN, params=TYPluginUtils.mkdict( table=self, userId=userId, player=player)), self.gameId) if ftlog.is_debug(): ftlog.debug(self._baseLogStr(">>", userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self) ftlog.hinfo("_doSit >> get new seat, |tableId, userId, seatId:", self.tableId, userId, player.seatId, caller=self) return result
def isInSameTable(self, inviter, invitee): inviterList = onlinedata.getOnlineLocList(inviter) ftlog.debug('isInSameTable userId->', inviter, ' loc->', inviterList) inviteeList = onlinedata.getOnlineLocList(invitee) ftlog.debug('isInSameTable userId->', invitee, ' loc->', inviteeList) for er in inviterList: erRoom, erTable = er[0], er[1] for ee in inviteeList: eeRoom, eeTable = ee[0], ee[1] if (erRoom == eeRoom) and (erTable == eeTable): return True return False
def isInSameTable(self, inviter, invitee): inviterList = onlinedata.getOnlineLocList(inviter) ftlog.debug('isInSameTable userId->', inviter, ' loc->', inviterList) inviteeList = onlinedata.getOnlineLocList(invitee) ftlog.debug('isInSameTable userId->', invitee, ' loc->', inviteeList) for er in inviterList: erRoom, erTable = er[0], er[1] for ee in inviteeList: eeRoom, eeTable = ee[0], ee[1] if (erRoom == eeRoom) and (erTable == eeTable): return True return False
def _doLeave(self, msg, userId, clientId): ''' 玩家操作, 尝试离开当前的桌子 实例桌子可以覆盖 _doLeave 方法来进行自己的业务逻辑处理 ''' ftlog.hinfo(self._baseLogStr("_doLeave <<", userId), "|msg, observers:", msg, self.observers, caller=self) gameId = msg.getParam("gameId", 0) if gameId and gameId != self.gameId: ftlog.warn("_doLeave gameId != self.gameId", userId, gameId, clientId) return {"isOK": False, "reason": TYRoom.LEAVE_ROOM_REASON_SYSTEM} reason = msg.getParam("reason", TYRoom.LEAVE_ROOM_REASON_ACTIVE) # if reason == TYRoom.LEAVE_ROOM_REASON_LOST_CONNECTION: # self.sendPlayerDataToAll(userId, managed=True) # return {"isOK": False, "reason": reason} if ftlog.is_debug(): ftlog.debug(self._baseLogStr("<<", userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self) result = {"isOK": True, "userId": userId, "gameId": self.gameId, "roomId": self.roomId, "tableId": self.tableId} player = self.getPlayer(userId) if player: self._doStandUp(msg, userId, player.seatId, reason, clientId) if userId in self.observers: del self.observers[userId] onlinedata.removeOnlineLoc(userId, self.roomId, self.tableId) if ftlog.is_debug(): ftlog.debug(self._baseLogStr(">>", userId), "|locList:", onlinedata.getOnlineLocList(userId), "|observers:", self.observers, caller=self) mpRes = self.createMsgPackRes("table_leave") mpRes.setResult("reason", reason) mpRes.setResult("userId", userId) router.sendToUser(mpRes, userId) if ftlog.is_debug(): ftlog.info(self._baseLogStr("_doLeave >>", userId), "|reason, observers:", reason, self.observers, caller=self) TYPluginCenter.evmsg(self.gameId, PluginEvents.EV_LEAVE_TABLE, { 'table': self, 'userId': userId, 'reason': reason }) return result
def _leave(self, userId, reason, needSendRes): ftlog.hinfo("_leave << |roomId, userId, reason: ", self.roomId, userId, reason, caller=self) self._remoteTableLeave(userId, reason) locList = onlinedata.getOnlineLocList(userId) if ftlog.is_debug(): ftlog.debug("<< |roomId, userId: ", self.roomId, userId, "|locList:", locList, caller=self) for loc in locList: onlineRoomId, onlineTableId = loc[0], loc[1] if strutil.getBigRoomIdFromInstanceRoomId( onlineRoomId) == self.bigRoomId: return False return True
def doEnter(self, userId): if self._logger.isDebug(): self._logger.debug("doEnter", "userId=", userId) mo = MsgPack() mo.setCmd("m_enter") mo.setResult("gameId", self.gameId) mo.setResult("roomId", self.roomId) mo.setResult("userId", userId) try: onlineLocList = onlinedata.getOnlineLocList(userId) self._logger.debug("doEnter", "userId=", userId, "onlinedata=", onlineLocList) if onlineLocList: raise BadStateException() signer = self.match.findSigner(userId) self._logger.debug("doEnter", "signer=", signer) if signer: if not signer.isEnter: self.matchMaster.startMatching([signer]) self.userFee[int(userId)] = signer.fee.toDict() self.match.enter(userId) mo.setResult("enter", 1) mo.setResult( "targets", self.match.curInst.targets if self.match.curInst else {}) router.sendToUser(mo, userId) else: raise AlreadySigninException() else: raise NotSigninException() except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo)
def doReturnQueue(self, userId): '''玩家换桌时返回队列''' if ftlog.is_debug(): ftlog.debug("<< |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) if not userId in self._roomUsers: return False if not self.scheduler.enter(userId): return False if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) if ftlog.is_debug(): locList = onlinedata.getOnlineLocList(userId) ftlog.debug(">> |roomId, userId, locList:", self.roomId, userId, locList, caller=self) return True
def _enter(self, userId): ftlog.hinfo("_enter << |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) isOk, checkResult = self.checkSitCondition(userId) if not isOk: return False, checkResult if userId in self._roomUsers: return False, TYRoom.ENTER_ROOM_REASON_CONFLICT if not self.scheduler.enter(userId): return False, TYRoom.ENTER_ROOM_REASON_CONFLICT self._roomUsers.add(userId) if ftlog.is_debug(): ftlog.info("_enter add to _roomUsers.add |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) locList = onlinedata.getOnlineLocList(userId) ftlog.debug(">> |roomId, userId, locList:", self.roomId, userId, locList) PlayerRoomDao.clear(userId, self.bigRoomId) # 防止因系统错误造成的数据遗留问题 return True, TYRoom.ENTER_ROOM_REASON_OK
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 _isObserver(self, userId): """ 陈龙和才哥需求: 在德州和三张里观战时, 不能加好友。原因是好多恶意玩家用这个做宣传。 跟辉哥商量过了, 没什么好办法实现~ 只能在这里写死 gameId by WangTao """ locList = onlinedata.getOnlineLocList(userId) gameIds = {8, 30} for onlineLoc in locList: roomId, tableId, seatId = onlineLoc onlineGameId = strutil.getGameIdFromInstanceRoomId(roomId) if onlineGameId not in gameIds: continue # 判断是否观战状态。 只适用三张和德州 if roomId and tableId and seatId: roomConf = gdata.getRoomConfigure(roomId) maxSeatN = roomConf['tableConf']['maxSeatN'] if seatId == maxSeatN + 1: # is observe ftlog.info( "FriendTcpHandler._isObserver| is observer" "| userId, loc:", userId, onlineLoc) return True return False
def _isObserver(self, userId): """ 陈龙和才哥需求: 在德州和三张里观战时, 不能加好友。原因是好多恶意玩家用这个做宣传。 跟辉哥商量过了, 没什么好办法实现~ 只能在这里写死 gameId by WangTao """ locList = onlinedata.getOnlineLocList(userId) gameIds = {8, 30} for onlineLoc in locList: roomId, tableId, seatId = onlineLoc onlineGameId = strutil.getGameIdFromInstanceRoomId(roomId) if onlineGameId not in gameIds: continue # 判断是否观战状态。 只适用三张和德州 if roomId and tableId and seatId: roomConf = gdata.getRoomConfigure(roomId) maxSeatN = roomConf['tableConf']['maxSeatN'] if seatId == maxSeatN + 1: # is observe ftlog.info("FriendTcpHandler._isObserver| is observer" "| userId, loc:", userId, onlineLoc) return True return False
def _leave(self, userId, reason, needSendRes): ftlog.hinfo("_leave << |roomId, userId, _roomUsersN, reason: ", self.roomId, userId, len(self._roomUsers), reason, caller=self) if ftlog.is_debug(): ftlog.debug("<< |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) ftlog.debug("<< |roomId, userId, scheduler.users: ", self.roomId, userId, self.scheduler.users.keys(), caller=self) if reason == TYRoom.LEAVE_ROOM_REASON_LOST_CONNECTION: return False if not userId in self._roomUsers: locList = onlinedata.getOnlineLocList(userId) if locList: ftlog.error("_leave >> not userId in self._roomUsers ", "|roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers)) self._remoteTableLeave(userId, reason, locList) return True if userId in self.scheduler.sittingUsers: # 从队列分配玩家进牌桌时,该玩家不允许离开队列。 ftlog.warn("can't leave when start table!", caller=self) return False if userId not in self.scheduler.users: self._remoteTableLeave(userId, reason) if userId in self.scheduler.users: self.scheduler.leave(userId) self._onLeaveQueueOk(userId) self._roomUsers.remove(userId) if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) PlayerRoomDao.clear(userId, self.bigRoomId) return True
def _doMatchQuickStart(self): tableInfo = self._match_table_info userInfos = tableInfo['userInfos'] userIds = [] userSeatList = [] for i, userInfo in enumerate(userInfos): this_seat = self.seats[i] userIds.append(userInfo['userId']) this_seat.userId = userInfo['userId'] this_seat.state = TYSeat.SEAT_STATE_WAIT this_seat.call123 = -1 userSeatList.append((userInfo['userId'], i + 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: onlinedata.removeOnlineLoc(userId, ctrlRoomId, ctrlRoomTableId) onlinedata.addOnlineLoc(userId, self.roomId, self.tableId, seatId) if ftlog.is_debug(): ftlog.debug("|locList:", onlinedata.getOnlineLocList(userId), caller=self) # 做一个延迟 delayConf = dizhuconf.getPublic().get('matchAnimationDelay', '') inter = delayConf.get('waitToNextMatch', 3) FTTasklet.getCurrentFTTasklet().sleepNb(inter) 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() delay = self._playAnimation(userInfos) if delay > 0: FTTasklet.getCurrentFTTasklet().sleepNb(delay) for x in xrange(len(self.players)): self.gamePlay.doReady(self.players[x], False) self._sendRanks(userInfos)
def createFT(userId, nRound, playMode, canDouble, goodCard=0): ''' 创建自建桌 @param userId: 谁创建 @param conf: 桌子配置 ''' # 获取creatorConf creatorConf = getCreatorConf(userId) # 收取创建自建桌费用 if not creatorConf: raise TYBizException(-1, '不支持自建桌') roundConf = creatorConf.getRoundConf(nRound) if not roundConf: raise TYBizException(-1, '不支持的局数: %s' % (nRound)) playModeConf = creatorConf.getPlayModeConf(playMode) if not playModeConf: raise TYBizException(-1, '不支持的玩法: %s' % (playMode)) # check loc locList = onlinedata.getOnlineLocList(userId) for loc in locList: roomId, _, _ = loc gameId = strutil.getGameIdFromInstanceRoomId(roomId) if gameId == DIZHU_GAMEID: raise TYBizException(-1, '正在其他桌游戏') ctrlRoomIds = collectCtrlRoomIdsByFTPlayMode(playMode) if not ctrlRoomIds: ftlog.warn('ft_service.createFT userId=', userId, 'nRound=', nRound, 'playMode=', playMode, 'canDouble=', canDouble) raise TYBizException(-1, '不支持的玩法: %s' % (playMode)) ctrlRoomId = ctrlRoomIds[random.randint(0, len(ctrlRoomIds) - 1)] if ftlog.is_debug(): ftlog.debug('ft_service.createFT userId=', userId, 'nRound=', nRound, 'playMode=', playMode, 'canDouble=', canDouble, 'goodCard=', goodCard, 'ctrlRoomId=', ctrlRoomId, 'ctrlRoomIds=', ctrlRoomIds) fee = None if roundConf.fee > 0: fee = {'itemId':creatorConf.cardAssetKindId, 'count':roundConf.fee} return ft_room_remote.createFT(ctrlRoomId, userId, nRound, playModeConf.toDict(), canDouble, fee, goodCard)
def lockUserForMatch(gameId, userId, bigRoomId, instId, ctrlRoomId, tableId, seatId, clientId): if ftlog.is_debug(): ftlog.debug("match_remote.lockUserForMatch gameId=", gameId, "userId=", userId, "bigRoomId=", bigRoomId, "instId=", instId, "ctrlRoomId=", ctrlRoomId, "tableId=", tableId, "seatId=", seatId, "clientId=", clientId) if not clientId: clientId = sessiondata.getClientId(userId) loc = None locList = onlinedata.getOnlineLocList(userId) for roomId, tableId, seatId in locList: try: roomGameId = strutil.getGameIdFromInstanceRoomId(roomId) if (roomGameId == gameId and tableId != 0 and seatId != 0): loc = [roomGameId, roomId, tableId, seatId] except: ftlog.error("match_remote.lockUserForMatch userId=", userId, "gameId=", gameId, "clientId=", clientId, "roomId=", roomId) if loc: # 检查loc if strutil.getBigRoomIdFromInstanceRoomId(loc[1]) != bigRoomId: ftlog.debug("match_remote.lockUserForMatch Fail gameId=", gameId, "userId=", userId, "bigRoomId=", bigRoomId, "instId=", instId, "ctrlRoomId=", ctrlRoomId, "tableId=", tableId, "seatId=", seatId, "clientId=", clientId, "loc=", loc) return False userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId) if not userMatchInfo: # 此处有异常,正常要有userMatchInfo userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId) userMatchInfo.ctrlRoomId = ctrlRoomId userMatchInfo.instId = instId userMatchInfo.state = UserMatchInfo.ST_SIGNIN userMatchInfo.ctrlRoomId = ctrlRoomId userMatchInfo.state = UserMatchInfo.ST_PLAYING saveUserMatchInfo(userMatchInfo) room = gdata.rooms()[ctrlRoomId] player = room.match.findPlayer(userId) if not player or not player.isQuit: onlinedata.setBigRoomOnlineLoc(userId, ctrlRoomId, tableId, seatId) ftlog.info("match_remote.lockUserForMatch ok gameId=", gameId, "userId=", userId, "bigRoomId=", bigRoomId, "instId=", instId, "ctrlRoomId=", ctrlRoomId, "tableId=", tableId, "seatId=", seatId, "isQuit=", player.isQuit if player else -1, "clientId=", clientId) return True
def leave(self, userId): '''玩家离开队列''' # 只有玩家在队列里时才锁队列并删除他 if userId in self.users: del self.users[userId] onlinedata.removeOnlineLoc(userId, self.room.roomId, self.room.roomId * 10000) if ftlog.is_debug(): ftlog.debug(">>", self.baseLogStr(None, userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self) return True
def doQuickStart(self, msg): assert self.roomId == msg.getParam("roomId") userId = msg.getParam("userId") shadowRoomId = msg.getParam("shadowRoomId") tableId = msg.getParam("tableId") clientId = msg.getParam("clientId") ftlog.hinfo("doQuickStart <<", "|userId, clientId, roomId, shadowRoomId, tableId:", userId, clientId, self.roomId, shadowRoomId, tableId) # msg = TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_QUICK_START', params=TYPluginUtils.mkdict( # userId=userId, roomId=self.roomId), result={}), self.gameId) # # if msg.getResult("reason") != None: # info = u'玩家需要验证' # self.sendQuickStartRes(self.gameId, userId, msg.getResult("reason"), self.bigRoomId, 0, info) # return if tableId == 0: isOk, reason = self.doEnter(userId) elif tableId == self.roomId * 10000: if userId in self._roomUsers: isOk = True # 玩家在队列里时断线重连 reason = TYRoom.ENTER_ROOM_REASON_OK else: # 服务器重启造成玩家已经不在房间对象里了 onlinedata.removeOnlineLoc(userId, self.roomId, tableId) isOk = False reason = TYRoom.ENTER_ROOM_REASON_CONFLICT else: # 防御性代码,处理快速开始online错乱 onlineSeat = onlinedata.getOnlineLocSeatId(userId, shadowRoomId, tableId) if onlineSeat == 0: # 断线重连过程中玩家因为超时、金币不足或比赛淘汰等原因已被踢出房间 isOk = False reason = TYRoom.ENTER_ROOM_REASON_CONFLICT ftlog.warn("doQuickStart conflict!", "|userId, onlineLocList:", userId, onlinedata.getOnlineLocList(userId), "|shadowRoomId, tableId:", shadowRoomId, tableId) else: ftlog.error("doQuickStart conflict!", "|onlineSeat:", onlineSeat) if onlineSeat == gdata.roomIdDefineMap()[shadowRoomId].configure['tableConf']['maxSeatN'] + 1: # 牌桌里旁观的玩家断线重连,请求转给GT self.sendTableCallObserveReq(userId, shadowRoomId, tableId, clientId) elif onlineSeat > 0: # 牌桌里坐着的玩家断线重连,请求转给GT self.querySitReq(userId, shadowRoomId, tableId, clientId) return if isOk: self._onQuickStartOk(userId) elif reason == TYRoom.ENTER_ROOM_REASON_CONFLICT: info = u'玩家已经在游戏中,状态冲突' self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, info) else: self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, '')
def clearInvalidObservers(self): '''一段防御性代码,防止本桌上一局的旁观者未被及时清理,下一局开局时换到了别的桌子,但收到本桌的协议 ''' invalidObservers = [] for userId in self.observers: onlineSeatId = onlinedata.getOnlineLocSeatId(userId, self.roomId, self.tableId) if onlineSeatId == 0: # Note: 断线的旁观玩家不做清理,table._doClearPlayers会处理 ftlog.warn(self._baseLogStr('invalid observer found', userId), '|locList:', onlinedata.getOnlineLocList(userId), caller=self) invalidObservers.append(userId) for userId in invalidObservers: del self.observers[userId]
def enter(self, userId): '''玩家进入队列''' if self.users.get(userId) != None: ftlog.error(getMethodName(), "already in queue!", self.baseLogStr(None, userId)) return False self.users[userId] = {"enterTime": time.time()} onlinedata.addOnlineLoc(userId, self.room.roomId, self.room.roomId * 10000, 1) if ftlog.is_debug(): ftlog.debug(">>", self.baseLogStr(None, userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self) return True
def getOnlineLocListByGameId(userId, gameId, clientId): ret = [] locList = onlinedata.getOnlineLocList(userId) for roomId, tableId, seatId in locList: try: roomGameId = strutil.getGameIdFromInstanceRoomId(roomId) if (roomGameId == gameId and tableId != 0 and seatId != 0): ret.append((roomGameId, roomId, tableId, seatId)) except: ftlog.error('dizhuonlinedata.getOnlineLocListByGameId userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'roomId=', roomId) return ret
def ensureNotInSeat(self, userId): ''' 确认该用户没有在其它桌子上打牌 ''' locList = onlinedata.getOnlineLocList(userId) for loc in locList: onlineRoomId, onlineTableId, onlineSeatId = loc[0], loc[1], loc[2] if not onlineRoomId in gdata.roomIdDefineMap(): onlinedata.removeOnlineLoc(userId, onlineRoomId, onlineTableId) continue gameId = strutil.getGameIdFromBigRoomId(onlineRoomId) if gameId == DIZHU_GAMEID and onlineSeatId: raise InSeatException()
def _leave(self, userId, reason, needSendRes): ftlog.hinfo("_leave << |roomId, userId, reason, state, _roomUsersN: ", self.roomId, userId, reason, self.getStateStr(), len(self._roomUsers), caller=self) if ftlog.is_debug(): ftlog.debug("<< |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) if reason == TYRoom.LEAVE_ROOM_REASON_LOST_CONNECTION: return False if self.state == self.MTT_STATE_START: return False if not userId in self._roomUsers: locList = onlinedata.getOnlineLocList(userId) if locList: ftlog.error("_leave >> not userId in self._roomUsers ", "|roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers)) self._remoteTableLeave(userId, reason, locList) return True if userId in self.scheduler.sittingUsers: # 从队列分配玩家进牌桌时,该玩家不允许离开队列。 ftlog.warn("can't leave when start table!", caller=self) return False if userId not in self.scheduler.users: self._remoteTableLeave(userId, reason) if userId in self.scheduler.users: self.scheduler.leave(userId) self._roomUsers.remove(userId) if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) if len(self._roomUsers) < 10: ftlog.hinfo("_leave >> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) PlayerRoomDao.clear(userId, self.bigRoomId) needSendRewardTodoTask = True if reason == TYRoom.LEAVE_ROOM_REASON_ACTIVE: self.matchCounter['usersLeaveMatchCount'] += 1 needSendRewardTodoTask = False if self.state > self.MTT_STATE_START: if ftlog.is_debug(): ftlog.debug("|needSendRewardTodoTask:", needSendRewardTodoTask, caller=self) self.__leaveMatch(userId, needSendRewardTodoTask=needSendRewardTodoTask) # 此函数会检查玩家是否已经离开比赛, 主动离赛不弹奖状 return True
def leave(self, userId): '''玩家离开队列''' # 只有玩家在队列里时才锁队列并删除他 if userId in self.users: del self.users[userId] onlinedata.removeOnlineLoc(userId, self.room.roomId, self.room.roomId * 10000) if ftlog.is_debug(): ftlog.debug(">>", self.baseLogStr(None, userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self) return True
def enter(self, userId): '''玩家进入队列''' if self.users.get(userId) != None: ftlog.error(getMethodName(), "already in queue!", self.baseLogStr(None, userId)) return False self.users[userId] = {"enterTime": time.time()} onlinedata.addOnlineLoc(userId, self.room.roomId, self.room.roomId * 10000, 1) if ftlog.is_debug(): ftlog.debug(">>", self.baseLogStr(None, userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self) return True
def doReturnQueue(self, userId): '''玩家换桌时返回队列''' if ftlog.is_debug(): ftlog.debug("<< |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) if not userId in self._roomUsers: return False if not self.scheduler.enter(userId): return False if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) if ftlog.is_debug(): locList = onlinedata.getOnlineLocList(userId) ftlog.debug(">> |roomId, userId, locList:", self.roomId, userId, locList, caller=self) return True
def _enter(self, userId): ftlog.hinfo("_enter << |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) isOk, checkResult = self.checkSitCondition(userId) if not isOk: return False, checkResult if userId in self._roomUsers: return False, TYRoom.ENTER_ROOM_REASON_CONFLICT if not self.scheduler.enter(userId): return False, TYRoom.ENTER_ROOM_REASON_CONFLICT self._roomUsers.add(userId) if ftlog.is_debug(): ftlog.info( "_enter add to _roomUsers.add |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) locList = onlinedata.getOnlineLocList(userId) ftlog.debug(">> |roomId, userId, locList:", self.roomId, userId, locList) PlayerRoomDao.clear(userId, self.bigRoomId) # 防止因系统错误造成的数据遗留问题 return True, TYRoom.ENTER_ROOM_REASON_OK
def getOnlineLoc(userId, gameId, roomId=0, tableId=0, locList=None): if not locList: locList = onlinedata.getOnlineLocList(userId) for onlineLoc in locList: if gameId != strutil.getGameIdFromInstanceRoomId(onlineLoc[0]): continue if roomId == 0: return onlineLoc if gdata.getBigRoomId(onlineLoc[0]) == gdata.getBigRoomId(roomId): if tableId == 0: return onlineLoc if onlineLoc[1] == tableId: return onlineLoc return [0, 0, 0]
def getOnlineLoc(userId, gameId, roomId=0, tableId=0, locList=None): if not locList: locList = onlinedata.getOnlineLocList(userId) for onlineLoc in locList: if gameId != strutil.getGameIdFromInstanceRoomId(onlineLoc[0]): continue if roomId == 0: return onlineLoc if gdata.getBigRoomId(onlineLoc[0]) == gdata.getBigRoomId(roomId): if tableId == 0: return onlineLoc if onlineLoc[1] == tableId: return onlineLoc return [0, 0, 0]
def doEnter(self, userId): if self._logger.isDebug(): self._logger.debug("doEnter", "userId=", userId) mo = MsgPack() mo.setCmd("m_enter") mo.setResult("gameId", self.gameId) mo.setResult("roomId", self.roomId) mo.setResult("userId", userId) try: onlineLocList = onlinedata.getOnlineLocList(userId) self._logger.debug("doEnter", "userId=", userId, "onlinedata=", onlineLocList) if onlineLocList: raise BadStateException() self.match.enter(userId) mo.setResult("enter", 1) mo.setResult("targets", self.match.curInst.targets if self.match.curInst else {}) router.sendToUser(mo, userId) except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo)
def chargeNotify(chargeNotifyEvent): userId = chargeNotifyEvent.userId rmbs = chargeNotifyEvent.rmbs from poker.entity.dao import onlinedata locList = onlinedata.getOnlineLocList(userId) for loc in locList: roomId = loc[0] tableId = loc[1] seatId = loc[2] gameId = roomId / 10000000 if gameId == FISH_GAMEID and tableId > 0 and seatId > 0: message = MsgPack() message.setCmd("table_call") message.setParam("action", "charge_notify") message.setParam("gameId", FISH_GAMEID) message.setParam("userId", userId) message.setParam("clientId", chargeNotifyEvent.clientId) message.setParam("roomId", roomId) message.setParam("tableId", tableId) message.setParam("seatId", seatId) router.sendTableServer(message, roomId)
def _leave(self, userId, reason, needSendRes): ftlog.hinfo("_leave << |roomId, userId, _roomUsersN, reason: ", self.roomId, userId, len(self._roomUsers), reason, caller=self) if ftlog.is_debug(): ftlog.debug("<< |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) ftlog.debug("<< |roomId, userId, scheduler.users: ", self.roomId, userId, self.scheduler.users.keys(), caller=self) if reason == TYRoom.LEAVE_ROOM_REASON_LOST_CONNECTION: return False if not userId in self._roomUsers: locList = onlinedata.getOnlineLocList(userId) if locList: ftlog.error("_leave >> not userId in self._roomUsers ", "|roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers)) self._remoteTableLeave(userId, reason, locList) return True # if userId in self.scheduler.sittingUsers: # 从队列分配玩家进牌桌时,该玩家不允许离开队列。 # ftlog.warn("can't leave when start table!", caller=self) # return False if userId not in self.scheduler.users: self._remoteTableLeave(userId, reason) if userId in self.scheduler.users: self.scheduler.leave(userId) self._onLeaveQueueOk(userId) self._roomUsers.remove(userId) if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) PlayerRoomDao.clear(userId, self.bigRoomId) return True
def doUserOffline(self, userId, clientId): evt = OnLineTcpChangedEvent(userId, HALL_GAMEID, 0) TGHall.getEventBus().publishEvent(evt) # 补发room_leave消息 olist = onlinedata.getOnlineLocList(userId) ftlog.debug('doUserOffline onlines->', olist) for ol in olist: roomId, _, _ = ol[0], ol[1], ol[2] if roomId > 0: msg = MsgPack() msg.setCmdAction('room', 'leave') msg.setParam('userId', userId) msg.setParam('roomId', roomId) msg.setParam('gameId', strutil.getGameIdFromInstanceRoomId(roomId)) msg.setParam('clientId', clientId) msg.setParam('reason', TYRoom.LEAVE_ROOM_REASON_LOST_CONNECTION) router.sendRoomServer(msg, roomId) # offline_geoc处理 onlinedata.setUserGeoOffline(userId, HALL_GAMEID) # 通知push服务 self._notifyPushUserOnlineStateChanged(userId, 0, clientId)
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 : # ftlog.debug("|userId, ctrlRoomId, ctrlRoomTableId:", userId, ctrlRoomId, ctrlRoomTableId, caller=self) onlinedata.removeOnlineLoc(userId, ctrlRoomId, ctrlRoomTableId) # ftlog.debug("|userId, roomId, tableId, seatId:", userId, self.roomId, self.tableId, seatId, caller=self) # ftlog.debug("|locList:", onlinedata.getOnlineLocList(userId), caller=self) onlinedata.addOnlineLoc(userId, self.roomId, self.tableId, seatId) if ftlog.is_debug() : ftlog.debug("|locList:", onlinedata.getOnlineLocList(userId), caller=self) # 增加从比赛等待界面到下一局开始时的时间间隔 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() 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 # clmn = MsgPack() # clmn.setCmd('table_call') # clmn.setParam('action', 'CL_MNOTE_SEND') # clmn.setParam('gameId', self.gameId) # clmn.setParam('roomId', self.roomId) # clmn.setParam('tableId', self.tableId) # clmn.setParam('userIds', userIds) # clmn.setParam('note', note) func = functools.partial(self.sendMNoteMsg, userIds, note) FTTimer(3, func) # self._mnoteTimer.setupTimer(0, 3, clmn, tasklet.gdata) for userId in userIds: self.__sendRank(userId)
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
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Auther: houguangdong # @Time: 2020/7/21 import freetime.util.log as ftlog from poker.entity.configure import gdata from poker.entity.dao import userdata, onlinedata from newfish.entity import config, util import random # rooms = gdata.rooms() # ftlog.info('kkkkkkkkkkkkk', rooms.keys()) # [441011001, 441021001, 441031001, 441041001, 443011001, 443021001, 444021001, 444031001, 444041001, 444051001, 444111001, 444121001, 444141001, 444151001, 444991001, 445011001, 446011001] onlineLocList = onlinedata.getOnlineLocList(10013)[0] # 116009 room = gdata.rooms()[onlineLocList[0]] table = room.maptable[onlineLocList[1]] table.tideTaskSystem.taskReady(random.choice(range(1, 9))) # ftlog.info('fffffffffffff', room.maptable.keys()) # ftlog.info('sssssssssssss', table.tideTaskSystem.usersData) # FISH_GAMEID = 44 # bigRoomIds = gdata.gameIdBigRoomidsMap().get(FISH_GAMEID) # ftlog.info(bigRoomIds, 'zzzzzzzzz') # [44101, 44102, 44103, 44104, 44301, 44302, 44402, 44403, 44404, # 44405, 44411, 44412, 44414, 44415, 44499, 44501, 44601] # ctrlRoomIds = [] # for bigRoomId in bigRoomIds: # roomConf = gdata.getRoomConfigure(bigRoomId)
def _doMatchQuickStart(self): ''' 牌桌开始 初始化牌桌玩家 如果是机器人,根据需求初始化机器人信息 ''' robots = [1, 2] tableInfo = self._match_table_info userInfos = tableInfo['users'] userIds = [] userSeatList = [] for i, userInfo in enumerate(userInfos): if userInfo['type'] == 'robot': userInfo['userId'] = robots.pop() this_seat = self.seats[i] userIds.append(userInfo['userId']) this_seat.userId = userInfo['userId'] this_seat.state = TYSeat.SEAT_STATE_WAIT this_seat.call123 = -1 userSeatList.append((userInfo['userId'], i + 1)) # 初始化用户数据 from dizhu.wx_resource import wx_resource wx_resource.initRobotSetting() robotCount = wx_resource.getRobotCount() robotRange = range(0, robotCount) robots = random.sample(robotRange, 3) for x in xrange(len(self.players)): self.players[x].initUser(0, 1, robots[x]) for userId, seatId in userSeatList: if TYPlayer.isRobot(userId): continue onlinedata.addOnlineLoc(userId, self.roomId, self.tableId, seatId) if ftlog.is_debug(): ftlog.debug("|locList:", onlinedata.getOnlineLocList(userId), caller=self) # 做一个延迟 delayConf = dizhuconf.getPublic().get('matchAnimationDelay', '') inter = delayConf.get('waitToNextMatch', 3) FTTasklet.getCurrentFTTasklet().sleepNb(inter) for x in xrange(len(self.seats)): this_seat = self.seats[x] if TYPlayer.isHuman(this_seat.userId): 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) mq.setResult('isOK', True) # 发送用户的quick_start router.sendToUser(mq, this_seat.userId) # 发送table_info self.gamePlay.sender.sendTableInfoResAll() delay = self._playAnimation(userInfos) if delay > 0: FTTasklet.getCurrentFTTasklet().sleepNb(delay) for x in xrange(len(self.players)): self.gamePlay.doReady(self.players[x], False) self._sendRanks(userInfos)
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 onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, clientId, kindId): """UT server中处理来自客户端的quick_start请求 Args: msg cmd : quick_start if roomId == 0: 表示快速开始,服务器为玩家选择房间,然后将请求转给GR if roomId > 0 and tableId == 0 : 表示玩家选择了房间,将请求转给GR if roomId > 0 and tableId == roomId * 10000 : 表示玩家在队列里断线重连,将请求转给GR if roomId > 0 and tableId > 0: if onlineSeatId > 0: 表示玩家在牌桌里断线重连,将请求转给GT else: 表示玩家选择了桌子,将请求转给GR """ assert isinstance(userId, int) and userId > 0 assert isinstance(roomId, int) and roomId >= 0 assert isinstance(tableId, int) and tableId >= 0 if ftlog.is_debug(): ftlog.debug("onCmdQuickStart->", userId, "msg =", msg, "roomId =", roomId, "tableId =", tableId, "clientId =", clientId) isRobot = userId < config.ROBOT_MAX_USER_ID if not isRobot and not util.isUsableClientVersion(userId): cls.onQuickStartFailed(cls.ENTER_ROOM_REASON_VERSION_DISABLE, userId, clientId, roomId) return # 单开, 无论何时quick_start进入都检查loc if not pokerconf.isOpenMoreTable(clientId): locList = onlinedata.getOnlineLocList(userId) if ftlog.is_debug(): ftlog.debug("onCmdQuickStart->getOnlineLocList->", userId, locList) try: for lRoomId, lTableId, lSeatId in locList: roomGameId = strutil.getGameIdFromInstanceRoomId(lRoomId) if roomGameId == FISH_GAMEID: roomId = lRoomId tableId = lTableId ftlog.info( "onCmdQuickStart->reconnect roomId, tableId->", userId, roomId, tableId) else: cls.onQuickStartFailed( cls.ENTER_ROOM_REASON_STATE_ERROR, userId, clientId, roomId) return break except: ftlog.warn("onCmdQuickStart->error", userId, roomId, tableId) redState = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.redState) if isRobot is False and redState == 0: ctrlRoomId = config.getCommonValueByKey("newbieRoomId") chosenTableId = 0 shadowRoomId = None if gdata.getBigRoomId(roomId) == gdata.getBigRoomId( ctrlRoomId) and tableId: chosenTableId = tableId shadowRoomId = tableId / 10000 TYRoomMixin.queryRoomQuickStartReq( msg, ctrlRoomId, chosenTableId, shadowRoomId=shadowRoomId) # 请求转给GR return if roomId == 0: # 玩家点击快速开始 chosenRoomId, reason = cls._chooseRoom(userId, gameId) ftlog.info("onCmdQuickStart->chosenRoomId", chosenRoomId, "userId =", userId, "reason =", reason) if reason == cls.ENTER_ROOM_REASON_OK: TYRoomMixin.queryRoomQuickStartReq(msg, chosenRoomId, 0) # 请求转给GR else: cls.onQuickStartFailed(reason, userId, clientId, roomId) return if tableId == 0: # 玩家只选择了房间 bigRoomId = gdata.getBigRoomId(roomId) if bigRoomId == 0: cls.onQuickStartFailed(cls.ENTER_ROOM_REASON_ROOM_ID_ERROR, userId, clientId, roomId) return ctrlRoomIds = gdata.bigRoomidsMap()[bigRoomId] ctrlRoomId = ctrlRoomIds[userId % len(ctrlRoomIds)] reason = cls.canQuickEnterRoom(userId, gameId, ctrlRoomId, kindId) if reason == cls.ENTER_ROOM_REASON_OK: roomConf = gdata.roomIdDefineMap()[roomId].configure fee = roomConf.get("fee_%s" % kindId, {}) or roomConf.get( "fee", {}) rewards = fee.get("rewards", []) if fee: _consume = [{"name": fee["kindId"], "count": fee["count"]}] ret = util.consumeItems(userId, _consume, "ROOM_GAME_FEE") if ret and rewards: util.addRewards(userId, rewards, "BI_NFISH_VOUCHER_REWARDS", kindId) TYRoomMixin.queryRoomQuickStartReq(msg, ctrlRoomId, 0) # 请求转给GR或GT else: cls.onQuickStartFailed(reason, userId, clientId, roomId) return if tableId == roomId * 10000: # 玩家在队列里断线重连 TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId) # 请求转给GR return onlineSeat = onlinedata.getOnlineLocSeatId(userId, roomId, tableId) if onlineSeat: TYRoomMixin.querySitReq(userId, roomId, tableId, clientId, {"seatId": onlineSeat}) # 玩家断线重连,请求转给GT else: # 玩家选择了桌子 shadowRoomId = tableId / 10000 ctrlRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId TYRoomMixin.queryRoomQuickStartReq( msg, ctrlRoomId, tableId, shadowRoomId=shadowRoomId) # 请求转给GR
def doQuickStart(self, msg): assert self.roomId == msg.getParam("roomId") userId = msg.getParam("userId") shadowRoomId = msg.getParam("shadowRoomId") tableId = msg.getParam("tableId") clientId = msg.getParam("clientId") ftlog.hinfo("doQuickStart <<", "|userId, clientId, roomId, shadowRoomId, tableId:", userId, clientId, self.roomId, shadowRoomId, tableId) msg = TYPluginCenter.event( TYPluginUtils.updateMsg(cmd='EV_QUICK_START', params=TYPluginUtils.mkdict( userId=userId, roomId=self.roomId), result={}), self.gameId) if msg.getResult("reason") != None: info = u'玩家需要验证' self.sendQuickStartRes(self.gameId, userId, msg.getResult("reason"), self.bigRoomId, 0, info) return if tableId == 0: isOk, reason = self.doEnter(userId) elif tableId == self.roomId * 10000: if userId in self._roomUsers: isOk = True # 玩家在队列里时断线重连 reason = TYRoom.ENTER_ROOM_REASON_OK else: # 服务器重启造成玩家已经不在房间对象里了 onlinedata.removeOnlineLoc(userId, self.roomId, tableId) isOk = False reason = TYRoom.ENTER_ROOM_REASON_CONFLICT else: # 防御性代码,处理快速开始online错乱 onlineSeat = onlinedata.getOnlineLocSeatId(userId, shadowRoomId, tableId) if onlineSeat == 0: # 断线重连过程中玩家因为超时、金币不足或比赛淘汰等原因已被踢出房间 isOk = False reason = TYRoom.ENTER_ROOM_REASON_CONFLICT ftlog.warn("doQuickStart conflict!", "|userId, onlineLocList:", userId, onlinedata.getOnlineLocList(userId), "|shadowRoomId, tableId:", shadowRoomId, tableId) else: ftlog.error("doQuickStart conflict!", "|onlineSeat:", onlineSeat) if onlineSeat == gdata.roomIdDefineMap( )[shadowRoomId].configure['tableConf']['maxSeatN'] + 1: # 牌桌里旁观的玩家断线重连,请求转给GT self.sendTableCallObserveReq(userId, shadowRoomId, tableId, clientId) elif onlineSeat > 0: # 牌桌里坐着的玩家断线重连,请求转给GT self.querySitReq(userId, shadowRoomId, tableId, clientId) return if isOk: self._onQuickStartOk(userId) elif reason == TYRoom.ENTER_ROOM_REASON_CONFLICT: info = u'玩家已经在游戏中,状态冲突' self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, info) else: self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, '')