Example #1
0
    def _sendWinloseToMatch(self, result):
        # 发送给match manager
        users = []
        for sst in result.seatStatements:
            user = {}
            user['userId'] = sst.seat.userId
            user['deltaScore'] = sst.delta
            user['seatId'] = sst.seat.seatId
            user['isTuoguan'] = sst.seat.status.isTuoguan
            user[
                'winloseForTuoguanCount'] = sst.seat.player.winloseForTuoguanCount
            user['stageRewardTotal'] = sst.seat.player.stageRewardTotal
            users.append(user)

        mp = MsgPack()
        mp.setCmd('room')
        mp.setParam('action', 'm_winlose')
        mp.setParam('gameId', self.gameId)
        mp.setParam('matchId', self.room.bigmatchId)
        mp.setParam('roomId', self.room.ctrlRoomId)
        mp.setParam('tableId', self.tableId)
        mp.setParam('users', users)
        mp.setParam('ccrc', self.table.matchTableInfo['ccrc'])

        if ftlog.is_debug():
            ftlog.debug('groupMatch._sendWinloseToMatch users=', users)

        if self.WINLOSE_SLEEP > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(self.WINLOSE_SLEEP)

        router.sendRoomServer(mp, self.room.ctrlRoomId)
Example #2
0
def sendLoginReward(gameId, userId, clientId, iscreate, isdayfirst):
    if iscreate:
        newUserReward = configure.getGameJson(gameId, 'login.reward',
                                              {}).get('newUserReward')
        if newUserReward:
            if not newUserReward.get('open', 0):
                return
            rewards = newUserReward.get('rewards')
            if rewards:
                mail = newUserReward.get('mail')
                contentItems = TYContentItem.decodeList(rewards)
                dizhu_util.sendRewardItems(userId, contentItems, mail,
                                           'LOGIN_REWARD', 0)
                FTTasklet.getCurrentFTTasklet().sleepNb(1.5)
                msg = MsgPack()
                msg.setCmd('dizhu')
                msg.setResult('action', 'new_user_reward')
                msg.setResult('rewards', rewards)
                msg.setResult('cardNoteCount',
                              newUserReward.get('cardNoteCount', 0))
                router.sendToUser(msg, userId)
                ftlog.info(
                    'dizhu_login_reward.sendLoginReward newUserReward userId=',
                    userId, 'gameId=', gameId, 'clientId=', clientId,
                    'iscreate=', iscreate, 'isdayfirst=', isdayfirst,
                    'rewards=', rewards)
Example #3
0
    def _sendWinloseToMatch(self, result):
        # 发送给match manager
        users = []
        for sst in result.seatStatements:
            if not sst.seat.player.isAI:
                user = {}
                user['userId'] = sst.seat.userId
                user['deltaScore'] = sst.delta
                user['finalScore'] = sst.final
                user['seatId'] = sst.seat.seatId
                users.append(user)
                if ftlog.is_debug():
                    ftlog.debug(
                        'DizhuTableProtoGroupMatch._sendWinloseToMatch',
                        'userId=', sst.seat.userId, 'delta=', sst.delta,
                        'final=', sst.final, 'seatId=', sst.seat.seatId)

        mp = MsgPack()
        mp.setCmd('room')
        mp.setParam('action', 'm_winlose')
        mp.setParam('gameId', self.gameId)
        mp.setParam('matchId', self.room.bigmatchId)
        mp.setParam('roomId', self.room.ctrlRoomId)
        mp.setParam('tableId', self.tableId)
        mp.setParam('users', users)
        mp.setParam('ccrc', self.table.matchTableInfo['ccrc'])

        if self.WINLOSE_SLEEP > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(self.WINLOSE_SLEEP)
        router.sendRoomServer(mp, self.room.ctrlRoomId)
Example #4
0
    def enterOneTable(self, userId, shadowRoomId, tableId):
        '''指定桌子坐下
        Returns
            False: 重试超过次数
        '''
        if ftlog.is_debug():
            ftlog.debug("<< |userId, roomId, shadowRoomId, tableId",
                        userId,
                        self.roomId,
                        shadowRoomId,
                        tableId,
                        caller=self)

        if gdata.roomIdDefineMap()[shadowRoomId].tableCount == 1:
            return tableId

        for _ in xrange(5):  # 这张桌子有可能正在分配座位,如果取桌子失败,需要休眠后重试
            result = daobase.executeTableCmd(
                shadowRoomId, 0, "ZREM", self.getTableScoresKey(shadowRoomId),
                tableId)  # ZREM key member删除元素
            if ftlog.is_debug():
                ftlog.debug("after ZREM tableId",
                            "|userId, shadowRoomId, tableId, result:",
                            userId,
                            shadowRoomId,
                            tableId,
                            result,
                            caller=self)
            if result == 1:
                return tableId

            FTTasklet.getCurrentFTTasklet().sleepNb(1)

        return 0
Example #5
0
    def _startMatchTable(self):
        tableInfo = self.table.matchTableInfo
        seatInfos = tableInfo['seats']
        if ftlog.is_debug():
            ftlog.debug('DizhuTableCtrlCustomMatch._startMatchTable',
                        'userIds=',
                        [seatInfo['userId']
                         for seatInfo in seatInfos], 'locker=', self.locker,
                        'tableId=', self.table.tableId, 'tableUserIds=',
                        [seat.userId for seat in self.table.seats])
        inter = self._getWaitToNextMatchInter()
        if inter > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(inter)

        for seatInfo in seatInfos:
            player = DizhuPlayerCustomMatch(self.room, seatInfo['userId'],
                                            seatInfo)
            self._fillPlayer(player)
            player.score = seatInfo['score']
            self.table.sitdown(player, False)

        if ftlog.is_debug():
            ftlog.debug('DizhuTableCtrlCustomMatch._startMatchTable',
                        'userIds=',
                        [seatInfo['userId']
                         for seatInfo in seatInfos], 'scores=',
                        [seat.player.score for seat in self.table.seats])

        for seat in self.table.seats:
            self.table.ready(seat, False)
Example #6
0
    def gameReadyAction(cls, cmd):
        # 换牌
        if cmd.table.runConf.huanpaiCardCount <= 0:
            # 发牌,选择首叫
            cmd.playMode.gameReady(cmd.table)
        gameRound = cmd.table.gameRound
        # ???为什么延时,等待客户端动画吗???
        if cmd.table.runConf.firstCallDelayTimes > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(
                cmd.table.runConf.firstCallDelayTimes)

        seat = gameRound.firstCallSeat

        if seat.status.isTuoguan:
            optime = cmd.table.runConf.optimeTuoguan
        else:
            optime = cmd.table.runConf.optimeCall

        # 移动curOpSeat
        cmd.playMode.moveCurOpSeat(cmd.table, seat, optime,
                                   seat.status.isTuoguan)

        # 启动叫地主计时器
        seat.startTimer(optime, cmd.table.processCommand,
                        CallTimeupCommand(seat))

        return TableState.STATE_CONTINUE
Example #7
0
    def _startMatchTable(self):
        tableInfo = self.table.matchTableInfo
        seatInfos = tableInfo['seats']
        if ftlog.is_debug():
            ftlog.debug('DizhuTableCtrlGroupMatch._startMatchTable',
                        'userIds=', [seatInfo['userId'] for seatInfo in seatInfos],
                        'locker=', self.locker,
                        'tableId=', self.table.tableId,
                        'tableUserIds=', [seat.userId for seat in self.table.seats],
                        'stageRewardTotal=', [seatInfo['stageRewardTotal'] for seatInfo in seatInfos])
        inter = self._getWaitToNextMatchInter()
        if inter > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(inter)

        for seatInfo in seatInfos:
            player = DizhuPlayerGroupMatch(self.room, seatInfo['userId'], seatInfo)
            player.championLimitFlag = seatInfo['championLimitFlag']
            self._fillPlayer(player)
            player.score = seatInfo['score']
            player.firstCallFalg = seatInfo['firstCallFalg']
            player.isQuit = seatInfo['isQuit']
            player.winloseForTuoguanCount = seatInfo['winloseForTuoguanCount']
            player.hasEnterRewards = seatInfo['hasEnterRewards']
            player.stageRewardTotal = seatInfo['stageRewardTotal']
            self.table.sitdown(player, False)

        if ftlog.is_debug():
            ftlog.debug('DizhuTableCtrlGroupMatch._startMatchTable',
                        'userIds=', [(seatInfo['userId'], seatInfo['winloseForTuoguanCount']) for seatInfo in seatInfos],
                        'scores=', [seat.player.score for seat in self.table.seats])
            
        for seat in self.table.seats:
            self.table.ready(seat, False)
    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)
Example #9
0
 def _tryReport(self, model, retryTimes, retryInterval):
     ftlog.debug('AsyncReporter._tryReport')
     ec, info = self._report(model)
     while (ec != 0 and retryTimes > 0):
         retryTimes -= 1
         FTTasklet.getCurrentFTTasklet().sleepNb(retryInterval)
         ec, info = self._report(model)
     return ec, info
Example #10
0
    def getBestTableId(self, userId, shadowRoomId, exceptTableId=None):
        '''原子化从redis里获取和删除评分最高的桌子Id
        Return:
            None: tableScores 队列为空, 所有桌子都在分配座位中
        '''

        def getBestTableIdFromRedis(shadowRoomId):
            '''从redis里取出并删除一个评分最高的牌桌
            '''
            tableId, tableScore = 0, 0
            datas = daobase.executeTableLua(shadowRoomId, 0, room_scripts.ALIAS_GET_BEST_TABLE_ID_LUA, 1,
                                            self.getTableScoresKey(shadowRoomId), 0)
            if datas and len(datas) == 2:
                tableId, tableScore = datas[0], datas[1]
            return tableId, tableScore

        if ftlog.is_debug():
            ftlog.debug("<<", "|shadowRoomId, exceptTableId:", shadowRoomId, exceptTableId, caller=self)
        pigTables = []
        tableId = 0
        for _ in xrange(5):  # 所有桌子有可能正在分配座位,如果取桌子失败,需要休眠后重试
            if gdata.roomIdDefineMap()[shadowRoomId].tableCount == 1:
                tableId = shadowRoomId * 10000 + 1
                tableScore = 100
            else:
                tableId, tableScore = getBestTableIdFromRedis(shadowRoomId)  # 从redis取一个牌桌

                # 该牌桌被客户端指定排除了,另外再取一个牌桌
                if exceptTableId and tableId and exceptTableId == tableId:
                    tableId1, tableScore1 = getBestTableIdFromRedis(shadowRoomId)

                    # 把之前从redis取出的牌桌加回redis
                    self._updateTableScore(shadowRoomId, tableScore, tableId, force=True)
                    tableId, tableScore = tableId1, tableScore1

            if ftlog.is_debug():
                ftlog.debug('getBestTableId shadowRoomId, tableId, tableScore=', shadowRoomId, tableId, tableScore)
            if tableId:
                if TYGame(self.gameId).isWaitPigTable(userId, self, tableId):
                    pigTables.append([shadowRoomId, tableScore, tableId])
                    tableId = 0
                    continue
                else:
                    break
            else:
                FTTasklet.getCurrentFTTasklet().sleepNb(0.2)
        if ftlog.is_debug():
            ftlog.debug('getBestTableId pigTables=', pigTables)
        if pigTables:
            for pig in pigTables:
                self._updateTableScore(pig[0], pig[1], pig[2], False)
        return tableId
Example #11
0
 def getTableSitdown(self, player):
     self._logger.info('TableManager.getTableSitdown player.userId=',
                       player.userId, 'idleTableCount=',
                       self.idleTableCount, 'allTableCount=',
                       self.allTableCount)
     for countN in xrange(5):
         isLock = daobase.executeMixCmd('HGET', RELAXATION_MATCH_LOCK_KEY,
                                        str(self._room.roomId))
         if isLock:
             FTTasklet.getCurrentFTTasklet().sleepNb(0.2)
             if countN >= 4:
                 return None
         else:
             break
     try:
         # 加锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY,
                               str(self._room.roomId), 1)
         sitTable = None
         for t in xrange(self.waitTableCount):
             table = self.waitTableList[t]
             playerList = table.getPlayerList()
             isMeet = False
             isSameIp = False
             # 休闲赛中,桌子内不能匹配当场比赛已经在一起打过的人,同时相同ip的不会坐在一起
             for onePlayer in playerList:
                 if sessiondata.getClientIp(
                         onePlayer.userId) == sessiondata.getClientIp(
                             player.userId):
                     isSameIp = True
                 if onePlayer.meetPlayersMap.get(player.userId,
                                                 None) == player:
                     isMeet = True
             if (not isMeet) and (not isSameIp) and table.idleSeatCount > 0:
                 table.sitdown(player)
                 sitTable = table
                 if table.idleSeatCount <= 0:
                     self._busyTableList.append(table)
                     del self.waitTableList[t]
                 break
                 # 如果在self.waitTableList 找到位置,那么就取self._idleTables里的
         if not sitTable:
             sitTable = self._borrowOneTable()
             if sitTable:
                 sitTable.sitdown(player)
                 self.waitTableList.append(sitTable)
         return sitTable
     finally:
         # 解锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY,
                               str(self._room.roomId), 0)
Example #12
0
 def _trySitdown(self, player, continueBuyin):
     for _ in xrange(3):
         table = self._getTable(player)
         if table:
             table.processing = True
             try:
                 if table.sitdown(player, continueBuyin):
                     return True
             except NoIdleSeatException:
                 pass
             finally:
                 table.processing = False
         FTTasklet.getCurrentFTTasklet().sleepNb(0.5)
     return False
Example #13
0
def process_players():
    count = 0
    deletedUserList = []
    for userId, user in endgame_player_map.items():
        count += 1
        if pktimestamp.getCurrentTimestamp() > user.expireTimeStamp:
            try:
                deletedUserList.append(userId)
                del endgame_player_map[userId]
            except:
                pass
        if count >= 1000:
            count = 0
            FTTasklet.getCurrentFTTasklet().sleepNb(0.5)
    if ftlog.is_debug():
        ftlog.debug('endgame.process_players deletedUserList=', deletedUserList)
def _getInfoFromTxt(behaviourConf):
    try:
        curDate = datetime.datetime.now().strftime('%Y-%m-%d')
        fileName = 'dizhu/behaviour/ddz_prediction_%s.txt' % curDate
        fileName = os.path.join(gdata.pathWebroot(), fileName)

        ret = os.path.isfile(fileName)
        if not ret:
            ftlog.warn('dizhu_user_behaviour.file_not_exist', 'fileName=',
                       fileName, 'ret=', ret)
            return False

        index = 0
        with open(fileName) as fileObject:
            for line in fileObject:
                index += 1
                if not line:
                    break

                infos = line.split('\t')
                userId = infos[0]
                status = infos[1].split('\n')[0]

                try:
                    userId = int(userId)
                except ValueError:
                    ftlog.warn('dizhu_user_behaviour.ValueError userId=',
                               userId)
                    continue

                if not _saveUserToRedis(userId, status, behaviourConf):
                    continue

                if ftlog.is_debug():
                    ftlog.debug('dizhu_user_behaviour.DIZHU_BEHAVIOUR_GROUP',
                                'userId=', userId, 'state=', status)

                # 1000行sleep 0.1秒
                if index >= 1000:
                    index = 0
                    FTTasklet.getCurrentFTTasklet().sleepNb(0.1)

        ftlog.info('dizhu_user_behaviour.fileLoadOver fileName=', fileName)

    except Exception, e:
        ftlog.warn('dizhu_user_behaviour.loadConf. error=', str(e))
        return False
Example #15
0
 def getTableSitdown(self, player):
     self._logger.info('TableManager.getTableSitdown player.userId=', player.userId,
                       'idleTableCount=', self.idleTableCount,
                       'allTableCount=', self.allTableCount)
     for countN in xrange(5):
         isLock = daobase.executeMixCmd('HGET', RELAXATION_MATCH_LOCK_KEY, str(self._room.roomId))
         if isLock:
             FTTasklet.getCurrentFTTasklet().sleepNb(0.2)
             if countN >= 4:
                 return None
         else:
             break
     try:
         # 加锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY, str(self._room.roomId), 1)
         sitTable = None
         for t in xrange(self.waitTableCount):
             table = self.waitTableList[t]
             playerList = table.getPlayerList()
             isMeet = False
             isSameIp = False
             # 休闲赛中,桌子内不能匹配当场比赛已经在一起打过的人,同时相同ip的不会坐在一起
             for onePlayer in playerList:
                 if sessiondata.getClientIp(onePlayer.userId) == sessiondata.getClientIp(player.userId):
                     isSameIp = True
                 if onePlayer.meetPlayersMap.get(player.userId, None) == player:
                     isMeet = True
             if (not isMeet) and (not isSameIp) and table.idleSeatCount > 0:
                 table.sitdown(player)
                 sitTable = table
                 if table.idleSeatCount <= 0:
                     self._busyTableList.append(table)
                     del self.waitTableList[t]
                 break
                 # 如果在self.waitTableList 找到位置,那么就取self._idleTables里的
         if not sitTable:
             sitTable = self._borrowOneTable()
             if sitTable:
                 sitTable.sitdown(player)
                 self.waitTableList.append(sitTable)
         return sitTable
     finally:
         # 解锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY, str(self._room.roomId), 0)
Example #16
0
    def _startMatchTable(self):
        seatInfos = self.matchTableInfo['seats'][:]
        if ftlog.is_debug():
            ftlog.debug('DizhuTableCtrlErdayiMatch._startMatchTable',
                        'tableInfo=', self.matchTableInfo,
                        'userIds=', [seatInfo['userId'] for seatInfo in seatInfos],
                        'tableUserIds=', [seat.userId for seat in self.table.seats])
        
        inter = self._getWaitToNextMatchInter()
        if inter > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(inter)

        for seatInfo in seatInfos:
            player = DizhuPlayerErdayiMatch(self.room, seatInfo['userId'], False, seatInfo)
            self._fillPlayer(player)
            player.score = seatInfo['score']
            player.rank = seatInfo['rank']
            player.isQuit = seatInfo['isQuit']
            self.table.sitdown(player, False)
            if ftlog.is_debug():
                ftlog.debug('DizhuTableCtrlErdayiMatch._startMatchTable',
                            'userId=', player.userId,
                            'score=', player.score,
                            'rank=', player.rank,
                            'seatInfos=', self.matchTableInfo)
        
        for userId in self.AI_USER_IDS:
            seatInfo = {
                'userId':userId,
                'name':'机器人',
                'rank':0,
                'score':0,
                'clientId':'robot_3.7_-hall6-robot',
                'ddzVer':0,
                'cardCount':seatInfos[0].get('cardCard', 0)
            }
            player = DizhuPlayerErdayiMatch(self.room, userId, True, seatInfo)
            self._fillPlayer(player)
            player.score = 0
            self.table.sitdown(player, False)
            
        for seat in self.table.seats:
            self.table.ready(seat, False)
Example #17
0
    def _sendWinloseToMatch(self, result):
        # 发送给match manager
        seatWinloses = []
        for sst in result.seatStatements:
            seatWinloses.append(sst.delta)

        mp = MsgPack()
        mp.setCmd('custom_match')
        mp.setParam('action', 'winlose')
        mp.setParam('gameId', self.gameId)
        mp.setParam('matchId', self.table.matchTableInfo['matchId'])
        mp.setParam('roomId', self.room.ctrlRoomId)
        mp.setParam('tableId', self.tableId)
        mp.setParam('seatWinloses', seatWinloses)
        mp.setParam('ccrc', self.table.matchTableInfo['ccrc'])
        
        if self.WINLOSE_SLEEP > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(self.WINLOSE_SLEEP)
        
        router.sendRoomServer(mp, self.room.ctrlRoomId)
Example #18
0
    def doMatchTableStart(self, msg):
        if ftlog.is_debug():
            ftlog.debug('DizhuMillionHeroMatchTable.doMatchTableStart gameId=',
                        self.gameId, 'roomId=', self.roomId, 'tableId=',
                        self.tableId, 'msg=', msg)

        # 牌桌清理
        self._doMatchTableClear()

        startTime = time.time()
        tableInfo = msg.getKey('params')
        self._doUpdateTableInfo(tableInfo)
        if ftlog.is_debug():
            ftlog.debug('DizhuMillionHeroMatchTable.doMatchTableStart gameId=',
                        self.gameId, 'roomId=', self.roomId, 'tableId=',
                        self.tableId, 'msg=', msg, 'usedTime=',
                        (time.time() - startTime))

        argd = {'handler': self._doMatchQuickStart}
        FTTasklet.create([], argd)
Example #19
0
    def _onSitdown(self, event):
        if ftlog.is_debug():
            ftlog.debug('DizhuTableProtoCustomMatch._onSitdown',
                        'tableId=', event.table.tableId,
                        'seatId=', event.seat.seatId,
                        'userId=', event.seat.userId)
        
        self.sendQuickStartRes(event.seat, True, TYRoom.ENTER_ROOM_REASON_OK)
        if event.table.idleSeatCount == 0:
            # 所有人都坐下后发tableInfo
            self.sendTableInfoResAll()
            
            # 延迟1秒进行animation Info相关处理
            FTTasklet.getCurrentFTTasklet().sleepNb(1)
    
            playAnmi, delaySeconds = self.playAnimationIfNeed(event.table)
            
            if playAnmi and delaySeconds > 0:
                FTTasklet.getCurrentFTTasklet().sleepNb(playAnmi['delaySeconds'])

        self.sendRobotNotifyCallUp(None)
Example #20
0
def sendCarryMessage(msg, userids=[]):
    '''
    发送延迟的携带消息
    '''
    if not msg:
        return
    if isinstance(msg, MsgPack):
        msg = msg.pack()
    assert (isinstance(msg, (str, unicode)))

    if not userids:
        userids = _ONLINE_USERS.keys()
    count = 0
    for userId in userids:
        if userId in _ONLINE_USERS:
            user = _ONLINE_USERS[userId]
            user.carryMsg.append(msg)
            count += 1
            if count % 500 == 0:
                FTTasklet.getCurrentFTTasklet().sleepNb(0.01)
    return count
Example #21
0
def doProxy(httpurl, datas, headers_=None, timeout=3):
    '''
    进行HTTP的代理协议处理
    '''
    postdata_ = ''
    if datas:
        postdata_ = urllib.urlencode(datas)
    body = __StringProducer(postdata_)
    agent = Agent(reactor)
    headers = {}
    if headers_:
        for k, v in headers_:
            headers[k] = [v]
    headers['User-Agent'] = ['Twisted Web Client Proxy']
    if datas:
        headers['Content-type'] = ['application/x-www-form-urlencoded']
    d = agent.request('POST', httpurl, Headers(headers), body)

    request = getRequest()
    resultDeferred = defer.Deferred()

    def cbProxyBody(responsebody):
        try:
            request.write(responsebody)
        except:
            ftlog.error('doProxy->cbProxyBody', httpurl)
        try:
            resultDeferred.callback('')
        except:
            ftlog.error('doProxy->cbProxyBody', httpurl)

    def cbProxyRequest(response):
        try:
            request.setResponseCode(response.code)
            for k, v in response.headers.getAllRawHeaders():
                if isinstance(v, (list, tuple)):
                    for vv in v:
                        request.setHeader(k, vv)
                else:
                    request.setHeader(k, v)
        except:
            ftlog.error('doProxy->cbProxyRequest', httpurl)
        dd = readBody(response)
        dd.addCallback(cbProxyBody)
        return dd

    d.addCallback(cbProxyRequest)
    tasklet = FTTasklet.getCurrentFTTasklet()
    tasklet.waitDefer(resultDeferred, timeout)
    doFinish('', {})
Example #22
0
    def enterOneTable(self, userId, shadowRoomId, tableId):
        '''指定桌子坐下
        Returns
            False: 重试超过次数
        '''
        if ftlog.is_debug():
            ftlog.debug("<< |userId, roomId, shadowRoomId, tableId", userId, self.roomId, shadowRoomId, tableId,
                        caller=self)

        if gdata.roomIdDefineMap()[shadowRoomId].tableCount == 1:
            return tableId

        for _ in xrange(5):  # 这张桌子有可能正在分配座位,如果取桌子失败,需要休眠后重试
            result = daobase.executeTableCmd(shadowRoomId, 0, "ZREM", self.getTableScoresKey(shadowRoomId), tableId)
            if ftlog.is_debug():
                ftlog.debug("after ZREM tableId", "|userId, shadowRoomId, tableId, result:",
                            userId, shadowRoomId, tableId, result, caller=self)
            if result == 1:
                return tableId

            FTTasklet.getCurrentFTTasklet().sleepNb(1)

        return 0
Example #23
0
    def _onSitdown(self, event):
        if ftlog.is_debug():
            ftlog.debug('DizhuTableProtoArenaMatch._onSitdown', 'tableId=',
                        event.table.tableId, 'seatId=', event.seat.seatId,
                        'userId=', event.seat.userId)

        if event.table.idleSeatCount == 0:
            delayConf = dizhuconf.getPublic().get('matchAnimationDelay', '')
            inter = delayConf.get('waitToNextMatch', 3)
            FTTasklet.getCurrentFTTasklet().sleepNb(inter)

            for seat in event.table.seats:
                self.sendQuickStartRes(seat, True, TYRoom.ENTER_ROOM_REASON_OK)

            # 所有人都坐下后发tableInfo
            self.sendTableInfoResAll()

            # 向前端发送牌桌动画信息
            delay = self._playAnimation()
            if delay > 0:
                FTTasklet.getCurrentFTTasklet().sleepNb(delay)

            if event.table.runConf.isSitDownAutoReady:
                self._sendRanks()
Example #24
0
 def notifyMatchStartDelayReport_(self):
     argl = FTTasklet.getCurrentFTTasklet().run_argl
     datas = argl[0]
     userIds = datas['userIds']
     roomId = datas['roomId']
     sequence = datas['sequence']
     index = datas['index']
     ftlog.info('notifyMatchStartDelayReport_ index=', index, 'total=',
                len(userIds))
     nindex = self.notifyMatchStartDelayReport(userIds, roomId, sequence,
                                               index)
     if nindex < 0:
         ftlog.info('notifyMatchStartDelayReport_ end')
     else:
         datas['index'] = nindex
         timer.FTTimer(0.1, self.notifyMatchStartDelayReport_, datas)
Example #25
0
def onAgentSelfCommand(agentProtocol, src, queryid, userheader1, userheader2, message):
    # 处理AGENT自身的命令, 而非转发的命令
    msg = MsgPack()
    try:
        msg.unpack(message)
    except:
        raise Exception('the json data error 2 !! [' + repr(message) + ']')

    task = FTTasklet.getCurrentFTTasklet()
    task.pack = msg
    task.run_args['src'] = src
    task.run_args['pack'] = msg
    if queryid:
        task.run_args['query_id'] = queryid
    task.run_args['userheader1'] = userheader1
    task.run_args['userheader2'] = userheader2
    runcmd.handlerCommand(msg)
Example #26
0
def onAgentSelfCommand(agentProtocol, src, queryid, userheader1, userheader2,
                       message):
    # 处理AGENT自身的命令, 而非转发的命令
    msg = MsgPack()
    try:
        msg.unpack(message)
    except:
        raise Exception('the json data error 2 !! [' + repr(message) + ']')

    task = FTTasklet.getCurrentFTTasklet()
    task.pack = msg
    task.run_args['src'] = src
    task.run_args['pack'] = msg
    if queryid:
        task.run_args['query_id'] = queryid
    task.run_args['userheader1'] = userheader1
    task.run_args['userheader2'] = userheader2
    runcmd.handlerCommand(msg)
Example #27
0
    def doGetVipTableList(self, userId, clientId):
        '''为了效率,贵宾室所有桌子放在一个GT进程里, 在此进程中通过遍历来获取每张桌子的状态
        '''
        msgRes = MsgPack()
        msgRes.setCmd("game")
        msgRes.setResult("action", "vip_table_list")

        clientVer = sessiondata.getClientIdVer(userId)
        if clientVer < 5.0:
            if self.gameId == 8:
                msgRes.setCmd("texas_room_list_response")
            if self.gameId == 30:
                msgRes.setCmd("room")
                msgRes.setResult("action", "vipTableList")

        msg = FTTasklet.getCurrentFTTasklet().pack
        tag = msg.getParam("tag", "")

        msgRes.updateResult(self._getVipTableList(userId, clientId, tag))
        router.sendToUser(msgRes, userId)
Example #28
0
    def doGetVipTableList(self, userId, clientId):
        '''为了效率,贵宾室所有桌子放在一个GT进程里, 在此进程中通过遍历来获取每张桌子的状态
        '''
        msgRes = MsgPack()
        msgRes.setCmd("game")
        msgRes.setResult("action", "vip_table_list")

        clientVer = sessiondata.getClientIdVer(userId)
        if clientVer < 5.0:
            if self.gameId == 8:
                msgRes.setCmd("texas_room_list_response")
            if self.gameId == 30:
                msgRes.setCmd("room")
                msgRes.setResult("action", "vipTableList")

        msg = FTTasklet.getCurrentFTTasklet().pack
        tag = msg.getParam("tag", "")

        msgRes.updateResult(self._getVipTableList(userId, clientId, tag))
        router.sendToUser(msgRes, userId)
Example #29
0
    def _winlose(self):
        table = FTTasklet.getCurrentFTTasklet().run_argl[0]
        playerList = table.getPlayerList()
        win0 = random.randint(0, len(playerList) - 1)
        win1 = random.randint(0, len(playerList) - 1)

        deltaScore = 100
        winScore = 0
        loseScore = 0
        winPlayerCount = 1 if win0 == win1 else 2
        if winPlayerCount == 1:
            winScore = int(deltaScore * 2)
            loseScore = -deltaScore
        else:
            winScore = deltaScore
            loseScore = int(-deltaScore * 2)

        for i, player in enumerate(playerList):
            isWin = i in (win0, win1)
            playerDeltaScore = winScore if isWin else loseScore
            playerDeltaScore = int(playerDeltaScore)
            self.match.winlose(table.tableId, table.ccrc, player.seat.seatId, player.userId, playerDeltaScore, isWin)
Example #30
0
    def _winlose(self):
        table = FTTasklet.getCurrentFTTasklet().run_argl[0]
        playerList = table.getPlayerList()
        win0 = random.randint(0, len(playerList) - 1)
        win1 = random.randint(0, len(playerList) - 1)

        deltaScore = 100
        winScore = 0
        loseScore = 0
        winPlayerCount = 1 if win0 == win1 else 2
        if winPlayerCount == 1:
            winScore = int(deltaScore * 2)
            loseScore = -deltaScore
        else:
            winScore = deltaScore
            loseScore = int(-deltaScore * 2)

        for i, player in enumerate(playerList):
            isWin = i in (win0, win1)
            playerDeltaScore = winScore if isWin else loseScore
            playerDeltaScore = int(playerDeltaScore)
            self.match.winlose(table.tableId, table.ccrc, player.seat.seatId,
                               player.userId, playerDeltaScore, isWin)
Example #31
0
def _sleepnb(sleepTime=0.01):
    if sleepTime > 0:
        FTTasklet.getCurrentFTTasklet().sleepNb(sleepTime)
Example #32
0
def _runInitFun():
    global _init_fun
    if callable(_init_fun):
        FTTasklet.create([], {"handler": _init_fun})
    _init_fun = None
Example #33
0
def _runInitFun():
    global _init_fun
    if callable(_init_fun):
        FTTasklet.create([], {"handler": _init_fun})
    _init_fun = None
Example #34
0
    def getBestTableIdWithScore(self,
                                userId,
                                shadowRoomId,
                                exceptTableId=None):
        '''原子化从redis里获取和删除评分最高的桌子Id
        Return:
            0, 0: tableScores 队列为空, 所有桌子都在分配座位中
        '''
        def getBestTableIdFromRedis(shadowRoomId):
            '''从redis里取出并删除一个评分最高的牌桌
            '''
            tableId, tableScore = 0, 0
            datas = daobase.executeTableLua(
                shadowRoomId, 0, room_scripts.ALIAS_GET_BEST_TABLE_ID_LUA, 1,
                self.getTableScoresKey(shadowRoomId), 0)
            if datas and len(datas) == 2:
                tableId, tableScore = datas[0], datas[1]
                ftlog.info("getBestTableIdFromRedis <<|tableId, tableScore:",
                           tableId, tableScore)
            return tableId, tableScore

        if ftlog.is_debug():
            ftlog.debug("<<",
                        "|shadowRoomId, exceptTableId:",
                        shadowRoomId,
                        exceptTableId,
                        caller=self)

        pigTables = []
        tableId = 0
        tableScore = 0
        for _ in xrange(5):  # 所有桌子有可能正在分配座位,如果取桌子失败,需要休眠后重试
            if gdata.roomIdDefineMap()[shadowRoomId].tableCount == 1:
                tableId = shadowRoomId * 10000 + 1
                tableScore = 100
            else:
                tableId, tableScore = getBestTableIdFromRedis(
                    shadowRoomId)  # 从redis取一个牌桌

                # 该牌桌被客户端指定排除了,另外再取一个牌桌
                if exceptTableId and tableId and exceptTableId == tableId:
                    tableId1, tableScore1 = getBestTableIdFromRedis(
                        shadowRoomId)

                    # 把之前从redis取出的牌桌加回redis
                    self._updateTableScore(shadowRoomId,
                                           tableScore,
                                           tableId,
                                           force=True)
                    tableId, tableScore = tableId1, tableScore1

            if ftlog.is_debug():
                ftlog.debug(
                    'getBestTableId shadowRoomId, tableId, tableScore=',
                    shadowRoomId, tableId, tableScore)
            if tableId:
                if TYGame(self.gameId).isWaitPigTable(userId, self, tableId):
                    pigTables.append([shadowRoomId, tableScore, tableId])
                    tableId = 0
                    continue
                else:
                    break
            else:
                FTTasklet.getCurrentFTTasklet().sleepNb(0.2)
        if ftlog.is_debug():
            ftlog.debug('getBestTableId pigTables=', pigTables)
        if pigTables:
            for pig in pigTables:
                self._updateTableScore(pig[0], pig[1], pig[2], False)
        return tableId, tableScore
Example #35
0
    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)
Example #36
0
                        (code, body))

        if code == 200:
            return 0, uploadPath

        ftlog.info('uploader.uploadVideo Fail uploadUrl=', uploadUrl,
                   'uploadPath=', uploadPath, 'token=', token, 'ret=',
                   (code, body))
        return -1, '上传失败'
    except:
        return -2, '上传失败'


if __name__ == '__main__':
    uploadUrl = 'http://up.wcsapi.biz.matocloud.com:8090/file/upload'
    token = '87c953283acaba7e75340fccad71c97b047569c2:MjEwN2QyMzI2NzAwNDNjYTMzYmQyYjFiYzJiMWRmODg5NDU0YmEyNQ==:eyJzY29wZSI6InR5aGFsbCIsImRlYWRsaW5lIjoiMTQ4NTUyMjU3MDAwMCIsIm92ZXJ3cml0ZSI6MCwiZnNpemVMaW1pdCI6MCwiaW5zdGFudCI6MCwic2VwYXJhdGUiOjB9'

    uploadUrl = 'http://zxty.up0.v1.wcsapi.com/file/upload'
    uploadUrl = 'http://192.168.56.200:9300/file/upload'
    token = '87c953283acaba7e75340fccad71c97b047569c2:OGZhZWE0MDEzZWQ5ZTU5OTdiNmJhY2YwZWNhNzc1MDMxNzAzYzAyYw==:eyJzY29wZSI6InR5aGFsbCIsImRlYWRsaW5lIjoiMTQ4NjY5ODIxNzAwMCIsIm92ZXJ3cml0ZSI6MCwiZnNpemVMaW1pdCI6MCwiaW5zdGFudCI6MCwic2VwYXJhdGUiOjB9'
    from freetime.core.reactor import mainloop

    def runUpload():
        ec, info = uploadVideo(uploadUrl, token, 'ztest_video_4.txt',
                               'videoData_23456')
        print 'runupload ec=', ec, 'info=', info

    argd = {'handler': runUpload}
    FTTasklet.create([], argd)
    mainloop()
Example #37
0
def _sleepnb(sleepTime=0.01):
    if sleepTime > 0:
        FTTasklet.getCurrentFTTasklet().sleepNb(sleepTime)
Example #38
0
                    table.processing = True
                    msg = self.makeSitMsg(userId, shadowRoomId, tableId,
                                          clientId, extParams)
                    isOK = table.doSit(msg, userId, msg.getParam("seatId", 0),
                                       clientId)
                    if not isOK:
                        continue
                    return isOK
                except Exception, e:
                    ftlog.error("_trySitDown error", userId, shadowRoomId,
                                tableId, clientId, extParams,
                                traceback.format_exc())
                finally:
                    if table:
                        table.processing = False
                FTTasklet.getCurrentFTTasklet().sleepNb(0.2)
            return False

    def getBestTable(self, userId):
        table = None
        self._updateUsableTableDict()
        if self._usableTableDict:
            maxSeatN = self.roomConf.get("tableConf", {}).get("maxSeatN", 4)
            if maxSeatN == 1:
                usableTableList = []
                for _, v in self._usableTableDict.iteritems():
                    usableTableList.extend(v)
                if usableTableList:
                    table = choice(usableTableList)
            else:
                mainTaskId = util.getMainTaskId(userId, self.bigRoomId)
Example #39
0
                        'uploadPath=', uploadPath,
                        'token=', token,
                        'ret=', (code, body))

        if code == 200:
            return 0, body

        ftlog.info('uploader.uploadVideo Res uploadUrl=', uploadUrl,
                   'uploadPath=', uploadPath,
                   'token=', token,
                   'ret=', code)
        return -1, '上传失败'
    except:
        return -2, '上传失败'


if __name__ == '__main__':
    uploadUrl = 'http://up.wcsapi.biz.matocloud.com:8090/file/upload/'
    token = '87c953283acaba7e75340fccad71c97b047569c2:MjEwN2QyMzI2NzAwNDNjYTMzYmQyYjFiYzJiMWRmODg5NDU0YmEyNQ==:eyJzY29wZSI6InR5aGFsbCIsImRlYWRsaW5lIjoiMTQ4NTUyMjU3MDAwMCIsIm92ZXJ3cml0ZSI6MCwiZnNpemVMaW1pdCI6MCwiaW5zdGFudCI6MCwic2VwYXJhdGUiOjB9'
    from freetime.core.reactor import mainloop


    def runUpload():
        ec, info = uploadVideo(uploadUrl, token, 'util1.py', zlib.compress('util.py'))
        print 'runupload ec=', ec, 'info=', info


    argd = {'handler': runUpload}
    FTTasklet.create([], argd)
    mainloop()