コード例 #1
0
ファイル: httphello.py プロジェクト: zhaozw/hall37
def getGaoFangIp2(userId, clientId):
    ip, port = '', 0
    try:
        gaofangConfs = configure.getJson('poker:map.gaofangip.2', {})
        policy = gaofangConfs.get('policy')
        if policy == 'defence2':
            intClientId = sessiondata.getClientIdNum(userId, clientId)
            clientIds = gaofangConfs['clientIds']
            areaId = clientIds.get(intClientId)
            if not areaId:
                areaId = clientIds.get(str(intClientId))
                if not areaId:
                    areaId = clientIds.get('default')
                    if not areaId:
                        areaId = gaofangConfs['areas'].keys()[0]
                    ftlog.warn('ERROR, getGaoFangIp2 not found area id of ',
                               intClientId, clientId, 'use default !')
                clientIds[intClientId] = areaId
            entrys = gaofangConfs['areas'][areaId]
            ipPorts = random.choice(entrys)  # 切换不同的端口接入
            ipPort = ipPorts[userId % len(ipPorts)]  # 使用相对固定的IP地址接入
            ip, port = ipPort[0], ipPort[1]
    except:
        ftlog.error()
    ftlog.info('getGaoFangIp2->', ip, port, userId, clientId)
    return ip, port
コード例 #2
0
ファイル: playmode.py プロジェクト: luningcowboy/tuyoo
 def standup(self, table, seat, reason):
     '''
     清空站起的座位
     '''
     assert(seat.table == table)
     
     if not seat.player:
         ftlog.warn('PlayMode.standup',
                    'tableId=', table.tableId,
                    'seatId=', seat.seatId)
         raise EmptySeatException()
     
     assert(table.gameRound is None)
     
     player = seat._player
     
     if table.dealer.buyinPolicy:
         try:
             table.dealer.buyinPolicy.cashin(table, player, seat)
         except Exception, e:
             ftlog.warn('PlayMode.standup cashin',
                        'tableId=', table.tableId,
                        'seatId=', seat.seatId,
                        'userId=', player.userId,
                        'ex=', str(e))
コード例 #3
0
ファイル: httphello.py プロジェクト: luningcowboy/tuyoo
def getGaoFangIp2(userId, clientId):
    ip, port, wsport = '', 0, 0
    try:
        gaofangConfs = configure.getJson('poker:map.gaofangip.2', {})
        policy = gaofangConfs.get('policy')
        if policy == 'defence2':
            intClientId = sessiondata.getClientIdNum(userId, clientId)
            clientIds = gaofangConfs['clientIds']
            areaId = clientIds.get(intClientId)
            if not areaId:
                areaId = clientIds.get(str(intClientId))
                if not areaId:
                    areaId = clientIds.get('default')
                    if not areaId:
                        areaId = gaofangConfs['areas'].keys()[0]
                    ftlog.warn('ERROR, getGaoFangIp2 not found area id of ',
                               intClientId, clientId, 'use default !')
                clientIds[intClientId] = areaId
            entrys = gaofangConfs['areas'][areaId]
            ipPorts = entrys[userId % len(entrys)] # 切换不同的端口接入
            ipPort = ipPorts[userId % len(ipPorts)] # 使用相对固定的IP地址接入
            ip, port = ipPort[0], ipPort[1]
            if len(ipPort) > 2 :
                wsport = ipPort[2]
    except:
        ftlog.error()
    ftlog.info('getGaoFangIp2->', ip, port, wsport, userId, clientId)
    return ip, port, wsport
コード例 #4
0
ファイル: match_remote.py プロジェクト: luningcowboy/tuyoo
def createMatchUser(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.createUserMatchInfo gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if userMatchInfo:
        if userMatchInfo.instId == instId:
            if userMatchInfo.state == UserMatchInfo.ST_SIGNIN:
                return ERR_ALREADY_SIGNIN
            return ERR_ALREADY_IN_MATCH
        else:
            ftlog.warn('match_remote.createUserMatchInfo gameId=', gameId,
                       'userId=', userId,
                       'contentItem=', contentItem,
                       'bigRoomId=', bigRoomId,
                       'instId=', instId,
                       'ctrlRoomId=', ctrlRoomId,
                       'recordInstId=', userMatchInfo.instId)
            
    userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId)
    userMatchInfo.ctrlRoomId = ctrlRoomId
    userMatchInfo.instId = instId
    if contentItem:
        userMatchInfo.feeItem = TYContentItem.decodeFromDict(contentItem)
    saveUserMatchInfo(userMatchInfo)
    return 0
コード例 #5
0
ファイル: quick_start.py プロジェクト: zhaozw/mjserver
    def _onEnterRoomFailed(cls,
                           msg,
                           checkResult,
                           userId,
                           gameId,
                           clientId,
                           roomId=0):
        '''进入房间失败回调函数'''
        ftlog.warn("|userId, reason, roomId:",
                   userId,
                   checkResult,
                   roomId,
                   caller=cls)  # 调用最小房间金币不够充值提醒的todotask
        if not roomId:
            roomId = msg.getParam('candidateRoomId', 0)
        if checkResult == TYRoom.ENTER_ROOM_REASON_LESS_MIN or checkResult == 104:
            from hall.entity import hallproductselector
            product, _ = hallproductselector.selectLessbuyProduct(
                gameId, userId, clientId, roomId)
            if product:
                from hall.entity.todotask import TodoTaskOrderShow
                todotask = TodoTaskOrderShow.makeByProduct(
                    "金币不够啦,买一个超值礼包吧!", "", product)
                if todotask:
                    TodoTaskHelper.sendTodoTask(gameId, userId, todotask)

        mo = MsgPack()
        mo.setCmd('quick_start')
        mo.setResult('gameId', gameId)
        mo.setResult('userId', userId)
        mo.setError(checkResult, '进入房间失败,请稍后重试')
        router.sendToUser(mo, userId)
コード例 #6
0
    def doCallDizhuTimeOut(self, player):
        '''
        叫地主超时
        '''
        ftlog.debug('doCallDizhuTimeOut...')

        if not player or self.table.status.state != DizhuState.TABLE_STATE_CALLING:
            ftlog.warn('ERROR !!, doCallDizhuTimeOut table.status=',
                       self.table.status, player)
            return

        assert (self.table.status.callGrade < 3)

        if TYPlayer.isHuman(player.userId):
            # 真实玩家超时默认不叫地主
            call = 0
        else:
            # AI必须叫地主
            if self.table.status.callGrade <= 0:
                call = 1
            else:
                call = self.table.status.callGrade + 1

        # 系统主动替玩家进行叫地主, 1分
        self.doCallDizhu(player, -1, call, DizhuPlayer.TUGUAN_TYPE_TIMEOUT)
コード例 #7
0
def chooseReward(self, userId, matchId, rank):
    if ftlog.is_debug():
        ftlog.debug('MatchLottery userId=', userId, 'matchId=', matchId,
                    'rank=', rank)

    if not self.matchList:
        d = dizhuconf.getMatchLotteryConf()
        self.decodeFromDict(d)

    if not self.checkMatchRank(userId, matchId):
        ftlog.warn('MatchLottery.checkMatchRank failed. userId=', userId,
                   'matchId=', matchId, 'rank=', rank)
        return None, None

    items = self.getMatchLotteryConf(matchId, rank)
    if not items:
        ftlog.warn('MatchLottery.checkMatchRank failed. no items. userId=',
                   userId, 'matchId=', matchId, 'rank=', rank)
        return None, None

    weights = 0
    for item in items:
        weights += item.get('weight', 0)
    r = random.randint(0, weights)
    lotteryReward = []
    weightTotal = 0
    for item in items:
        weightTotal += item.get('weight', 0)
        if r <= weightTotal:
            lotteryReward.append({
                'itemId': str(item.get('itemId')),
                'count': item.get('count')
            })
            break
    lotteryReward = items[-1] if not lotteryReward else lotteryReward

    if ftlog.is_debug():
        ftlog.debug('MatchLottery weights=', weights, 'r=', r, 'userId=',
                    userId, 'lotteryReward=', lotteryReward)

    if lotteryReward:
        contentItems = TYContentItem.decodeList(lotteryReward)
        assetList = dizhu_util.sendRewardItems(userId, contentItems, '',
                                               'DIZHU_MATCH_LOTTERY', 0)

        ftlog.info('MatchLottery.chooseReward userId=', userId, 'matchId=',
                   matchId, 'lotteryReward=', lotteryReward, 'assetList=',
                   assetList)

    for i in items:
        assetKind = hallitem.itemSystem.findAssetKind(i['itemId'])
        i['img'] = assetKind.pic
        i['des'] = assetKind.desc
        i['name'] = assetKind.displayName

    if ftlog.is_debug():
        ftlog.debug('MatchLottery.chooseReward userId=', userId, 'matchId=',
                    matchId, 'rank=', rank, 'lotteryReward=', lotteryReward)

    return lotteryReward, items
コード例 #8
0
def processWhenUserLogin(self, gameId, isDayFirst, timestamp=None):
    '''
    当用户登录时调用该方法,处理对用户登录感兴趣的道具
    @param gameId: 哪个游戏驱动
    @param isDayFirst: 是否是
    '''
    items = list(self._itemIdMap.values())
    timestamp = timestamp if timestamp is not None else pktimestamp.getCurrentTimestamp(
    )
    for item in items:
        needRemove = False
        if item.needRemoveFromBag(timestamp):
            self._removeItem(item)
            needRemove = True
        else:
            item.itemKind.processWhenUserLogin(item, self._assets, gameId,
                                               isDayFirst, timestamp)

        try:
            if item.kindId == 1086:
                ftlog.info('TYUserBagImpl.processWhenUserLogin', 'userId=',
                           self.userId, 'itemId=', item.itemId, 'itemData=',
                           item.encodeToItemData().toDict(), 'needRemove=',
                           needRemove, 'timestamp=', timestamp)
        except:
            ftlog.warn('TYUserBagImpl.processWhenUserLogin', 'userId=',
                       self.userId, 'itemId=', item.itemId, 'itemData=',
                       item.encodeToItemData().toDict(), 'needRemove=',
                       needRemove, 'timestamp=', timestamp)
コード例 #9
0
    def encodeExchanges(cls, gameId, userId, clientId, exchangeIds, timestamp):
        ret = []
        for exchangeId in exchangeIds:
            exchangeObj = hall_exmall.findExchange(exchangeId)
            if not exchangeObj:
                ftlog.warn(
                    'HallExMallHandler.encodeExchanges NotFoundExchange',
                    'userId=', userId, 'clientId=', clientId, 'exchangeId=',
                    exchangeId, 'timestamp=', timestamp)
                continue

            if not hall_exmall.canDisplayExchange(userId, clientId,
                                                  exchangeObj, timestamp):
                if ftlog.is_debug():
                    ftlog.debug(
                        'HallExMallHandler.encodeExchanges CanntDisplay',
                        'userId=', userId, 'clientId=', clientId,
                        'exchangeId=', exchangeId, 'timestamp=', timestamp)
                continue

            try:
                encoded = cls.encodeExchange(gameId, userId, clientId,
                                             exchangeObj, timestamp)
                ret.append(encoded)
            except:
                ftlog.error('HallExMallHandler.encodeExchanges Exception',
                            'userId=', userId, 'clientId=', clientId,
                            'exchangeId=', exchangeId, 'timestamp=', timestamp)
        return ret
コード例 #10
0
def query(dst, data, userheader1='', userheader2='', timeout=2, notimeoutex=0, returnDeffer=0):
    src = ftcon.global_config["server_id"]
    server_conf = ftcon.getServerConf(src)
    agent_id = server_conf['agent']
    protocol = ftcon.serverid_protocol_map[agent_id]
    if ide_debug():
        ide_print_pack("Query[%s]" % dst.split("-")[0], json.loads(data))
    d = protocol.query(src, dst, userheader1, userheader2, data, timeout, notimeoutex=notimeoutex)
    if returnDeffer == 1:
        return d
    res = stackless.getcurrent()._fttask.waitDefer(d)
    global _QUERY_SLOW_TIME
    if isinstance(res, tuple):
        msg = res[0]
        query_write_time = res[1]
        query_recive_time = res[2]
        ct = time()
        if ct - query_write_time > _QUERY_SLOW_TIME:
            if performance.PERFORMANCE_NET:
                msg = performance.linkMsgTime('DO', msg)
            ftlog.warn('QUERY REPLAY SLOW ! reply=%0.6f' % (query_recive_time - query_write_time),
                       'schedule=%0.6f' % (ct - query_recive_time), 'total=%0.6f' % (ct - query_write_time),
                       'dst=', dst, 'request=', data, 'response=', msg)
        return msg
    return res
コード例 #11
0
def doTreasureBox1(userId):
    datas = _getTbData(userId)
    tbroomid = datas['tbroomid']
    if not tbroomid:
        ftlog.warn('doTreasureBox1 userId=', userId, 'datas=', datas)
        return {'ok': 0, 'info': '本房间不支持宝箱,请进入高倍房再使用'}
    return doTreasureBox(userId, tbroomid)
コード例 #12
0
ファイル: hallnewnotify.py プロジェクト: luningcowboy/tuyoo
    def __init__(self, argd):
        self.argd = argd
        self._alive = False

        if self.argd['ntimeId'] == NOTIFY_TIME_ATONCE_ID:
            self.startTimer = FTTimer(0, self.start)
            ftlog.hinfo('Notify.__init__ atonce', self.argd)
        else:
            ntime = [0, 1]
            if self.argd['ntimeId'] == NOTIFY_TIME_TIMER_ID:
                try:
                    dtList = self.argd['ntime'].split('|')
                    ntime = map(int, dtList[1].split(':'))
                except:
                    ftlog.warn('Notify.__init__.NOTIFY_TIME_TIMER_ID error')
                    ntime = map(int, '00:01'.split(':'))
            else:
                ntime = map(int, self.argd['ntime'].split(':'))
            hm = map(int, getNowTimeStr().split(':'))

            interval = (ntime[0] * 60 * 60 +
                        ntime[1] * 60) - (hm[0] * 60 * 60 + hm[1] * 60)
            ftlog.hinfo('Notify.__init__ begin:', ntime, hm, interval,
                        (ntime[0] * 60 * 60 + ntime[1] * 60),
                        (hm[0] * 60 * 60 + hm[1] * 60))
            if interval > 0:
                self.startTimer = FTTimer(interval, self.start)

            ftlog.hinfo('Notify.__init__ end:', interval, self.argd)
コード例 #13
0
ファイル: httpgame.py プロジェクト: luningcowboy/tuyoo
 def getJdAddress(self, proviceId, cityId, countyId):
     try:
         if proviceId:
             addrs = self._getJdAddress(
                 'http://gdss.touch4.me/?act=api.getJdCity',
                 ('proviceId', proviceId), self.JD_ADDRESS_RET_CODE_OK)
         elif cityId:
             addrs = self._getJdAddress(
                 'http://gdss.touch4.me/?act=api.getJdCounty',
                 ('cityId', cityId), self.JD_ADDRESS_RET_CODE_OK)
         elif countyId:
             addrs = self._getJdAddress(
                 'http://gdss.touch4.me/?act=api.getJdTown',
                 ('townId', countyId),  # gdss接口参数名字起错了,将错就错
                 self.JD_ADDRESS_RET_CODE_OK,
                 self.JD_ADDRESS_RET_CODE_NO_DATA)  # 四级地址可能是没有的
         else:
             addrs = self._getJdAddress(
                 'http://gdss.touch4.me/?act=api.getJdProvice',
                 ('', 0),  # 无需参数,硬造个key
                 self.JD_ADDRESS_RET_CODE_OK)
         return {'retcode': 0, 'retmsg': addrs}
     except Exception, e:
         ftlog.warn('HttpGameHandler.getJdAddress failed', e)
         return {'retcode': -1}
コード例 #14
0
ファイル: tasklet.py プロジェクト: zhaozw/hall37
 def tasklet(self):
     global DEBUG_TASK_MAIN_TIME, DEBUG_TASK_MAP, DEBUG_TASK_SCHEDULE, SLOW_TASK_TIMES
     self._return_channel = FTChannel()
     self._me = stackless.getcurrent()
     if DEBUG_TASK_SCHEDULE:
         tkey = repr(self._me)
         DEBUG_TASK_MAP[tkey].insert(0, (self.run_args['creattime'], "create"))
         DEBUG_TASK_MAP[tkey].append((time(), "run"))
     self._timeocall = None
     self._me._fttask = self
     ctn = time()
     try:
         self.handle()
         ct = time()
         rtime = ct - ctn
         time_recv = self.run_args.get('time_recv', 0)
         if time_recv:
             time_recv = ctn - time_recv
         if rtime > SLOW_TASK_TIMES or time_recv > SLOW_TASK_TIMES:
             ftlog.warn('TASKLET TOO SLOW !! runtime=%0.6f' % (rtime), 'schedule=%0.6f' % (time_recv), 'ct=', ct,
                        'args=', self.run_args)
     except:
         ftlog.error('tasklet handle error', self.run_args)
     FTTasklet.concurrent_task_count -= 1
     if DEBUG_TASK_SCHEDULE:
         del DEBUG_TASK_MAP[tkey]
コード例 #15
0
ファイル: match_remote.py プロジェクト: zhaozw/hall37
def createMatchUser(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.createUserMatchInfo gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if userMatchInfo:
        if userMatchInfo.instId == instId:
            if userMatchInfo.state == UserMatchInfo.ST_SIGNIN:
                return ERR_ALREADY_SIGNIN
            return ERR_ALREADY_IN_MATCH
        else:
            ftlog.warn('match_remote.createUserMatchInfo gameId=', gameId,
                       'userId=', userId,
                       'contentItem=', contentItem,
                       'bigRoomId=', bigRoomId,
                       'instId=', instId,
                       'ctrlRoomId=', ctrlRoomId,
                       'recordInstId=', userMatchInfo.instId)

    userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId)
    userMatchInfo.ctrlRoomId = ctrlRoomId
    userMatchInfo.instId = instId
    if contentItem:
        userMatchInfo.feeItem = TYContentItem.decodeFromDict(contentItem)
    saveUserMatchInfo(userMatchInfo)
    return 0
コード例 #16
0
ファイル: rpccore.py プロジェクト: zhaozw/hall37
def _initializeRpcMehodss(gdata_):
    '''
    初始化RPC的命令入口, 获取各个游戏的实例的handler进行注册处理
    分游戏自动搜索自定义的RPC方法
    '''
    ftlog.debug('_initializeRpcMehodss begin')
    mpkgs = ['poker']
    for _, tygame in gdata.games().items():
        mpkgs.append(tygame._packageName)

    for mpkg in mpkgs:
        ftlog.debug('_initializeRpcMehodss package->', mpkg)
        # 注册RCP Server调用入口
        for rpcSevPkg in gdata.SRV_TYPE_PKG_NAME.values():
            pkg = mpkg + '.servers.' + rpcSevPkg + '.rpc'
            methods = decorator._loadDecoratorModuleMethods(pkg, 'markRpcCall')
            for method in methods:
                assert (method in _MARKED_METHOD)
                del _MARKED_METHOD[_MARKED_METHOD.index(method)]
                _registerRpcCall(method)
    for pkg in _SYS_RPC_PACKAGES:
        methods = decorator._loadDecoratorModuleMethods(pkg, 'markRpcCall')
        for method in methods:
            assert (method in _MARKED_METHOD)
            del _MARKED_METHOD[_MARKED_METHOD.index(method)]
            _registerRpcCall(method)

    if _MARKED_METHOD:
        for m in _MARKED_METHOD:
            ftlog.warn('this method marked as RCP, but not in rpc packages !!', getattr(m, decorator._METHOD_MARKE))
    cps = _runenv._rpc_methods.keys()
    cps.sort()
    for cp in cps:
        ftlog.debug('RPC CMD->', cp, _runenv._rpc_methods[cp])
    ftlog.debug('_initializeRpcMehodss end')
コード例 #17
0
    def quickStart(self, userId, tableId, continueBuyin, mixId=''):
        if ftlog.is_debug():
            ftlog.debug('DizhuTableRoomMix.quickStart', 'userId=', userId,
                        'roomId=', self.roomId, 'tableId=', tableId,
                        'continueBuyin=', continueBuyin, 'mixId=', mixId)
        if tableId:
            player = self.findPlayer(userId)
            if player:
                if player.table:
                    player.table.online(player.seat)
                    return player
                player.online = True

        # 开始游戏
        try:
            player = self.enterRoom(userId, continueBuyin, mixId)
            seat = self.startGame(userId, continueBuyin)
        except Exception, e:
            self.leaveRoom(userId, TYRoom.LEAVE_ROOM_REASON_LESS_MIN)
            ftlog.warn('DizhuTableRoomNormalBase.quickStart'
                       'userId=', userId, 'roomId=', self.roomId,
                       'continueBuyin=', continueBuyin, 'warn=', e.message)
            # 发送离开房间
            mp = MsgPack()
            mp.setCmd('room_leave')
            mp.setResult('reason', 0)
            mp.setResult('gameId', self.gameId)
            mp.setResult(
                'roomId',
                self.roomId)  # 处理结果返回给客户端时,部分游戏(例如德州、三顺)需要判断返回的roomId是否与本地一致
            mp.setResult('userId', userId)
            router.sendToUser(mp, userId)
            return
コード例 #18
0
    def _doStandUp(self, msg, userId, seatId, reason, clientId):
        '''
        玩家操作, 尝试离开当前的座位
        子类需要自行判定userId和seatId是否吻合
        '''
        if ftlog.is_debug():
            ftlog.debug(self._baseLogStr("<<", userId), "|seatId, locList:", seatId,
                        onlinedata.getOnlineLocList(userId), caller=self)

        seatIndex = seatId - 1
        player = self.players[seatIndex]
        result = {"isOK": True, "userId": userId, "gameId": self.gameId, "roomId": self.roomId, "tableId": self.tableId}
        if player.userId != userId:
            ftlog.warn('the seat userId not match userId=', userId, 'seat.userId=', player.userId, caller=self)
            return result

        player = self.players[seatId - 1]
        self._playerStandUp(player)
        self.onStandUpOk(userId, seatId)

        mpStandUpRes = self.createMsgPackRes("standup")
        mpStandUpRes.setResult("reason", reason)
        mpStandUpRes.setResult("seatId", seatIndex)
        mpStandUpRes.setResult("userId", userId)
        self.sendToAllTableUser(mpStandUpRes)

        if ftlog.is_debug():
            ftlog.debug(self._baseLogStr(">>", userId), "|locList:", onlinedata.getOnlineLocList(userId), caller=self)
        return result
コード例 #19
0
    def _getHttpStatus(self):
        contents = http7Mgetlivedata()

        if ftlog.is_debug():
            ftlog.debug('Sportlottery _getHttpStatus', 'toDict=',
                        self.toDict())

        if not contents or len(contents) == 0:
            ftlog.info('Sportlottery._getHttpStatus',
                       'http7Mgetlivedata contents empty', contents)
            return

        liveData = contents.get('LiveData')
        if not liveData or len(liveData) == 0:
            ftlog.info('Sportlottery._getHttpStatus',
                       'http7Mgetlivedata LiveData empty', liveData)
            return

        matchD = liveData.get(str(self.matchId))
        if matchD:
            self.score = matchD.get('Score', [0, 0])
            self.status = matchD.get('Status', 0)
            if self.status != 0:
                self.save()

            if self.status in RESULTS:
                if self.timer:
                    self.timer.cancel()
        else:
            ftlog.warn('Sportlottery._getHttpStatus',
                       'liveData havenot matchId=', self.matchId, 'obj=', self)
コード例 #20
0
ファイル: hall_yyb_gifts.py プロジェクト: luningcowboy/tuyoo
def _loadAllUserGiftStatus(userId):
    ret = {}
    datas = daobase.executeUserCmd(userId, 'hgetall', 'yyb.gifts:%s' % (userId))
    if datas:
        for i in xrange(len(datas) / 2):
            try:
                kindId = int(datas[i * 2])
                data = datas[i * 2 + 1]
                
                if ftlog.is_debug():
                    ftlog.debug('hall_yyb_gifts._loadAllUserGiftStatus',
                                'userId=', userId,
                                'kindId=', kindId,
                                'data=', data)
                    
                giftKind = findGiftKind(kindId)
                if not giftKind:
                    ftlog.warn('UnknownYYBGiftKind',
                               'userId=', userId,
                               'kindId=', kindId,
                               'data=', data)
                    continue
                status = _decodeUserGiftStatus(giftKind, data)
                ret[kindId] = status
            except:
                ftlog.warn('BadYYBGiftKindData',
                           'userId=', userId,
                           'kindId=', data[i * 2],
                           'data=', data[i * 2 + 1])
    return ret
コード例 #21
0
    def chooseFirstCall(self, table):
        tableInfo = table.matchTableInfo
        gameRound = table.gameRound
        seats = gameRound.seats
        for seat in seats:
            if seat.player.firstCallFalg == 1:
                if ftlog.is_debug():
                    ftlog.debug(
                        'GroupMatchFirstCallPolicyInturn.chooseFirstCall',
                        'roomId=', table.roomId, 'tableId=', table.tableId,
                        'stepType=', tableInfo['step']['type'], 'matchId=',
                        tableInfo['matchId'], 'currCardCount=',
                        tableInfo['seats'][0]['cardCount'], 'userIds=',
                        [s.player.userId for s in seats], 'callPlayerUserId=',
                        seat.player.userId)
                seat.player.firstCallFalg = 0
                return seat

        ftlog.warn(
            'GroupMatchFirstCallPolicyInturn.chooseFirstCall inturn calling warning',
            'roomId=', table.roomId, 'tableId=', table.tableId, 'matchId=',
            tableInfo['matchId'], 'userIds=', [s.player.userId for s in seats])

        index = random.randint(0, len(gameRound.seats) - 1)
        return gameRound.seats[index]
コード例 #22
0
    def doTableSmilies(self, gameId, msg):
        if ftlog.is_debug():
            ftlog.debug("<< |msg", msg)

        table = msg.getParam("table")
        userId = msg.getParam("userId")
        seatIndex = msg.getParam("seatId")
        toSeatIndex = msg.getParam("toSeatId")
        smilies = msg.getParam("smilies")

        player = table.players[seatIndex]
        if player.userId != userId:
            ftlog.warn(table._baseLogStr(
                "onTableChat player.userId != userId!", userId),
                       "|seatIndex, player:",
                       seatIndex,
                       player.userId,
                       caller=self)
            return False

        toPlayer = table.players[toSeatIndex]
        if toPlayer.userId == 0:
            ftlog.warn(table._baseLogStr("onTableChat toPlayer.userId == 0!"),
                       "|toSeatIndex:",
                       toSeatIndex,
                       caller=self)
            return False

        self.sendSmiliesResOk(table, seatIndex, toSeatIndex, 0, smilies, 0, 0,
                              '')
コード例 #23
0
 def _doNextCall(self, nctype):
     '''
     找到下一个叫地主的玩家, 发送开始叫地主的事件消息
     '''
     nsid = self._findNextCaller()
     if ftlog.is_debug():
         ftlog.debug('DizhuBaseGamePlay._doNextCall nctype=', nctype,
                     'nsid=', nsid)
     if nsid > 0:
         self.table.status.nowOper = nsid
         grab = 1 if nctype == 0 or nctype == 1 else 0
         # 发送下一个操作的命令
         self.sender.sendCallNextRes(nsid, grab)
         # 启动叫地主计时器
         seat = self.table.seats[nsid - 1]
         params = {
             'robot': seat.isRobot,
             'seatId': nsid,
             'userId': seat.userId
         }
         interval = random.randint(
             1, 3) if seat.isRobot else self.table.runConfig.optime
         self.table.tableTimer.setup(interval, 'CL_TIMEUP_CALL', params)
         # 牌局记录器处理
         self.table.gameRound.next(nsid - 1, grab, interval)
     else:
         ftlog.warn('_doNextCall can not found next caller...')
コード例 #24
0
ファイル: table_smilies_plugin.py プロジェクト: zhaozw/hall37
    def onTableChat(self, gameId, msg):
        if ftlog.is_debug():
            ftlog.debug("<< |msg", msg, caller=self)

        table = msg.getParam("table")
        userId = msg.getParam("userId")
        seatIndex = msg.getParam("seatId")
        isFace = msg.getParam("isFace")
        voiceIdx = msg.getParam("voiceIdx")
        chatMsg = msg.getParam("msg")

        player = table.players[seatIndex]
        if player.userId != userId:
            ftlog.warn(table._baseLogStr("onTableChat player.userId != userId!", userId),
                       "|seatIndex, player:", seatIndex, player.userId, caller=self)
            return False

        if isFace == 0:
            # 纯文本内容
            chatMsg = keywords.replace(chatMsg[:80])  # 80个字符长度限制
            if difangConf.isEnableLogChatMsg(gameId):
                hallchatlog.reportChatLog(userId, chatMsg, self.gameId, table.roomId, table.tableId, seatIndex,
                                          userName=player.name, roomName=table.room.roomConf.get('name'))
                ftlog.info('onTableChat |gameId, tableId, userId, name, chatMsg:',
                           gameId, table.tableId, player.userId, player.name, chatMsg, caller=self)

        self.sendTableChatResToAll(table, player, isFace, voiceIdx, chatMsg)
コード例 #25
0
ファイル: match.py プロジェクト: luningcowboy/tuyoo
    def doUserRevive(self, player, isRevive):
        ''' 如果是第一个用户reset '''
        if player.userId not in self._waitRevivePlayersMap:
            ftlog.warn('MatchInstance.revive doUserRevive matchId=',
                       self.matchId, 'instd=', self.instId, 'userId=',
                       player.userId, 'isRevive=', isRevive, 'revivePlayer=',
                       self._waitRevivePlayersMap.keys())
            return False

        # 删除等待用户
        del self._waitRevivePlayersMap[player.userId]

        # 正好是当前timer处理用户, 需要重置
        if self._reviveProcesser._currentUserId == player.userId:
            self._resetReviveTimer()

        # 复活或者出局
        if isRevive:
            player.score = player.stage.stageConf.getRankLine(
                player.mixId).getMinScoreByRank(
                    player.stage.stageConf.reviveCondition.get('rank'))
            player.isFromRevive = True
            player.rank = player.stage.calcRank(player.score, player.mixId)
            self._winlosePlayerList.append(player)
        else:
            self._outPlayer(player)

        ftlog.info('MatchInstance.revive doUserRevive matchId=', self.matchId,
                   'instd=', self.instId, 'userId=', player.userId,
                   'isRevive=', isRevive, 'revivePlayer=',
                   len(self._waitRevivePlayersMap))
        return True
コード例 #26
0
def moveTo(gameId, userId, bigRoomId, instId, ctrlRoomId, toInstId):
    if ftlog.is_debug():
        ftlog.debug("match_remote.moveTo gameId=", gameId, "userId=", userId,
                    "bigRoomId=", bigRoomId, "instId=", instId, "ctrlRoomId=",
                    ctrlRoomId, "toInstId=", toInstId)
    try:
        userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
        if userMatchInfo:
            if userMatchInfo.instId == instId:
                userMatchInfo.instId = toInstId
                userMatchInfo.state = UserMatchInfo.ST_SIGNIN
                saveUserMatchInfo(userMatchInfo)
                ftlog.debug("match_remote.moveTo ok gameId=", gameId,
                            "userId=", userId, "bigRoomId=", bigRoomId,
                            "instId=", instId, "ctrlRoomId=", ctrlRoomId,
                            "toInstId=", toInstId)
                return True
            else:
                ftlog.warn("match_remote.moveTo fail gameId=", gameId,
                           "userId=", userId, "bigRoomId=", bigRoomId,
                           "instId=", instId, "ctrlRoomId=", ctrlRoomId,
                           "toInstId=", toInstId, "recordInstId=",
                           userMatchInfo.instId)
                return False
    except:
        ftlog.error("match_remote.moveTo exception gameId=", gameId, "userId=",
                    userId, "bigRoomId=", bigRoomId, "instId=", instId,
                    "ctrlRoomId=", ctrlRoomId, "toInstId=", toInstId)
        return False
コード例 #27
0
ファイル: configure.py プロジェクト: isoundy000/learn_python
def stringIdToNumber(datakey, stringid):
    '''字符串Id转数字'''
    if stringid == 'UNKNOWN':
        return UNKNOW_ID
    if isinstance(stringid, int):
        return stringid
    numDict = _get(datakey, {})
    if not numDict:
        ftlog.warn('configure.stringIdToNumber', datakey, 'NotConfig')
        return UNKNOW_ID
    num = numDict.get(stringid, UNKNOW_ID)
    if num == UNKNOW_ID:
        if stringid.find('robot') >= 0:  # 机器人的clientid忽略
            return UNKNOW_ID
    if num <= 0:
        ftlog.warn('stringIdToNumber Error %s %s "%s"' %
                   (datakey, type(stringid), stringid))
        return UNKNOW_ID
    """
    try:
        assert(num > 0), 'stringIdToNumber Error %s %s "%s"' %(datakey, type(stringid), stringid)
    except:
        ftlog.error()
    """
    return num
コード例 #28
0
def addUserScore(userId, rankId, issueNum, score=0):

    issueNum = str(issueNum)

    userData = dizhu_score_ranking.loadUserData(userId, rankId, issueNum)
    if userData:
        ftlog.info('hotfix.addUserScore', 'userId=', userId, 'rankId=', rankId,
                   'issueNum=', issueNum, 'score=', score, 'userData=',
                   userData.toDict())

        try:
            score = int(score)
        except ValueError, e:
            ftlog.warn('hotfix.addUserScore.valueError', 'userId=', userId,
                       'rankId=', rankId, 'issueNum=', issueNum, 'err=', e)
            return

        userData.score += score
        userData.score = max(0, userData.score)

        ret = dizhu_score_ranking.saveUserData(userData)
        rankingDefine = dizhu_score_ranking.getConf().findRankingDefine(rankId)
        rankLimit = rankingDefine.rankLimit if rankingDefine else 3000
        dizhu_score_ranking.insertRanklist(rankId, issueNum, userData.userId,
                                           userData.score, rankLimit)

        ftlog.info('hotfix.addUserScore.over', 'userId=', userId, 'rankId=',
                   rankId, 'issueNum=', issueNum, 'score=', score, 'userData=',
                   userData.toDict())
コード例 #29
0
    def _getHttpOdds(self):
        if ftlog.is_debug():
            ftlog.debug('SportOdds', '_getHttpOdds=',
                        self.sportlottery.toDict())

        contents = http7Mgethdaoddsinfo(self.sportlottery.matchId)
        if not contents or len(contents) == 0:
            return

        if contents.get('GameId') != str(self.sportlottery.matchId):
            ftlog.warn('SportOdds httpOdds GameId not match', 'matchId=',
                       self.sportlottery.matchId, 'GameId=',
                       contents.get('GameId'))
            return

        Datas = contents.get('Datas')
        if not Datas or len(Datas) == 0:
            ftlog.warn('SportOdds httpOdds Datas empty', 'Datas=', Datas,
                       'contents=', contents)
            return

        tag = 0
        for data in Datas:
            if data.get('Cid') in self.ODDS:
                odds = data.get('Data', [])
                if odds and len(odds) >= 3:
                    self.sportlottery.odds = odds[:3]
                    self.sportlottery.save()
                    if self.timer:
                        self.timer.cancel()

                    tag = 1
                    break
        if self.sportlottery and tag == 1:
            self.sportlottery.clearSportOdds()
コード例 #30
0
    def _doReqDisbind(self, player, clientId):
        if self.preDisbind:
            ftlog.warn('DizhuFriendTable._doReqDisbind', 'tableId=',
                       self.tableId, 'ftId=', self.ftId, 'seatId=',
                       player.seatId, 'userId=', player.userId, 'err=',
                       'Already request')
            return

        if not self.ftTable:
            ftlog.warn('DizhuFriendTable._doReqDisbind', 'tableId=',
                       self.tableId, 'ftId=', self.ftId, 'seatId=',
                       player.seatId, 'userId=', player.userId, 'err=',
                       'ftTableIsNone')
            return

        ftlog.info('DizhuFriendTable._doReqDisbind', 'tableId=', self.tableId,
                   'ftId=', self.ftId, 'seatId=', player.seatId, 'userId=',
                   player.userId)

        if len(self.results
               ) == 0 and self.status.state <= DizhuState.TABLE_STATE_IDEL:
            if player.userId == self.ftTable.userId:
                returnFee = False if self._waitContinue else True
                self._doDisbind(returnFee)
            else:
                self._doStandupAndRoomLeave(player, clientId)
            return

        self.preDisbind = True
        self.preDisbindSeatId = player.seatId
        self.preDisbindSeatState[player.seatIndex] = 1
        optime = self.runConfig.optimeDisbind
        self.preDisbindExpires = pktimestamp.getCurrentTimestamp() + optime
        self.preDisbindTimer.setup(optime, 'FT_DISBIND_SURE_TIMEOUT', {})
        self.gamePlay.sender.sendReqDisbindRes(player, optime)
コード例 #31
0
def httpTodayCallback(httpObj):
    if httpObj:
        ftlog.info('hallsportlottery.httpTodayCallback', 'httpObj=', httpObj,
                   'httpContents=', httpObj.httpContents)

        global _sportlotteryMap

        for match in httpObj.httpContents:
            timestamp = match['timestamp']
            if time.time() >= timestamp or time.time() + 7200 >= timestamp:
                continue

            date = datetime.datetime.fromtimestamp(timestamp).strftime(
                '%Y-%m-%d')
            daobase.executeMixCmd('hset', leagueDaykey % date,
                                  match['matchId'], strutil.dumps(match))

            if int(match['matchId']) in _sportlotteryMap:
                continue

            try:
                sportObj = Sportlottery()
                sportObj.fromDict(match)
                sportObj.start()
                _sportlotteryMap[sportObj.matchId] = sportObj

                if ftlog.is_debug():
                    ftlog.debug('httpTodayCallback', 'sportObj=', sportObj)
            except:
                ftlog.warn('hallsportlottery.httpTodayCallback', 'match=',
                           match)

        del httpObj
コード例 #32
0
ファイル: treasure_chest.py プロジェクト: luningcowboy/tuyoo
    def helpShortenTreasureChest(cls, userId, rewardId, helpUserId):
        ''' 好友助力缩短时间 '''
        # 返回剩余秒数及其状态
        userTreasureChest = UserTreasureChest(helpUserId).loadTreasureChest()
        for chest in userTreasureChest.treasureChestList:
            if chest.rewardId == rewardId:
                if userId in chest.helpUserIds or helpUserId == userId:
                    ftlog.warn(
                        'TreasureChestHelper.helpShortenTreasureChest HAS_HELP userId=',
                        userId, 'rewardId=', rewardId, 'helpUserId=',
                        helpUserId, 'helpCount=', len(chest.helpUserIds))
                    return False, None, None

                chest.openTimestamp -= _treasureChestTotalConf.treasureChest.helpShortenSeconds
                chest.helpUserIds.append(userId)
                if chest.openTimestamp - pktimestamp.getCurrentTimestamp(
                ) <= 0:
                    chest.state = TreasureChest.TREASURE_CHEST_STATE_WAIT_OPEN
                userTreasureChest.saveTreasureChest()
                return True, chest.state, max(
                    0, chest.openTimestamp - pktimestamp.getCurrentTimestamp())

        ftlog.warn(
            'TreasureChestHelper.helpShortenTreasureChest NOT EXISTS helpUserId=',
            helpUserId, 'rewardId=', rewardId)
        return False, None, None
コード例 #33
0
ファイル: big_match_room.py プロジェクト: zhaozw/hall37
    def doQuickStart(self, msg):
        assert self.roomId == msg.getParam("roomId")

        userId = msg.getParam("userId")
        shadowRoomId = msg.getParam("shadowRoomId")
        tableId = msg.getParam("tableId")
        clientId = msg.getParam("clientId")
        ftlog.info(getMethodName(), "<<",
                   "|userId, clientId, roomId, shadowRoomId, tableId:", userId,
                   clientId, self.roomId, shadowRoomId, tableId)

        if tableId == self.roomId * 10000:
            isOk = True  # 玩家在队列里时断线重连
            player = self.match.findPlayer(userId)
            if player is None or not player.group:
                #             if player is None or not player.group:
                ftlog.warn(getMethodName(), '|room=', self.roomId, 'userId=',
                           userId, 'not found player')
                onlinedata.removeOnlineLoc(userId, self.roomId, tableId)
                isOk = False
        else:
            isOk = False

        if isOk:
            reason = self.ENTER_ROOM_REASON_OK
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId,
                                   self.match.tableId)
            # 如果用户已经被分组则发送等待信息
            if player.group:
                self.match.playerNotifier.notifyMatchWait(player, player.group)
        else:
            reason = self.ENTER_ROOM_REASON_INNER_ERROR
            info = u'在线状态错误或其他系统内部错误'
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId,
                                   0, info)
コード例 #34
0
def startSportlottery():
    global _sportlotteryMap
    now = datetime.datetime.now()
    for n in range(DAYS + 1):
        _afterday = (now + datetime.timedelta(days=n)).strftime('%Y-%m-%d')
        datas = daobase.executeMixCmd('hgetall', leagueDaykey % _afterday)
        if datas:
            for i in xrange(len(datas) / 2):
                matchId = datas[i * 2]

                if int(matchId) in _sportlotteryMap:
                    continue

                jstr = datas[i * 2 + 1]
                try:
                    d = strutil.loads(jstr)
                    sportObj = Sportlottery()
                    sportObj.fromDict(d)
                    sportObj.start()
                    _sportlotteryMap[sportObj.matchId] = sportObj

                    if ftlog.is_debug():
                        ftlog.debug('startSportlottery', 'sportObj=', sportObj)
                except:
                    ftlog.warn('hallsportlottery.startSportlottery',
                               'matchId=', matchId)

        if ftlog.is_debug():
            ftlog.debug('startSportlottery date',
                        'n=', n, '_sportlotteryMap key=',
                        _sportlotteryMap.keys(), 'datas=', datas)
コード例 #35
0
ファイル: big_match_room.py プロジェクト: zhaozw/hall37
    def doQuickStart(self, msg):
        assert self.roomId == msg.getParam("roomId")

        userId = msg.getParam("userId")
        shadowRoomId = msg.getParam("shadowRoomId")
        tableId = msg.getParam("tableId")
        clientId = msg.getParam("clientId")
        ftlog.info(getMethodName(), "<<", "|userId, clientId, roomId, shadowRoomId, tableId:", userId, clientId,
                   self.roomId, shadowRoomId, tableId)

        if tableId == self.roomId * 10000:
            isOk = True  # 玩家在队列里时断线重连
            player = self.match.findPlayer(userId)
            if player is None or not player.group:
                #             if player is None or not player.group:
                ftlog.warn(getMethodName(), '|room=', self.roomId,
                           'userId=', userId, 'not found player')
                onlinedata.removeOnlineLoc(userId, self.roomId, tableId)
                isOk = False
        else:
            isOk = False

        if isOk:
            reason = self.ENTER_ROOM_REASON_OK
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, self.match.tableId)
            # 如果用户已经被分组则发送等待信息
            if player.group:
                self.match.playerNotifier.notifyMatchWait(player, player.group)
        else:
            reason = self.ENTER_ROOM_REASON_INNER_ERROR
            info = u'在线状态错误或其他系统内部错误'
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, info)
コード例 #36
0
ファイル: configure.py プロジェクト: zhaozw/hall37
def getVcTemplate(moduleKey, clientId, gameId=None):
    """
    http://192.168.10.93:8090/pages/viewpage.action?pageId=1868148
    """
    if isinstance(clientId, int):
        strClientId = numberToClientId(clientId)
        numClientId = clientIdToNumber(strClientId)
    else:
        numClientId = clientIdToNumber(clientId)
        strClientId = numberToClientId(numClientId)

    assert (numClientId > 0), 'the clientId int value error, input=' + str(clientId) + ' convert=' + str(
        numClientId) + ' ' + str(strClientId)
    assert (strClientId != ''), 'the clientId str value error, input=' + str(clientId) + ' convert=' + str(
        numClientId) + ' ' + str(strClientId)

    if not gameId:
        gameId = strutil.getGameIdFromHallClientId(strClientId)
        assert (gameId > 0), 'the gameId error, input=' + str(strClientId) + ' convert=' + str(gameId) + ' ' + str(
            numClientId) + ' ' + str(strClientId)

    xkey = 'game:' + str(gameId) + ':' + moduleKey + ':' + CLIENT_ID_MATCHER
    datas = _get(xkey, {})
    if not '_cache' in datas:
        strutil.replaceObjRefValue(datas)
        datas['_cache'] = {}

    _cache = datas['_cache']
    tname = _cache.get(numClientId, None)
    if tname == None:
        # 先判定1:1真实映射
        actual = datas.get('actual', {})
        tname = actual.get(strClientId, None)
        if tname == None:
            tname = actual.get(str(numClientId), None)

        # 第二优先级判定主次渠道,主次渠道可覆盖大部分的批量配置需求,比正则表达式配置难度低
        if tname == None:
            channel = strutil.getChannelFromHallClientId(clientId)
            tname = actual.get(channel, None)

        # 再判定正则表达式映射
        if tname == None:
            for vm in datas.get('virtual', []):
                if strutil.regMatch(vm[0], strClientId):
                    tname = vm[1]
                    break
        # 最后取缺省值
        if tname == None:
            clientSys, _, _ = strutil.parseClientId(strClientId)
            tname = datas.get('default_' + str(clientSys).lower(), None)
        # 最后取缺省值
        if tname == None:
            tname = datas.get('default', None)
        if tname == None:
            ftlog.warn('the clientId can not find template name ' + str(moduleKey) + ' ' + str(
                numClientId) + ' ' + strClientId)
        _cache[numClientId] = tname
    return tname
コード例 #37
0
ファイル: game_play.py プロジェクト: zhaozw/hall37
    def doActionGameEnd(self):
        if ftlog.is_debug():
            ftlog.info("doActionGameEnd <<", self.getBasicAttrsLog(), caller=self)
        if self.__state != self.GAME_PLAY_STATE_FINAL:
            ftlog.warn("state error!", self.getBasicAttrsLog(), caller=self)
            return

        self.transitToStateWait()
コード例 #38
0
ファイル: game_play.py プロジェクト: zhaozw/hall37
 def doActionCheckStartGame(self):
     '''检查游戏人数是否达到开局要求
     Note: 先补足筹码,然后踢掉筹码不足的玩家
     '''
     ftlog.debug("<<", self.getBasicAttrsLog(), caller=self)
     if self.__state != self.GAME_PLAY_STATE_WAIT:
         ftlog.warn("doActionCheckStartGame state error!", self.getBasicAttrsLog())
         return False
コード例 #39
0
ファイル: vip_handler.py プロジェクト: zhaozw/hall37
 def doAssistanceGet(self, gameId, userId):
     try:
         _consumeCount, finalCount, sendChip = hallvip.userVipSystem.gainAssistance(gameId, userId)
         if sendChip > 0:
             datachangenotify.sendDataChangeNotify(gameId, userId, 'udata')
         todotask = TodoTaskGoldRain(VipHelper.buildGotAssistanceDesc(finalCount, sendChip))
         TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
     except TYAssistanceChipTooMuchException, e:
         ftlog.warn('ERROR, doAssistanceGet', gameId, userId, e.chip, e.upperChipLimit, e.errorCode, e.message)
コード例 #40
0
ファイル: cache.py プロジェクト: zhaozw/hall37
def cloneData(data):
    '''
    使用JSON的loads和dump克隆一个数据对象
    '''
    try:
        return json.loads(json.dumps(data))
    except:
        ftlog.warn('Can not use json copy !! data=' + repr(data))
        return deepcopy(data)
コード例 #41
0
ファイル: group_match_remote.py プロジェクト: zhaozw/hall37
def numberToClientId(numberId):
    cid = ''
    try:
        cid = pokerconf.numberToClientId(numberId)
    except:
        pass
    if not cid:
        ftlog.warn('group_match_remote.numberToClientId failed:', numberId)
    return cid
コード例 #42
0
ファイル: group_match_remote.py プロジェクト: zhaozw/hall37
def clientIdToNumber(clientId):
    cid = 0
    try:
        cid = pokerconf.clientIdToNumber(clientId)
    except:
        pass
    if cid == 0:
        ftlog.warn('group_match_remote.clientIdToNumber failed:', clientId)
    return cid
コード例 #43
0
def addUserItem(userId, gameId, kindId, count, eventId, userBag):
    timestamp = pktimestamp.getCurrentTimestamp()
    itemKind = hallitem.itemSystem.findItemKind(kindId)
    if not itemKind:
        ftlog.warn('TYOldItemTransfer.addUserItem gameId=', gameId, 'userId=', userId, 'itemKindId=', kindId, 'err=',
                   'UnknownItemKindId')
        raise TYItemException(-1, '未知的道具类型')
    item = userBag.addItemUnitsByKind(gameId, itemKind, count, timestamp, 0, eventId, 0)
    return _encodeItem(kindId, item[0], timestamp)
コード例 #44
0
ファイル: quick_start.py プロジェクト: zhaozw/hall37
 def _onEnterCreateRoomFailed(cls, checkResult, userId, gameId, clientId, roomId=0):
     '''进入创建房间失败回调函数'''
     ftlog.warn("|userId, reason, roomId:", userId, checkResult, roomId, caller=cls)
     mo = MsgPack()
     mo.setCmd('quick_start')
     mo.setResult('gameId', gameId)
     mo.setResult('userId', userId)
     mo.setResult('reason', checkResult)
     router.sendToUser(mo, userId)
コード例 #45
0
ファイル: performance.py プロジェクト: zhaozw/hall37
def watchSlowCall(fun, funArgl, funArgd, slowTime, slowFun):
    t = time()
    r = fun(*funArgl, **funArgd)
    if slowTime == None:
        slowTime = SLOW_CALL_TIME
    t = time() - t
    if t > SLOW_CALL_TIME:
        ftlog.warn('SLOW CALL, TIME=', slowTime, 'USETIME=%0.4f' % (t), slowFun(fun, funArgl, funArgd))
    return r
コード例 #46
0
ファイル: custom_room_plugin.py プロジェクト: zhaozw/hall37
    def onRoomCreateCustomTable(self, gameId, msg):
        '''在GR处理自建桌逻辑
        '''
        if ftlog.is_debug():
            ftlog.debug("<< |msg", msg, caller=self)

        userId = msg.getParam("userId")
        selectedRoomOptions = msg.getParam("selectedRoomOptions")
        if not selectedRoomOptions:
            return
        customConfVer = msg.getParam("customConfVer")
        if customConfVer != difangConf.getCustomRoomConf(gameId, 'ver'):
            ftlog.warn("onRoomCreateCustomTable confVer error! |msg:", msg, caller=self)
            return
        gameRoundN = selectedRoomOptions.get("gameRoundN")
        if not gameRoundN:
            return
        roomId = msg.getParam("roomId")
        room = gdata.rooms()[roomId]
        clientId = msg.getParam("clientId")

        needRoomCardN = difangConf.getCustomRoomConf(gameId, 'roomCardNCost').get(str(gameRoundN), -1)
        if needRoomCardN == -1:
            tips = difangConf.getCustomRoomConf(difangConf.GAME_ID, 'err_tips')
            tip = tips[self.CREATE_CUSTOM_TABLE_ERR_NO_NOT_ALLOW]
            TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(tip, True))
            ftlog.warn("onRoomCreateCustomTable get needRoomCardN error! |msg:", msg, caller=self)
            self.sendGameCreateCustomTableRes(0, userId)
            return

        if ftlog.is_debug():
            ftlog.debug("|userId, gameId, customConfVer, gameRoundN, needRoomCardN:",
                        userId, gameId, customConfVer, gameRoundN, needRoomCardN, caller=self)

        if needRoomCardN > 0 and not self.isCardEnough(gameId, userId, needRoomCardN, clientId):
            tips = difangConf.getCustomRoomConf(difangConf.GAME_ID, 'err_tips')
            tip = tips[self.CREATE_CUSTOM_TABLE_ERR_NO_NOT_ENOUGH]
            TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(tip, True))
            self.sendGameCreateCustomTableRes(0, userId)
            return

        tableId = room.getIdleTableId()
        if not tableId:
            ftlog.error("there are no idle tables!", "|userId, roomId:", userId, room.roomId)
            return

        ftId = self.assignFriendTableId(gameId, tableId)

        ftlog.info("onRoomCreateCustomTable |userId, tableId, ftId:", userId, tableId, ftId, caller=self)
        self.sendGameCreateCustomTableRes(ftId, userId)
        gamedata.setGameAttr(userId, gameId, "selectedRoomOptions", json.dumps(selectedRoomOptions))
        gamedata.setGameAttr(userId, gameId, "customConfVer", customConfVer)

        shadowRoomId = tableId / 10000
        room.querySitReq(userId, shadowRoomId, tableId, clientId,
                         extParams={"selectedRoomOptions": selectedRoomOptions, "ftId": ftId})
コード例 #47
0
ファイル: dbmysql.py プロジェクト: zhaozw/hall37
def _get_table_data(datas, row, col):
    try:
        if datas and len(datas) > 0:
            dstr = datas[row][col]
            if dstr[0] == '{' and dstr[-1] == '}':
                return dstr
        ftlog.warn('WARN, the mysql data error !!', datas)
    except:
        ftlog.warn('WARN, the mysql data not found !!', datas)
    return None
コード例 #48
0
ファイル: queue_room.py プロジェクト: zhaozw/hall37
 def _popOneUser(self):
     '''从等待玩家队列中pop一个玩家,pop过程中无异步操作'''
     for userId in self.users.keys():
         if self._isValidUser(userId):
             del self.users[userId]
             self.sittingUsers.add(userId)
             return userId
         else:
             ftlog.warn("_popOneUser user %d is not valid:" % userId)
     return None
コード例 #49
0
ファイル: task.py プロジェクト: zhaozw/hall37
 def _unregisterEvents(self):
     for eventType, gameIds in self._interestEventMap.iteritems():
         for gameId in gameIds:
             game = gdata.games().get(gameId)
             if game:
                 game.getEventBus().unsubscribe(eventType, self._handleEvent)
             else:
                 ftlog.warn('TYTaskSystemImpl._registerEvents gameId=', gameId,
                            'err=', 'Not find game')
     self._interestEventMap = {}
コード例 #50
0
ファイル: protocol.py プロジェクト: zhaozw/hall37
    def lineReceived(self, data):
        if performance.PERFORMANCE_NET:
            data = performance.linkMsgTime('LR', data)
        ftlog.debug('S2AProtocol->lineReceived', FTTasklet.concurrent_task_count, time(), data)
        src, dst, query_id, userheader1, userheader2, msg = agentmsg.unpack(data)
        if ide_debug():
            ide_print_pack("S2AP Recv [%5s]" % src.split("-")[0], json.loads(msg))
        if src is None or dst is None:
            ftlog.info("ERROR, recive a error format message")
            return

        if self.peer_id == 0:
            self.peer_id = src
            ftcon.serverid_protocol_map[self.peer_id] = self
            ftlog.info('receive register, agentid=', self.peer_id)
            return

        _countProtocolPack(1, self)

        # send过来的数据
        if query_id == '':
            self._runTasklet(data=msg, src=src, dst=dst, userheader1=userheader1, userheader2=userheader2,
                             time_recv=time())
        else:
            querysrc, _ = query_id.split('.')
            server_id = ftcon.global_config["server_id"]
            # query本服务的请求
            if querysrc != server_id:
                self._runTasklet(data=msg, src=src, dst=dst, query_id=query_id, userheader1=userheader1,
                                 userheader2=userheader2, time_recv=time())
            # response回来的请求
            else:
                if userheader1 == 'RQ':  # 本进程内, 异步查询本进程的其他消息接口
                    self._runTasklet(data=msg, src=src, dst=dst, query_id=query_id, userheader1=userheader1,
                                     userheader2=userheader2, time_recv=time())
                else:
                    d, c, t = None, None, 0
                    #                     ftlog.debug('lineReceived', query_id, id(_LIVE_MESSAGES), id(self))
                    if query_id in _LIVE_MESSAGES:
                        d, c, t = _LIVE_MESSAGES[query_id]
                        del _LIVE_MESSAGES[query_id]
                    else:
                        if query_id in _FAILED_MESSAGES:
                            del _FAILED_MESSAGES[query_id]
                            ftlog.warn('QUERY TOO SLOW !!', query_id, msg)
                            if len(_FAILED_MESSAGES) > 100:
                                _FAILED_MESSAGES.clear()
                        else:
                            ftlog.warn('NOT KNOW of query_id->', query_id, msg)
                    if d and c:
                        try:
                            c.cancel()
                            d.callback((msg, t, time()))
                        except:
                            ftlog.error(msg)
コード例 #51
0
ファイル: custom_room_plugin.py プロジェクト: zhaozw/hall37
    def isCardEnough(self, gameId, userId, needRoomCardN, clientId):
        count = self.queryFangKaCount(gameId, userId, clientId)
        if ftlog.is_debug():
            ftlog.debug("<< |count, userId, needRoomCard, clientId:",
                        count, userId, needRoomCardN, clientId, caller=self)
        if count >= needRoomCardN:
            return True

        ftlog.warn("not enough room cards! |userId, count, needRoomCardN, clientId:",
                   userId, count, needRoomCardN, clientId, caller=self)
        return False
コード例 #52
0
ファイル: runcmd.py プロジェクト: zhaozw/hall37
def filterErrorMessage(msg):
    from poker.util import webpage

    gameId, clientId, userId, action = msg.getParams('gameId', 'clientId', 'userId', 'action')
    cmd = msg.getCmd()
    bugclientId = 'IOS_3.82_tuyoo.appStore,weixinPay,alipay.0-hall6.appStore.tuyoo2016'
    url = 'http://open.touch4.me/open/v3/user/setForbidden'

    if (gameId is None and cmd == 'game' and action == 'leave' and clientId == bugclientId):
        datas = {'lock_users': [userId]}
        ftlog.warn('kill cracker, msg:', msg)
        webpage.webgetJson(url, datas, None, 10)
コード例 #53
0
ファイル: hallroulette.py プロジェクト: zhaozw/hall37
def getWeightConfTemplate(userId, gameId, clientId):
    '''
        获取包含权重的配置信息
    '''
    clientConf = getTemeplateName()

    if not clientConf:
        ftlog.warn('doRoulette->', gameId, clientId, userId, 'config is None !')
        return {}
    rouletteTemplateMap = getRouletteTemplateMap()
    templateConf = rouletteTemplateMap.get(clientConf, {})
    return templateConf
コード例 #54
0
ファイル: dtg_room.py プロジェクト: zhaozw/hall37
    def doQuickStart(self, msg):
        assert self.roomId == msg.getParam("roomId")

        userId = msg.getParam("userId")
        shadowRoomId = msg.getParam("shadowRoomId")
        tableId = msg.getParam("tableId")
        clientId = msg.getParam("clientId")
        ftlog.hinfo("doQuickStart <<", "|userId, clientId, roomId, shadowRoomId, tableId:", userId, clientId,
                    self.roomId, shadowRoomId, tableId)

        # msg = TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_QUICK_START', params=TYPluginUtils.mkdict(
        #     userId=userId, roomId=self.roomId), result={}), self.gameId)
        #
        # if msg.getResult("reason") != None:
        #     info = u'玩家需要验证'
        #     self.sendQuickStartRes(self.gameId, userId, msg.getResult("reason"), self.bigRoomId, 0, info)
        #     return

        if tableId == 0:
            isOk, reason = self.doEnter(userId)
        elif tableId == self.roomId * 10000:
            if userId in self._roomUsers:
                isOk = True  # 玩家在队列里时断线重连
                reason = TYRoom.ENTER_ROOM_REASON_OK
            else:  # 服务器重启造成玩家已经不在房间对象里了
                onlinedata.removeOnlineLoc(userId, self.roomId, tableId)
                isOk = False
                reason = TYRoom.ENTER_ROOM_REASON_CONFLICT
        else:  # 防御性代码,处理快速开始online错乱
            onlineSeat = onlinedata.getOnlineLocSeatId(userId, shadowRoomId, tableId)
            if onlineSeat == 0:  # 断线重连过程中玩家因为超时、金币不足或比赛淘汰等原因已被踢出房间
                isOk = False
                reason = TYRoom.ENTER_ROOM_REASON_CONFLICT
                ftlog.warn("doQuickStart conflict!", "|userId, onlineLocList:", userId,
                           onlinedata.getOnlineLocList(userId),
                           "|shadowRoomId, tableId:", shadowRoomId, tableId)
            else:
                ftlog.error("doQuickStart conflict!", "|onlineSeat:", onlineSeat)
                if onlineSeat == gdata.roomIdDefineMap()[shadowRoomId].configure['tableConf']['maxSeatN'] + 1:
                    # 牌桌里旁观的玩家断线重连,请求转给GT
                    self.sendTableCallObserveReq(userId, shadowRoomId, tableId, clientId)
                elif onlineSeat > 0:
                    # 牌桌里坐着的玩家断线重连,请求转给GT
                    self.querySitReq(userId, shadowRoomId, tableId, clientId)
                return

        if isOk:
            self._onQuickStartOk(userId)
        elif reason == TYRoom.ENTER_ROOM_REASON_CONFLICT:
            info = u'玩家已经在游戏中,状态冲突'
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, info)
        else:
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, '')
コード例 #55
0
ファイル: table_mixin.py プロジェクト: zhaozw/hall37
 def clearInvalidObservers(self):
     '''一段防御性代码,防止本桌上一局的旁观者未被及时清理,下一局开局时换到了别的桌子,但收到本桌的协议
     '''
     invalidObservers = []
     for userId in self.observers:
         onlineSeatId = onlinedata.getOnlineLocSeatId(userId, self.roomId, self.tableId)
         if onlineSeatId == 0:  # Note: 断线的旁观玩家不做清理,table._doClearPlayers会处理
             ftlog.warn(self._baseLogStr('invalid observer found', userId),
                        '|locList:', onlinedata.getOnlineLocList(userId), caller=self)
             invalidObservers.append(userId)
     for userId in invalidObservers:
         del self.observers[userId]
コード例 #56
0
ファイル: rpccore.py プロジェクト: zhaozw/hall37
def getRpcDstRoomServerId(roomId, canChangeRoomId):
    allrooms = gdata.roomIdDefineMap()
    if roomId in allrooms:
        roomDef = allrooms[roomId]
        return roomDef.serverId
    elif canChangeRoomId:  # this roomId may be big roomId
        bigrooms = gdata.bigRoomidsMap()
        if roomId in bigrooms:
            ctrlroomIds = bigrooms[roomId]
            ctrlRoomId = ctrlroomIds[0]  # ctrlRoom0 做为 ctrlRooms 的调度器
            roomDef = allrooms[ctrlRoomId]
            return roomDef.serverId
    ftlog.warn('getRpcDstRoomServerId roomId error !!', roomId, canChangeRoomId)
コード例 #57
0
ファイル: tasklet.py プロジェクト: zhaozw/hall37
 def _checkBusy(self):
     if FTTasklet.concurrent_task_count >= FTTasklet.MAX_CONCURRENT:
         # 只在空闲向繁忙转换时,打印一次
         if FTTasklet.BUSY_FLAG == 0:
             ftlog.error("_checkBusy: too much task(%d)!" % FTTasklet.concurrent_task_count)
         FTTasklet.BUSY_FLAG = 1
         ftlog.warn("_checkBusy: too much task(%d)!" % FTTasklet.concurrent_task_count)
     else:
         # 只在繁忙向空闲转换时,打印一次
         if FTTasklet.BUSY_FLAG == 1:
             ftlog.info("_checkBusy: task count recover(%d)!" % FTTasklet.concurrent_task_count)
         FTTasklet.BUSY_FLAG = 0
     return FTTasklet.BUSY_FLAG
コード例 #58
0
ファイル: hallroulette.py プロジェクト: zhaozw/hall37
def doWeightListForItem(userId, gameId, clientId, itemList):
    if not itemList:
        ftlog.warn('doRoulette->', gameId, clientId, userId, 'itemList is None !')
        return None
    items = []
    probability = []
    allWeight = 0
    for _key, value in enumerate(itemList):
        items.append(value.get('rouletteId'))
        probability.append(value.get('weight'))
        allWeight += value.get('weight')
    ret, _x = random_pick(items, probability, allWeight)
    return ret