예제 #1
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)
예제 #2
0
파일: state.py 프로젝트: luningcowboy/tuyoo
    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
예제 #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)
예제 #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
예제 #5
0
파일: table.py 프로젝트: luningcowboy/tuyoo
    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)
예제 #6
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)
예제 #7
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)
예제 #8
0
    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)
예제 #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
예제 #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
예제 #11
0
파일: models.py 프로젝트: zhaozw/hall37
 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)
예제 #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
예제 #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)
예제 #14
0
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
예제 #15
0
파일: models.py 프로젝트: zhaozw/hall37
 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)
예제 #16
0
파일: table.py 프로젝트: luningcowboy/tuyoo
    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)
예제 #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)
예제 #18
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)
예제 #19
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
예제 #20
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
예제 #21
0
파일: runhttp.py 프로젝트: zhaozw/hall37
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('', {})
예제 #22
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()
예제 #23
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)
예제 #24
0
파일: protocols.py 프로젝트: zhaozw/hall37
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)
예제 #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)
예제 #26
0
파일: vip_room.py 프로젝트: zhaozw/hall37
    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)
예제 #27
0
파일: vip_room.py 프로젝트: zhaozw/hall37
    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)
예제 #28
0
파일: matchtest.py 프로젝트: zhaozw/hall37
    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)
예제 #29
0
파일: matchtest.py 프로젝트: zhaozw/hall37
    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)
예제 #30
0
파일: synccenter.py 프로젝트: zhaozw/hall37
def _sleepnb(sleepTime=0.01):
    if sleepTime > 0:
        FTTasklet.getCurrentFTTasklet().sleepNb(sleepTime)
예제 #31
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
예제 #32
0
    def add(self,
            gameId,
            userAssets,
            kindId,
            count,
            timestamp,
            eventId,
            intEventParam,
            roomId=0,
            tableId=0,
            roundId=0,
            param01=0,
            param02=0):

        assert (count >= 0)
        assert (eventId == "BUY_PRODUCT")
        userId = userAssets.userId

        ftlog.info("kindId, count, intEventParam:", kindId, count,
                   intEventParam)

        # intProductId = intEventParam
        # productId = configure.numberToStringId("poker:map.productid", intProductId)
        # product = hallstore.storeSystem.findProduct(productId)
        # priceRmb = float(product.priceDiamond) / 10

        from hall.entity import hallitem, datachangenotify
        from freetime.core.tasklet import FTTasklet
        curr_tasklet = FTTasklet.getCurrentFTTasklet()
        order = curr_tasklet.order
        priceRmb = float(order.product.priceDiamond) / 10

        cardType = int(kindId.split(':')[1])
        final = before = _get_fangka_count(userId, cardType, userAssets)
        ret_code, ret_msg = _http_buy(cardType, userId, count, priceRmb)

        if ret_code == 1:
            itemKind = hallitem.itemSystem.findItemKind(cardType)
            if not itemKind:
                ftlog.error('TYAssetKindDifangFangka.add |itemKind not found',
                            '|userId:', userId, 'kindId:', kindId, 'cardType:',
                            cardType, 'count:', count)
                return before

            userBag = userAssets.getUserBag()
            userBag.addItemUnitsByKind(gameId,
                                       itemKind,
                                       count,
                                       timestamp,
                                       0,
                                       eventId,
                                       intEventParam,
                                       roomId=roomId,
                                       tableId=tableId,
                                       roundId=roundId,
                                       param01=param01,
                                       param02=param02)
            datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
            tools.callLater(5, datachangenotify.sendDataChangeNotify, gameId,
                            userId, 'item')
            tools.callLater(10, datachangenotify.sendDataChangeNotify, gameId,
                            userId, 'item')

            final = _get_fangka_count(userId, cardType, userAssets)

        ftlog.info('TYAssetKindDifangFangka.add gameId=', gameId, 'userId=',
                   userId, 'kind=', kindId, 'count=', count, 'timestamp=',
                   timestamp, 'eventId=', eventId, 'intEventParam=',
                   intEventParam, 'ret_code=', ret_code, 'ret_msg=', ret_msg,
                   'before=', before, 'final=', final)

        if ret_code != 1:
            raise TYBizException(ret_code, ret_msg)

        return final
예제 #33
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)
예제 #34
0
파일: synccenter.py 프로젝트: zhaozw/hall37
def _sleepnb(sleepTime=0.01):
    if sleepTime > 0:
        FTTasklet.getCurrentFTTasklet().sleepNb(sleepTime)
예제 #35
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)
예제 #36
0
    def doWinLose(cls, room, table, seatId, isTimeOutKill=False):
        if not table._match_table_info:
            ftlog.warn('ErdayiMatch.doWinLoseTable roomId=', room.roomId,
                       'tableId=', table.tableId, 'seatId=', seatId,
                       'isTimeOutKill=', isTimeOutKill, 'err=',
                       'not matchTableInfo')
            return

        # 计算春天
        dizhuseatId = table.status.diZhu
        if seatId != dizhuseatId:
            if table.seats[dizhuseatId - 1].outCardCount == 1:
                table.status.chuntian = 2
        else:
            s1 = table.seats[(dizhuseatId - 1 + 1) % table.maxSeatN]
            s2 = table.seats[(dizhuseatId - 1 + 2) % table.maxSeatN]
            if s1.outCardCount == 0 and s2.outCardCount == 0:
                table.status.chuntian = 2

        # 翻倍计算 叫地主的倍数
        windoubles = table.status.callGrade
        # 炸弹倍数
        windoubles *= pow(2, table.status.bomb)
        # 春天倍数
        windoubles *= table.status.chuntian
        # 底牌倍数
        windoubles *= table.status.baseCardMulti
        # 明牌倍数
        windoubles *= table.status.show

        dizhuwin = 0
        if seatId == dizhuseatId:
            dizhuwin = 1
        if seatId == 0:  # 流局
            dizhuwin = 0
            windoubles = 1
        else:
            windoubles = abs(windoubles)

        userids = [seat.userId for seat in table.seats]
        seat_coin = [0] * len(table.seats)
        detalChips = [0] * len(table.seats)
        baseBetChip = table._match_table_info['step']['basescore']
        robot_card_count = [0] * len(table.seats)  # 每个座位

        # 计算所有农民的输赢
        for i, player in enumerate(table.players):
            userids.append(player.userId)
            if seatId == 0:
                detalChips[i] = -baseBetChip
            if i + 1 == dizhuseatId:
                continue
            detalChip = baseBetChip * windoubles
            # 计算本农民的倍数
            seatMulti = max(table.seats[i].seatMulti, 1) * max(
                table.seats[dizhuseatId - 1].seatMulti, 1)
            detalChip *= seatMulti
            if dizhuwin:
                detalChip *= -1
            detalChips[i] = detalChip
            detalChips[dizhuseatId - 1] -= detalChip
            if ftlog.is_debug():
                ftlog.debug('ErdayiMatch.doWinLoseTable roomId=', room.roomId,
                            'tableId=', table.tableId, 'seatId=', seatId,
                            'dizhuseatId=', dizhuseatId, 'detalChip=',
                            detalChip, 'dizhuDetalChip=',
                            detalChips[dizhuseatId - 1])

        punish.Punish.doWinLosePunish(table.runConfig.punishCardCount,
                                      table.runConfig.isMatch, seat_coin,
                                      detalChips, robot_card_count)
        seat_coin = [0] * len(table.seats)
        for i, seatInfo in enumerate(table._match_table_info['seats']):
            seat_coin[i] = seatInfo['score']
        # 返回当前Table的game_win
        moWin = MsgPack()
        moWin.setCmd('table_call')
        moWin.setResult('action', 'game_win')
        moWin.setResult('isMatch', 1)
        moWin.setResult('gameId', table.gameId)
        moWin.setResult('roomId', table.roomId)
        moWin.setResult('tableId', table.tableId)
        #         moWin.setResult('stat', dict(zip(tdz_stat_title, table.status)))
        moWin.setResult('stat', table.status.toInfoDictExt())
        moWin.setResult('dizhuwin', dizhuwin)
        if seatId == 0:
            moWin.setResult('nowin', 1)
        moWin.setResult('slam', 0)
        moWin.setResult('cards', [seat.cards for seat in table.seats])

        roundId = table.gameRound.number
        table.clear(userids)

        for i, player in enumerate(table.players):
            uid = player.userId
            mrank = 3
            mtableRanking = 3
            moWin.setResult('seat' + str(player.seatId), [
                detalChips[i], seat_coin[i], 0, 0, 0, 0, mrank, mtableRanking
            ])
            if not player.isAI:
                #增加经验
                exp = userdata.incrExp(uid, 20)
                explevel = dizhuaccount.getExpLevel(exp)
                gamedata.setGameAttr(uid, table.gameId, 'level', explevel)
                if ftlog.is_debug():
                    ftlog.debug('ErdayiMatch.doWinLoseTable', 'addExp=', 20,
                                'curExp=', exp, 'curLevel=', explevel)

        table.gamePlay.sender.sendToAllTableUser(moWin)

        # 发送给match manager
        users = []
        for i, player in enumerate(table.players):
            if not player.isAI:
                user = {}
                user['userId'] = player.userId
                user['deltaScore'] = int(detalChips[i])
                user['seatId'] = player.seatId
                users.append(user)

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

        if cls.WINLOSE_SLEEP > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(cls.WINLOSE_SLEEP)
        # 记录游戏winlose
        try:
            for u in users:
                table.room.reportBiGameEvent('TABLE_WIN', u['userId'],
                                             table.roomId, table.tableId,
                                             roundId, u['deltaScore'], 0, 0,
                                             [], 'table_win')
        except:
            if ftlog.is_debug():
                ftlog.exception()
        router.sendRoomServer(mnr_msg, table.room.ctrlRoomId)
예제 #37
0
파일: match.py 프로젝트: luningcowboy/tuyoo
    def doWinLose(cls, room, table, seatId, isTimeOutKill=False): # TODO:
        if not table._match_table_info:
            ftlog.warn('GroupMatch.doWinLoseTable roomId=', room.roomId,
                       'tableId=', table.tableId,
                       'seatId=', seatId,
                       'isTimeOutKill=', isTimeOutKill,
                       'err=', 'not matchTableInfo')
            return

        if ftlog.is_debug():
            ftlog.debug('GroupMatch.doWinLose roomId=', room.roomId,
                        'tableId=', table.tableId,
                        'seatId=', seatId,
                        'isTimeOutKill=', isTimeOutKill,
                        'stageReward=', table.group.stageConf.conf.get('stageReward'))
        
        # 计算春天
        dizhuseatId = table.status.diZhu
        if seatId != dizhuseatId: 
            if table.seats[dizhuseatId - 1].outCardCount == 1:
                table.status.chuntian = 2
        else:
            s1 = table.seats[(dizhuseatId - 1 + 1) % table.maxSeatN]
            s2 = table.seats[(dizhuseatId - 1 + 2) % table.maxSeatN]
            if s1.outCardCount == 0 and s2.outCardCount == 0:
                table.status.chuntian = 2
                 
        # 翻倍计算 叫地主的倍数
        windoubles = table.status.callGrade
        # 炸弹倍数
        windoubles *= pow(2, table.status.bomb)
        # 春天倍数
        windoubles *= table.status.chuntian
        # 底牌倍数
        windoubles *= table.status.baseCardMulti
        # 明牌倍数
        windoubles *= table.status.show
         
        dizhuwin = 0
        if seatId == dizhuseatId:
            dizhuwin = 1
        if seatId == 0 : # 流局
            dizhuwin = 0
            windoubles = 1
        else:
            windoubles = abs(windoubles)
 
        userids = []
        detalChips = []
        seat_coin = []
        baseBetChip = table._match_table_info['mInfos']['basescore']
        robot_card_count = [0] * len(table.seats)  # 每个座位
        for x in xrange(len(table.seats)):
            uid = table.seats[x].userId
            userids.append(uid)
            if seatId == 0 : # 流局
                detalChip = -baseBetChip
            else:
                if dizhuwin :
                    if x + 1 == dizhuseatId :
                        detalChip = baseBetChip + baseBetChip
                    else:
                        detalChip = -baseBetChip
                else:
                    if x + 1 == dizhuseatId :
                        detalChip = -baseBetChip - baseBetChip
                    else:
                        detalChip = baseBetChip
            detalChip *= windoubles
            detalChips.append(detalChip)
            seat_coin.append(table._match_table_info['mInfos']['scores'][x] + detalChip)
            robot_card_count[x] = table.seats[x].robotCardCount
            ftlog.info('dizhu.game_win userId=', uid, 'roomId=', room.roomId, 'tableId=', table.tableId, 'delta=', detalChip)
        
        punish.Punish.doWinLosePunish(table.runConfig.punishCardCount, table.runConfig.isMatch,
                                      seat_coin, detalChips, robot_card_count)
        for x in xrange(len(table.seats)):
            uid = table.seats[x].userId
            table._match_table_info['mInfos']['scores'][x] = seat_coin[x]

        # 返回当前Table的game_win
        moWin = MsgPack()
        moWin.setCmd('table_call')
        moWin.setResult('action', 'game_win')
        moWin.setResult('isMatch', 1)
        moWin.setResult('gameId', table.gameId)
        moWin.setResult('roomId', table.roomId)
        moWin.setResult('tableId', table.tableId)
#         moWin.setResult('stat', dict(zip(tdz_stat_title, table.status)))
        moWin.setResult('stat', table.status.toInfoDictExt())
        moWin.setResult('dizhuwin', dizhuwin)
        if seatId == 0:
            moWin.setResult('nowin', 1)
        moWin.setResult('slam', 0)
        moWin.setResult('cards', [seat.cards for seat in table.seats])
        
        roundId = table.gameRound.number
        table.clear(userids)
         
        for x in xrange(len(userids)):
            uid = userids[x]
            mrank = 3
            mtableRanking = 3
            moWin.setResult('seat' + str(x + 1), [detalChips[x], seat_coin[x], 0, 0, 0, 0, mrank, mtableRanking])

            if detalChips[x] > 0:
                stageRewards = table.group.stageConf.conf.get('stageReward', None) if table.group.stageConf else None
                if stageRewards:
                    contentItems = TYContentItem.decodeList(stageRewards)
                    assetList = dizhu_util.sendRewardItems(uid, contentItems, '', 'DIZHU_STAGE_REWARD', 0)
                    moWin.setResult('stageReward', stageRewards)
                    ftlog.info('stageRewards send. userId=', uid, 'stageRewards=', stageRewards, 'assetList=', assetList)

            #增加经验
            exp = userdata.incrExp(uid, 20)
            explevel = dizhuaccount.getExpLevel(exp)
            gamedata.setGameAttr(uid, table.gameId, 'level', explevel)
            if ftlog.is_debug():
                ftlog.debug('BigMatch.doWinLoseTable',
                            'addExp=', 20,
                            'curExp=', exp,
                            'curLevel=', explevel)
             
        table.gamePlay.sender.sendToAllTableUser(moWin)
         
        # 发送给match manager
        users = []
        for x in xrange(len(userids)):
            user = {}
            user['userId'] = userids[x]
            user['deltaScore'] = int(detalChips[x])
            user['seatId'] = x + 1
            users.append(user)
         
        mnr_msg = MsgPack()
        mnr_msg.setCmd('room')
        mnr_msg.setParam('action', 'm_winlose')
        mnr_msg.setParam('gameId', table.gameId)
        mnr_msg.setParam('matchId', table.room.bigmatchId)
        mnr_msg.setParam('roomId', table.room.ctrlRoomId)
        mnr_msg.setParam('tableId', table.tableId)
        mnr_msg.setParam('users', users)
        mnr_msg.setParam('ccrc', table._match_table_info['ccrc'])
        
        if cls.WINLOSE_SLEEP > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(cls.WINLOSE_SLEEP)
        # 记录游戏winlose
        try:
            for u in users:
                table.room.reportBiGameEvent('TABLE_WIN', u['userId'], table.roomId,
                                             table.tableId, roundId, u['deltaScore'],
                                             0, 0, [], 'table_win')
        except:
            if ftlog.is_debug():
                ftlog.exception()
        router.sendRoomServer(mnr_msg, table.room.ctrlRoomId)