Ejemplo n.º 1
0
 def doGetGameInfoForSdk(self):
     paramsDict = runhttp.getDict()
     ftlog.debug("doGetGameInfoForSdk:", paramsDict)
     uidlist = paramsDict.get('uids', '').split(',')
     for_winchip = paramsDict.get('for_winchip', 0)
     for_level_info = paramsDict.get('for_level_info', 0)
     for_online_info = paramsDict.get('for_online_info', 1)
     gameIds = paramsDict.get('gameids', '').split(',')
     for x in xrange(len(gameIds)):
         gameIds[x] = strutil.parseInts(gameIds[x])
     for x in xrange(len(uidlist)):
         uidlist[x] = strutil.parseInts(uidlist[x])
     return self._doGetGameInfoForSdk(uidlist, gameIds, for_level_info, for_winchip, for_online_info)
Ejemplo n.º 2
0
 def doGetGameInfoForSdk(self):
     paramsDict = runhttp.getDict()
     ftlog.debug("doGetGameInfoForSdk:", paramsDict)
     uidlist = paramsDict.get('uids', '').split(',')
     for_winchip = paramsDict.get('for_winchip', 0)
     for_level_info = paramsDict.get('for_level_info', 0)
     for_online_info = paramsDict.get('for_online_info', 1)
     gameIds = paramsDict.get('gameids', '').split(',')
     for x in xrange(len(gameIds)):
         gameIds[x] = strutil.parseInts(gameIds[x])
     for x in xrange(len(uidlist)):
         uidlist[x] = strutil.parseInts(uidlist[x])
     return self._doGetGameInfoForSdk(uidlist, gameIds, for_level_info,
                                      for_winchip, for_online_info)
Ejemplo n.º 3
0
def checkSetMedal(gameId, userId, baseScore, isGameStart, winchip):
    winchip = 0 if isGameStart else winchip

    winrate, oldLevel = gamedata.getGameAttrs(userId, gameId,
                                              ['winrate', 'level'], False)
    winrate = strutil.loads(winrate, ignoreException=True, execptionValue={})
    if winrate is None:
        winrate = {}
    if winchip >= 0 or isGameStart:
        _processGamePlayWinTimes(winrate, isGameStart)
    oldLevel = strutil.parseInts(oldLevel)
    deltaExp = 0
    if winchip > 0 or isGameStart:
        deltaExp = _calUserDetalExp(winchip, baseScore)

    exp = userdata.incrExp(userId, deltaExp)
    explevel, _ = gameexp.getLevelInfo(gameId, exp)
    gamedata.setGameAttrs(userId, gameId, ['winrate', 'level'],
                          [strutil.dumps(winrate), explevel])
    if oldLevel != explevel:
        TYGame(gameId).getEventBus().publishEvent(
            UserLevelGrowEvent(gameId, userId, oldLevel, explevel))
    if isGameStart:
        # 广告商通知
        pcount = commconf.getAdNotifyPlayCount(gameId)
        if pcount > 0 and winrate.get('pt', 0) == pcount:
            sdkclient.adNotifyCallBack(gameId, userId)
    return exp, deltaExp, winrate
Ejemplo n.º 4
0
def _checkSetMedal(userId, roomMutil, basebet, basemulti, isGameStart,
                   winchip):
    winchip = 0 if isGameStart else winchip

    winrate, oldLevel = gamedata.getGameAttrs(userId, DIZHU_GAMEID,
                                              ['winrate', 'level'], False)
    winrate = strutil.loads(winrate, ignoreException=True, execptionValue={})
    if winchip >= 0 or isGameStart:
        _processGamePlayWinTimes(winrate, isGameStart)

    oldLevel = strutil.parseInts(oldLevel)
    detalExp = 0
    if winchip > 0 or isGameStart:
        detalExp = _calUserDetalExp(winchip, roomMutil, basebet, basemulti)
    exp = userdata.incrExp(userId, detalExp)
    explevel = dizhuaccount.getExpLevel(exp)

    gamedata.setGameAttrs(userId, DIZHU_GAMEID, ['winrate', 'level'],
                          [strutil.dumps(winrate), explevel])
    if oldLevel != explevel:
        from dizhu.game import TGDizhu
        TGDizhu.getEventBus().publishEvent(
            UserLevelGrowEvent(DIZHU_GAMEID, userId, oldLevel, explevel))
    if isGameStart:
        # 广告商通知
        pcount = dizhuconf.getAdNotifyPlayCount()
        if pcount > 0 and winrate.get('pt', 0) == pcount:
            sdkclient.adNotifyCallBack(DIZHU_GAMEID, userId)
    nextExp = dizhuaccount.getGameUserNextExp(explevel)
    title = dizhuaccount.getGameUserTitle(explevel)
    return [explevel, exp, detalExp, nextExp, title]
Ejemplo n.º 5
0
def _moveHall51DataBack(userId, gameId, clientId):
    try:
        gameId = HALL_ID
        flag = gamedata.getGameAttrInt(userId, gameId, 'userChipMoveGame')
        ftlog.info('_moveHall51DataBack', userId, gameId, flag)
        if flag > 0:
            # 当前用户登录过HALL51
            chip, exp, charm, coupon = gamedata.getGameAttrs(
                userId, gameId, ['chip', 'exp', 'charm', 'coupon'])
            chip, exp, charm, coupon = strutil.parseInts(
                chip, exp, charm, coupon)
            ftlog.info('_moveHall51DataBack data->', userId, gameId, chip, exp,
                       charm, coupon)
            if charm > 0:
                userdata.incrCharm(userId, charm)
            if exp > 0:
                userdata.incrExp(userId, exp)
            if coupon > 0:
                trueDelta, finalCount = userchip.incrCoupon(
                    userId, gameId, coupon, userchip.ChipNotEnoughOpMode.NOOP,
                    userchip.EVENT_NAME_SYSTEM_REPAIR, 0, clientId)
                ftlog.info('_moveHall51DataBack data coupon->', userId, gameId,
                           coupon, trueDelta, finalCount)
            if chip > 0:
                trueDelta, finalCount = userchip.incrChip(
                    userId, gameId, chip, userchip.ChipNotEnoughOpMode.NOOP,
                    userchip.EVENT_NAME_SYSTEM_REPAIR, 0, clientId)
                ftlog.info('_moveHall51DataBack data chip->', userId, gameId,
                           chip, trueDelta, finalCount)
            gamedata.delGameAttrs(
                userId, gameId,
                ['chip', 'exp', 'charm', 'coupon', 'userChipMoveGame'])
            datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
    except:
        ftlog.error()
Ejemplo n.º 6
0
def getGlobal(gameId, userId, pageNo=1):
    """
    已废弃,待删除
    取得当前用户的全局未读私信的内容
    """
    maxMsgId = daobase.executeMixCmd('HGET', 'msg',
                                     'msg.id.max.' + str(gameId))
    readMaxId = gamedata.getGameAttrs(userId, gameId, 'msg.id.global')
    rediskey = 'msg:' + str(gameId)

    maxMsgId, readMaxId = strutil.parseInts(maxMsgId, readMaxId)
    msglist = []
    maxId = readMaxId
    if pageNo < 1:
        pageNo = 1
    lstart = (pageNo - 1) * 20
    lend = lstart + 20 - 1
    datas = daobase.executeMixCmd('LRANGE', rediskey, lstart, lend)
    count = 0
    if datas:
        for msgstr in datas:
            msg = strutil.loads(msgstr, ignoreException=True)
            if msg:
                maxId = max(maxId, msg['id'])
                msglist.append(msg)
                count += 1
    if maxId > readMaxId:
        gamedata.setGameAttr(userId, gameId, 'msg.id.global', maxId)
    return {
        'count': count,
        'maxId': maxMsgId,
        'readId': readMaxId,
        'pageNo': pageNo,
        'list': msglist
    }
Ejemplo n.º 7
0
def resumeItemFromTable(userId, gameId, itemId, count, roomId, tableId):
    """退还房卡,加锁操作"""
    ftlog.debug('user_remote resumeItemFromTable userId:', userId
                , ' gameId:', gameId
                , ' itemId:', itemId
                , ' count:', count
                , ' roomId:', roomId
                , ' tableId:', tableId
                )

    clientId = sessiondata.getClientId(userId)
    loc = onlinedata.checkUserLoc(userId, clientId, gameId)
    ftlog.debug('user_remote resumeItemFromTable loc:', loc)

    lgameId, lroomId, ltableId, lseatId = loc.split('.')
    lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
    if (lroomId != roomId) or (ltableId != tableId):
        ftlog.info('user_remote resumeItemFromTable loc not match, do not resume item. userId:', userId
                   , ' gameId:', gameId
                   , ' itemId:', itemId
                   , ' count:', count
                   , ' roomId:', roomId
                   , ' tableId:', tableId
                   , ' loc:', loc)
        return

    MajiangItem.addUserItemByKindId(userId
                                    , gameId
                                    , itemId
                                    , count
                                    , 'MAJIANG_FANGKA_RETURN_BACK'
                                    , roomId)
Ejemplo n.º 8
0
def _setRoomOnLineInfo(gameId, roomId, userCount, playTableCount, observerCount):
    userCount, playTableCount, observerCount = strutil.parseInts(userCount, playTableCount, observerCount)
    val = str(userCount) + '|' + str(playTableCount) + '|' + str(observerCount)
    info = _ROOMS.get(roomId, None)
    if info != val:  # 减少非必要的redis数据更新
        _ROOMS[roomId] = val
        return daobase._sendBiCmd('HSET', daoconst.BI_KEY_ROOM_ONLINES % (gameId), roomId, val)
    return 1
Ejemplo n.º 9
0
    def onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, playMode,
                        clientId):
        '''
        拦截父类处理的选择房间逻辑,先于父类处理,若选择成功,则不进行父类的选择房间处理逻辑,否则正常走父类的处理逻辑
        '''

        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, clientId, gameId)
            ftlog.debug(
                'DizhuQuickStartV4_0.onCmdQuickStart:old client, checkUserLoc->',
                loc,
                caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
                    lgameId, lroomId, ltableId, lseatId)
                if lgameId == gameId and lroomId > 0:
                    roomId = lroomId
                    tableId = ltableId
                    ftlog.debug(
                        'DizhuQuickStartV4_0.onCmdQuickStartold client, reset roomId, tableId->',
                        roomId,
                        tableId,
                        caller=cls)

        _, version, _ = strutil.parseClientId(clientId)
        ftlog.debug("DizhuQuickStartV4_0.onCmdQuickStart: clientId=", clientId,
                    "userId=", userId, "roomId=", roomId,
                    "tableId=", tableId, "version=", version, "type:",
                    type(version), "playMode=", playMode)

        # 地主会优先去匹配比赛的房间,客户端是3.76及更高版本才支持
        if (playMode == None or playMode == "match" or playMode
                == "straightMatch") and roomId == 0 and gameId == 6 and (
                    version >= 3.76 or
                    (version >= 3.73
                     and not (clientId in _DIZHU_QMATCH_V3_73_IGNORE))):
            chose_roomid, ok = cls._chooseDizhuMatchRoom(
                userId, gameId, playMode)
            ftlog.debug(
                "DizhuQuickStartV4_0._chooseDizhuMatchRoom:chosen|room_id=",
                chose_roomid, "userId=", userId, "ok=", ok)
            if ok:
                bigroomid = gdata.getBigRoomId(chose_roomid)
                ftlog.debug(
                    "DizhuQuickStartV4_0._chooseDizhuMatchRoom: userId=",
                    userId, "roomId=", chose_roomid)
                cls.notifyQuickGotoDizhuMatch(gameId, userId, bigroomid)
                return

        if playMode == "match":
            playMode = dizhuconf.PLAYMODE_123

        super(DizhuQuickStartV4_0,
              cls).onCmdQuickStart(msg, userId, gameId, roomId, tableId,
                                   playMode, clientId)
        return
Ejemplo n.º 10
0
 def getSavedSeatUserId(cls, seatMaxN, roomId, tableId):
     attrlist = []
     for x in xrange(seatMaxN):
         attrlist.append('seat%dUserId' % (x + 1))
     uids = tabledata.getTableAttrs(roomId,
                                    tableId,
                                    attrlist,
                                    filterKeywords=False)
     return strutil.parseInts(*uids)
Ejemplo n.º 11
0
def get_unread_count(userid, typeid):
    """
    取得当前用户的未读站内消息的个数
    """
    readkey = MESSAGE_TYPES[typeid]
    maxid, readid = gamedata.getGameAttrs(userid, HALL_GAMEID,
                                          ['msg.id.max', readkey])
    maxid, readid = strutil.parseInts(maxid, readid)
    return maxid - readid
Ejemplo n.º 12
0
def _tryReadDataFromMySql(userId, intClientId, appId, ctfull):
    # 得到MySQL中的数据
    csize = getMysqlSize()
    dbname = 'user' + str(userId % csize)
    tablename = 't' + str(userId / csize % 200)
    sqlstr = 'select data from %s where userid=%d limit 1' % (tablename,
                                                              userId)
    ftlog.info('_tryReadDataFromMySql', userId, intClientId, appId, dbname,
               sqlstr)
    jsonstr = dbmysql._queryMysql00(userId, dbname, sqlstr)
    ftlog.info('_tryReadDataFromMySql before', userId, jsonstr)
    if not jsonstr:
        ftlog.info('_tryReadDataFromMySql', userId,
                   'the user mysql data not found !')
        return 0
    loaddatas = strutil.loads(jsonstr)
    # 拆解执行数据装载,避免redis的slowlog, 避免挤压redis
    isok, chip, diamond, coin, coupon = 1, 0, 0, 0, 0
    rkeys = loaddatas.keys()
    while (len(rkeys)) > 0:
        subrkeys = rkeys[0:4]
        rkeys = rkeys[4:]
        subdata = {}
        for subkey in subrkeys:
            subdata[subkey] = loaddatas[subkey]
        jsonstr1 = strutil.dumps(subdata)
        isok1, chip1, diamond1, coin1, coupon1 = daobase.executeUserLua(
            userId, dataswap_scripts.DATA_SWAP_LUA_SCRIPT, 3, userId, ctfull,
            jsonstr1)
        ftlog.debug('_tryReadDataFromMySql save to redis->', userId, isok,
                    jsonstr1)
        isok = min(isok, isok1)
        chip = max(chip, chip1)
        diamond = max(diamond, diamond1)
        coin = max(coin, coin1)
        coupon = max(coupon, coupon1)
    ftlog.info('_tryReadDataFromMySql save to redis->', userId, 'isok=', isok,
               'chip=', chip, 'diamond=', diamond, 'coin=', coin, 'coupon=',
               coupon)
    chip, diamond, coin, coupon = strutil.parseInts(chip, diamond, coin,
                                                    coupon)
    if isok == 1:
        from poker.entity.biz import bireport
        bireport.reportBiChip(userId, chip, chip, chip,
                              'DATA_FROM_MYSQL_2_REDIS_CHIP', intClientId,
                              appId, appId, 0, daoconst.CHIP_TYPE_CHIP)
        bireport.reportBiChip(userId, coin, coin, coin,
                              'DATA_FROM_MYSQL_2_REDIS_COIN', intClientId,
                              appId, appId, 0, daoconst.CHIP_TYPE_COIN)
        bireport.reportBiChip(userId, diamond, diamond, diamond,
                              'DATA_FROM_MYSQL_2_REDIS_DIAMOND', intClientId,
                              appId, appId, 0, daoconst.CHIP_TYPE_DIAMOND)
        bireport.reportBiChip(userId, coupon, coupon, coupon,
                              'DATA_FROM_MYSQL_2_REDIS_COUPON', intClientId,
                              appId, appId, 0, daoconst.CHIP_TYPE_COUPON)
        return 1
    return 0
Ejemplo n.º 13
0
def _tryReadDataFromMySql(userId, intClientId, appId, ctfull):
    # 得到MySQL中的数据
    csize = getMysqlSize()
    dbname = 'user' + str(userId % csize)
    tablename = 't' + str(userId / csize % 200)
    sqlstr = 'select data from %s where userid=%d limit 1' % (tablename, userId)
    ftlog.info('_tryReadDataFromMySql', userId, intClientId, appId, dbname, sqlstr)
    jsonstr = dbmysql._queryMysql00(userId, dbname, sqlstr)
    ftlog.info('_tryReadDataFromMySql before', userId, jsonstr)
    if not jsonstr:
        ftlog.info('_tryReadDataFromMySql', userId, 'the user mysql data not found !')
        return 0
    loaddatas = strutil.loads(jsonstr)
    # 拆解执行数据装载,避免redis的slowlog, 避免挤压redis
    isok, chip, diamond, coin, coupon = 1, 0, 0, 0, 0
    rkeys = loaddatas.keys()
    while (len(rkeys)) > 0:
        subrkeys = rkeys[0:4]
        rkeys = rkeys[4:]
        subdata = {}
        for subkey in subrkeys:
            subdata[subkey] = loaddatas[subkey]
        jsonstr1 = strutil.dumps(subdata)
        isok1, chip1, diamond1, coin1, coupon1 = daobase.executeUserLua(userId,
                                                                        dataswap_scripts.DATA_SWAP_LUA_SCRIPT, 3,
                                                                        userId, ctfull, jsonstr1)
        ftlog.debug('_tryReadDataFromMySql save to redis->', userId, isok, jsonstr1)
        isok = min(isok, isok1)
        chip = max(chip, chip1)
        diamond = max(diamond, diamond1)
        coin = max(coin, coin1)
        coupon = max(coupon, coupon1)
    ftlog.info('_tryReadDataFromMySql save to redis->', userId,
               'isok=', isok, 'chip=', chip, 'diamond=', diamond,
               'coin=', coin, 'coupon=', coupon)
    chip, diamond, coin, coupon = strutil.parseInts(chip, diamond, coin, coupon)
    if isok == 1:
        from poker.entity.biz import bireport
        bireport.reportBiChip(userId, chip, chip, chip,
                              'DATA_FROM_MYSQL_2_REDIS_CHIP',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_CHIP)
        bireport.reportBiChip(userId, coin, coin, coin,
                              'DATA_FROM_MYSQL_2_REDIS_COIN',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_COIN)
        bireport.reportBiChip(userId, diamond, diamond, diamond,
                              'DATA_FROM_MYSQL_2_REDIS_DIAMOND',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_DIAMOND)
        bireport.reportBiChip(userId, coupon, coupon, coupon,
                              'DATA_FROM_MYSQL_2_REDIS_COUPON',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_COUPON)
        return 1
    return 0
Ejemplo n.º 14
0
def getGlobalUnReadCount(gameId, userId):
    """
    已废弃,待删除
    取得当前用户的未读站内消息的个数
    """
    maxglobalid = daobase.executeMixCmd('HGET', 'msg',
                                        'msg.id.max.' + str(gameId))
    globalid = gamedata.getGameAttr(userId, gameId, 'msg.id.global')
    maxglobalid, globalid = strutil.parseInts(maxglobalid, globalid)
    return maxglobalid - globalid
Ejemplo n.º 15
0
def _setRoomOnLineInfo(gameId, roomId, userCount, playTableCount,
                       observerCount):
    userCount, playTableCount, observerCount = strutil.parseInts(
        userCount, playTableCount, observerCount)
    val = str(userCount) + '|' + str(playTableCount) + '|' + str(observerCount)
    info = _ROOMS.get(roomId, None)
    if info != val:  # 减少非必要的redis数据更新
        _ROOMS[roomId] = val
        return daobase._sendBiCmd('HSET',
                                  daoconst.BI_KEY_ROOM_ONLINES % (gameId),
                                  roomId, val)
    return 1
Ejemplo n.º 16
0
    def onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, playMode, clientId):
        # 单开, 无论何时quick_start进入都检查loc
        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, clientId, gameId)
            if ftlog.is_debug():
                ftlog.debug('DizhuQuickStart old client, checkUserLoc->', loc, caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
                if lgameId == gameId and lroomId > 0:
                    if ftlog.is_debug():
                        ftlog.debug('DizhuQuickStart _quickStart re-connected |userId, loc:', userId, loc,
                                    '|roomId, tableId:', roomId, tableId, caller=cls)
                    roomId = lroomId
                    tableId = ltableId
                    msg.setParam('isReConnected', True)
                    if ftlog.is_debug():
                        ftlog.debug('DizhuQuickStart old client, reset roomId, tableId->', roomId, tableId, caller=cls)

        if not tableId and game.isShutDown():
            cls._sendTodoTaskToUser(userId, ENTER_ROOM_REASON_GAME_SHUTDOWN_GO)
            return

        # 带有roomId
        if roomId:
            cls._quickStart(msg, userId, gameId, roomId, tableId, playMode, clientId)
            return

        # 不带 roomId 服务器来选择房间
        ctrlRoomIds, mixRoomReversed = cls._getQuickStartRoomList(userId, playMode, rankId=msg.getParam('rankId', '-1'))  # 快开列表
        chose_roomid, ok, mixId = cls._chooseRoom(userId, ctrlRoomIds, rankId=msg.getParam('rankId', '-1'), mixRoomReversed=mixRoomReversed)  # 选择一个
        if ok == ENTER_ROOM_REASON_OK:
            bigroomid = gdata.getBigRoomId(chose_roomid)
            ismatch = gdata.roomIdDefineMap()[chose_roomid].configure.get('ismatch', 0)
            if ftlog.is_debug():
                ftlog.debug("DizhuQuickStart._chooseRoom: userId=", userId, "roomId=", chose_roomid, 'mixId=', mixId)
            if ismatch:
                cls.notifyQuickGotoDizhuMatch(gameId, userId, bigroomid, mixId=mixId)
            else:
                msg.setParam('mixId', mixId)
                ctrRoomIds = gdata.bigRoomidsMap()[bigroomid]
                ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]
                TYRoomMixin.queryRoomQuickStartReq(msg, ctrlRoomId, 0)  # 请求发给 GR
        elif ok == ENTER_ROOM_REASON_QUIT_ROOM_ERROR:
            cls._sendTodoTaskToUser(userId, ok)
        elif (ok == ENTER_ROOM_REASON_LESS_MIN or ok == ENTER_ROOM_REASON_LESS_MIN_QUICKSTART) and msg.getParam('rankId', '-1') in ['0', '1']:
            cls._sendTodoTaskBuyChip(userId, chose_roomid, clientId, mixId)
        elif ok == ENTER_ROOM_REASON_LESS_MIN_QUICKSTART:
            cls._sendTodoTaskBuyChip(userId, chose_roomid, clientId, mixId)
        else:
            cls._sendTodoTaskJumpHighRoom(userId, playMode, clientId, rankId='-1')
        return
Ejemplo n.º 17
0
    def checkReConnect(cls, userId, clientId, gameId):
        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        if ftlog.is_debug():
            ftlog.debug('checkUserLoc |userId, gameId, loc:', userId, gameId, loc, caller=cls)
        if isinstance(loc, basestring):
            lgameId, lroomId, ltableId, lseatId = strutil.parseInts(*loc.split('.'))
            if lgameId == gameId and lroomId > 0:
                if ftlog.is_debug():
                    ftlog.debug('re-connected |userId, gameId, loc:', userId, gameId, loc, caller=cls)
                TYRoomMixin.querySitReq(userId, lroomId, ltableId, clientId)
                return True

        return False
Ejemplo n.º 18
0
def _getRoomOnLineUserCount(gameId, withShadowRoomInfo):
    '''
    重BI数据库中取得当前的游戏的所有的在线人数信息
    return allcount, counts, details, allobcount, obcounts, obdetails
    allcount int,游戏内所有房间的人数的总和
    counts 字典dict,key为大房间ID(bigRoomId),value为该大房间内的人数总和
    details 字典dict,key为房间实例ID(roomId),value为该房间内的人数
    allobcount, obcounts, obdetails 观察者数量,需要table类实现observersNum属性
    此数据由每个GR,GT进程每10秒钟向BI数据库进行汇报一次
    '''
    rkey = daoconst.BI_KEY_ROOM_ONLINES % (gameId)
    datas = daobase._executeBiCmd('HGETALL', rkey)
    counts = {}
    details = {}
    allcount = 0
    allobcount = 0
    obdetails = {}
    obcounts = {}
    if datas:
        allrooms = gdata.roomIdDefineMap()
        for x in xrange(len(datas) / 2):
            i = x * 2
            roomId = int(datas[i])
            roomConf = allrooms.get(roomId, None)
            if roomConf:
                bigRoomId = str(roomConf.bigRoomId)
                tks = datas[i + 1].split('|')
                ucount, ocount = strutil.parseInts(tks[0], tks[-1])
                ucount += roomConf.configure.get('dummyUserCount', 0)
                if withShadowRoomInfo:
                    details[str(roomId)] = ucount
                if bigRoomId in counts:
                    counts[bigRoomId] += ucount
                else:
                    counts[bigRoomId] = ucount
                allcount += ucount

                if withShadowRoomInfo:
                    obdetails[str(roomId)] = ocount
                if bigRoomId in obcounts:
                    obcounts[bigRoomId] += ocount
                else:
                    obcounts[bigRoomId] = ocount
                allobcount += ocount

            else:
                daobase._sendBiCmd('HDEL', rkey, roomId)
    return allcount, counts, details, allobcount, obcounts, obdetails
Ejemplo n.º 19
0
def _getRoomOnLineUserCount(gameId, withShadowRoomInfo):
    '''
    重BI数据库中取得当前的游戏的所有的在线人数信息
    return allcount, counts, details, allobcount, obcounts, obdetails
    allcount int,游戏内所有房间的人数的总和
    counts 字典dict,key为大房间ID(bigRoomId),value为该大房间内的人数总和
    details 字典dict,key为房间实例ID(roomId),value为该房间内的人数
    allobcount, obcounts, obdetails 观察者数量,需要table类实现observersNum属性
    此数据由每个GR,GT进程每10秒钟向BI数据库进行汇报一次
    '''
    rkey = daoconst.BI_KEY_ROOM_ONLINES % (gameId)
    datas = daobase._executeBiCmd('HGETALL', rkey)
    counts = {}
    details = {}
    allcount = 0
    allobcount = 0
    obdetails = {}
    obcounts = {}
    if datas:
        allrooms = gdata.roomIdDefineMap()
        for x in xrange(len(datas) / 2):
            i = x * 2
            roomId = int(datas[i])
            roomConf = allrooms.get(roomId, None)
            if roomConf:
                bigRoomId = str(roomConf.bigRoomId)
                tks = datas[i + 1].split('|')
                ucount, ocount = strutil.parseInts(tks[0], tks[-1])
                ucount += roomConf.configure.get('dummyUserCount', 0)
                if withShadowRoomInfo:
                    details[str(roomId)] = ucount
                if bigRoomId in counts:
                    counts[bigRoomId] += ucount
                else:
                    counts[bigRoomId] = ucount
                allcount += ucount

                if withShadowRoomInfo:
                    obdetails[str(roomId)] = ocount
                if bigRoomId in obcounts:
                    obcounts[bigRoomId] += ocount
                else:
                    obcounts[bigRoomId] = ocount
                allobcount += ocount

            else:
                daobase._sendBiCmd('HDEL', rkey, roomId)
    return allcount, counts, details, allobcount, obcounts, obdetails
Ejemplo n.º 20
0
    def doJoinCreateTable(self, userId, gameId, clientId, roomId0, tableId0,
                          playMode):
        """用户加入自建牌桌
        """
        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        lgameId, lroomId, ltableId, lseatId = loc.split('.')
        lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
            lgameId, lroomId, ltableId, lseatId)
        if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >= 0:
            ftlog.warn('create_table error, user in table')
            sendPopTipMsg(userId, "请稍候,正在进桌...")
            config = {
                "type": "quickstart",
                "pluginParams": {
                    "roomId": lroomId,
                    "tableId": ltableId,
                    "seatId": lseatId
                }
            }
            todotask = TodoTaskEnterGameNew(lgameId, config)
            mo = MsgPack()
            mo.setCmd('todo_tasks')
            mo.setResult('gameId', gameId)
            mo.setResult('pluginId', lgameId)
            mo.setResult('userId', userId)
            mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask))
            router.sendToUser(mo, userId)
        else:
            msg = runcmd.getMsgPack()
            createTableNo = msg.getParam('createTableNo', 0)
            if not createTableNo:
                return
            tableId0, roomId0 = CreateTableData.getTableIdByCreateTableNo(
                createTableNo)
            if not tableId0 or not roomId0:
                sendPopTipMsg(userId, "找不到您输入的房间号")
                return
            msg = runcmd.getMsgPack()
            msg.setParam("shadowRoomId", roomId0)
            msg.setParam("roomId", roomId0)
            msg.setParam("tableId", tableId0)
            msg.setCmdAction("room", "join_create_table")
            router.sendRoomServer(msg, roomId0)

            if router.isQuery():
                mo = runcmd.newOkMsgPack(1)
                router.responseQurery(mo, '', str(userId))
Ejemplo n.º 21
0
 def _checkUserLoc(cls, userId, clientId, gameId):
     ''' 检查用户位置信息,返回所在房间roomId以及tableId '''
     if not pokerconf.isOpenMoreTable(clientId):
         loc = onlinedata.checkUserLoc(userId, clientId, gameId)
         if isinstance(loc, basestring):
             locGameId, locRoomId, locTableId, locSeatId = loc.split('.')
             locGameId, locRoomId, locTableId, locSeatId = strutil.parseInts(locGameId, locRoomId, locTableId, locSeatId)
             if locGameId == gameId and locRoomId > 0:
                 if ftlog.is_debug():
                     ftlog.debug('DizhuQuickStartWx.checkUserLoc'
                                 'userId=', userId,
                                 'clientId=', clientId,
                                 'locRoomId=', locRoomId,
                                 'locTableId=', locTableId,
                                 'locSeatId=', locSeatId)
                 return locRoomId, locTableId, locSeatId
     return 0, 0, 0
Ejemplo n.º 22
0
    def doJoinCreateTable(self, userId, gameId, clientId, roomId0, tableId0, playMode):
        """用户加入自建牌桌
        """
        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        lgameId, lroomId, ltableId, lseatId = loc.split('.')
        lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
        if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >= 0:
            ftlog.warn('create_table error, user in table')
            sendPopTipMsg(userId, "请稍候,正在进桌...")
            config = {
                "type": "quickstart",
                "pluginParams": {
                    "roomId": lroomId,
                    "tableId": ltableId,
                    "seatId": lseatId
                }
            }
            todotask = TodoTaskEnterGameNew(lgameId, config)
            mo = MsgPack()
            mo.setCmd('todo_tasks')
            mo.setResult('gameId', gameId)
            mo.setResult('pluginId', lgameId)
            mo.setResult('userId', userId)
            mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask))
            router.sendToUser(mo, userId)
        else:
            msg = runcmd.getMsgPack()
            createTableNo = msg.getParam('createTableNo', 0)
            if not createTableNo:
                return
            tableId0, roomId0 = CreateTableData.getTableIdByCreateTableNo(createTableNo)
            if not tableId0 or not roomId0:
                sendPopTipMsg(userId, "找不到您输入的房间号")
                return
            msg = runcmd.getMsgPack()
            msg.setParam("shadowRoomId", roomId0)
            msg.setParam("roomId", roomId0)
            msg.setParam("tableId", tableId0)
            msg.setCmdAction("room", "join_create_table")
            router.sendRoomServer(msg, roomId0)

            if router.isQuery():
                mo = runcmd.newOkMsgPack(1)
                router.responseQurery(mo, '', str(userId))
Ejemplo n.º 23
0
    def recoverUserTableChips(self, userId, clientId):
        try:
            tableChips = userchip.getTableChipsAll(userId)
            ftlog.debug('recoverUserTableChips->', tableChips)
            datas = None
            if isinstance(tableChips, dict):
                datas = tableChips
            elif isinstance(tableChips, list):
                datas = {}
                for x in xrange(len(tableChips) / 2):
                    datas[tableChips[x * 2]] = tableChips[x * 2 + 1]
            delTablesIds = []
            for tableId, tchip in datas.items():
                tableId, tchip = strutil.parseInts(tableId, tchip)
                troomId = strutil.getTableRoomId(tableId)
                if not troomId or troomId <= 0:
                    delTablesIds.append(tableId)
                    continue
                gameId, _, _, _ = strutil.parseInstanceRoomId(troomId)
                if not gameId or gameId <= 0:
                    delTablesIds.append(tableId)
                    continue
                seatId = 0
                try:
                    seatId, _ = roommgr.doCheckUserLoc(userId, gameId, troomId,
                                                       tableId, clientId)
                except:
                    delTablesIds.append(tableId)
                    ftlog.error()
                    continue

                if not seatId:
                    userchip.moveAllTableChipToChip(userId, gameId,
                                                    'TABLE_TCHIP_TO_CHIP',
                                                    troomId, clientId, tableId)
                    delTablesIds.append(tableId)
                else:
                    # the user is on the table , do not clear
                    pass

            if delTablesIds:
                userchip.delTableChips(userId, delTablesIds)
        except:
            ftlog.error()
Ejemplo n.º 24
0
def get(userid, typeid):
    """
    获取消息列表
    @param userid:
    @param typeid: 类型, L{message.MESSAGE_TYPES}
    @return:
    """
    if typeid not in MESSAGE_TYPES:
        raise Exception("message.get, unkown type:{}".format(typeid))
    rediskey = REDIS_KEY.format(typeid, HALL_GAMEID, userid)
    msglist = _msg_load_and_expire(userid, rediskey)
    msglist.sort(key=_msg_order)

    readkey = MESSAGE_TYPES[typeid]
    maxid, readid = gamedata.getGameAttrs(userid, HALL_GAMEID,
                                          ['msg.id.max', readkey])
    maxid, readid = strutil.parseInts(maxid, readid)
    if maxid > readid:
        gamedata.setGameAttr(userid, HALL_GAMEID, readkey, maxid)
    return {'readid': readid, 'list': msglist}
Ejemplo n.º 25
0
    def recoverUserTableChips(self, userId, clientId):
        try:
            tableChips = userchip.getTableChipsAll(userId)
            ftlog.debug('recoverUserTableChips->', tableChips)
            datas = None
            if isinstance(tableChips, dict):
                datas = tableChips
            elif isinstance(tableChips, list):
                datas = {}
                for x in xrange(len(tableChips) / 2):
                    datas[tableChips[x * 2]] = tableChips[x * 2 + 1]
            delTablesIds = []
            for tableId, tchip in datas.items():
                tableId, tchip = strutil.parseInts(tableId, tchip)
                troomId = strutil.getTableRoomId(tableId)
                if not troomId or troomId <= 0:
                    delTablesIds.append(tableId)
                    continue
                gameId, _, _, _ = strutil.parseInstanceRoomId(troomId)
                if not gameId or gameId <= 0:
                    delTablesIds.append(tableId)
                    continue
                seatId = 0
                try:
                    seatId, _ = roommgr.doCheckUserLoc(userId, gameId, troomId, tableId, clientId)
                except:
                    delTablesIds.append(tableId)
                    ftlog.error()
                    continue

                if not seatId:
                    userchip.moveAllTableChipToChip(userId, gameId, 'TABLE_TCHIP_TO_CHIP', troomId, clientId, tableId)
                    delTablesIds.append(tableId)
                else:
                    # the user is on the table , do not clear
                    pass

            if delTablesIds:
                userchip.delTableChips(userId, delTablesIds)
        except:
            ftlog.error()
Ejemplo n.º 26
0
    def checkReConnect(cls, userId, clientId, gameId):
        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        if ftlog.is_debug():
            ftlog.debug('checkUserLoc |userId, gameId, loc:',
                        userId,
                        gameId,
                        loc,
                        caller=cls)
        if isinstance(loc, basestring):
            lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
                *loc.split('.'))
            if lgameId == gameId and lroomId > 0:
                if ftlog.is_debug():
                    ftlog.debug('re-connected |userId, gameId, loc:',
                                userId,
                                gameId,
                                loc,
                                caller=cls)
                TYRoomMixin.querySitReq(userId, lroomId, ltableId, clientId)
                return True

        return False
Ejemplo n.º 27
0
def resumeItemFromTable(userId, gameId, itemId, count, roomId, tableId):
    """退还房卡,加锁操作"""
    ftlog.debug('user_remote resumeItemFromTable userId:', userId, ' gameId:',
                gameId, ' itemId:', itemId, ' count:', count, ' roomId:',
                roomId, ' tableId:', tableId)

    clientId = sessiondata.getClientId(userId)
    loc = onlinedata.checkUserLoc(userId, clientId, gameId)
    ftlog.debug('user_remote resumeItemFromTable loc:', loc)

    lgameId, lroomId, ltableId, lseatId = loc.split('.')
    lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
        lgameId, lroomId, ltableId, lseatId)
    if (lroomId != roomId) or (ltableId != tableId):
        ftlog.info(
            'user_remote resumeItemFromTable loc not match, do not resume item. userId:',
            userId, ' gameId:', gameId, ' itemId:', itemId, ' count:', count,
            ' roomId:', roomId, ' tableId:', tableId, ' loc:', loc)
        return

    MajiangItem.addUserItemByKindId(userId, gameId, itemId, count,
                                    'MAJIANG_FANGKA_RETURN_BACK', roomId)
Ejemplo n.º 28
0
def _calRankInfoData(userId, seatDeltaChip, winslam, windoubles):
    ftlog.debug('calRankInfoData->', userId, seatDeltaChip, winslam,
                windoubles)
    # 每周,城市赢金榜
    if seatDeltaChip > 0 and dizhuconf.isUseTuyouRanking():  # 陌陌使用自己的排行榜
        city_code = sessiondata.getCityZip(userId)
        city_index = city_locator.ZIP_CODE_INDEX.get(city_code, 1)
        rankingId = 110006100 + city_index
        hallranking.rankingSystem.setUserScore(str(rankingId), userId,
                                               seatDeltaChip)

    # 更新gamedata中的各种max和累积值
    winchips, losechips, maxwinchip, weekchips, winrate, maxweekdoubles, slams, todaychips = gamedata.getGameAttrs(
        userId, DIZHU_GAMEID, [
            'winchips', 'losechips', 'maxwinchip', 'weekchips', 'winrate',
            'maxweekdoubles', 'slams', 'todaychips'
        ], False)
    ftlog.debug('calRankInfoData->', winchips, losechips, maxwinchip,
                weekchips, winrate, maxweekdoubles, slams)
    winchips, losechips, maxwinchip, maxweekdoubles, slams = strutil.parseInts(
        winchips, losechips, maxwinchip, maxweekdoubles, slams)
    updatekeys = []
    updatevalues = []

    # 计算累计的输赢金币
    if seatDeltaChip > 0:
        winchips = winchips + seatDeltaChip
        updatekeys.append('winchips')
        updatevalues.append(winchips)
    else:
        losechips = losechips + seatDeltaChip
        updatekeys.append('losechips')
        updatevalues.append(losechips)

    # 计算增加最大的赢取金币数
    if seatDeltaChip > maxwinchip:
        updatekeys.append('maxwinchip')
        updatevalues.append(seatDeltaChip)

    # 计算增加每星期的累计赢取、输掉的金币数
    weekchips = strutil.loads(weekchips, ignoreException=True)
    if weekchips == None or len(weekchips) != 2 or (
            not 'week' in weekchips) or (not 'chips' in weekchips):
        weekchips = {'week': -1, 'chips': 0}
    weekOfYear = pktimestamp.formatTimeWeekInt()
    if weekOfYear != weekchips['week']:
        weekchips = {'week': weekOfYear, 'chips': seatDeltaChip}
    else:
        weekchips['chips'] = weekchips['chips'] + seatDeltaChip
    updatekeys.append('weekchips')
    updatevalues.append(strutil.dumps(weekchips))

    # 计算增加每星期的累计赢取的金币数
    if seatDeltaChip > 0:
        todaychips = strutil.loads(todaychips, ignoreException=True)
        if todaychips == None or len(todaychips) != 3 \
            or (not 'today' in todaychips) or (not 'chips' in todaychips) or (not 'last' in todaychips) :
            todaychips = {'today': -1, 'chips': 0, 'last': 0}
        today = pktimestamp.formatTimeDayInt()
        if today != todaychips['today']:
            yesterdaychips = 0
            if todaychips['today'] == pktimestamp.formatTimeYesterDayInt():
                yesterdaychips = todaychips['chips']
            todaychips = {
                'today': today,
                'chips': seatDeltaChip,
                'last': yesterdaychips
            }
        else:
            todaychips['chips'] = todaychips['chips'] + seatDeltaChip
        updatekeys.append('todaychips')
        updatevalues.append(strutil.dumps(todaychips))

    # 计算marsscore
    winchipsDelta = int(winchips) - int(losechips)
    winrate = strutil.loads(winrate,
                            ignoreException=True,
                            execptionValue={'wt': 0})
    wintimes = int(winrate.get('wt', 0))
    marsscore = winchipsDelta * 0.6 + wintimes * 200 * 0.4
    if marsscore > 0:
        updatekeys.append('marsscore')
        updatevalues.append(marsscore)

    # 计算slams和maxweekdoubles
    if seatDeltaChip > 0:
        if winslam:
            updatekeys.append('slams')
            updatevalues.append(slams + 1)

        if maxweekdoubles < windoubles:
            updatekeys.append('maxweekdoubles')
            updatevalues.append(windoubles)

    if len(updatekeys) > 0:
        gamedata.setGameAttrs(userId, DIZHU_GAMEID, updatekeys, updatevalues)
    return 1
Ejemplo n.º 29
0
    def onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, playMode,
                        clientId):
        '''UT server中处理来自客户端的quick_start请求  
        Args:
            msg
                cmd : quick_start
                if roomId == 0:
                    表示快速开始,服务器为玩家选择房间,然后将请求转给GR
                    
                if roomId > 0 and tableId == 0 : 
                    表示玩家选择了房间,将请求转给GR
                    
                if roomId > 0 and tableId == roomId * 10000 :
                    表示玩家在队列里断线重连,将请求转给GR
                    
                if roomId > 0 and tableId > 0:
                    if onlineSeatId > 0: 
                        表示玩家在牌桌里断线重连,将请求转给GT
                    else:
                        表示玩家选择了桌子,将请求转给GR
        '''
        assert isinstance(userId, int) and userId > 0
        assert isinstance(roomId, int) and roomId >= 0
        assert isinstance(tableId, int) and tableId >= 0
        ftlog.debug("MajiangQuickStartV4_0.onCmdQuickStart clientId:",
                    clientId, " userId:", userId, " roomId:", roomId,
                    " tableId:", tableId, " gameId:", gameId, " playMode:",
                    playMode)

        isCreate = False
        if roomId > 0:
            isCreate = cls.isFriendRoom(roomId)

        isReconnect = False
        # 单开, 无论何时quick_start进入都检查loc
        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, clientId, gameId)
            ftlog.debug('MajiangQuickStartV4_0.onCmdQuickStart checkUserLoc:',
                        loc,
                        caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
                    lgameId, lroomId, ltableId, lseatId)
                if isCreate and (lroomId == 0) and (ltableId == 0):
                    # 好友桌的快速开始必须有loc,没有loc则进桌失败
                    ftlog.debug(
                        'MajiangQuickStartV4_0.onCmdQuickStart room is friendTable, loc is 0, means, table is dissolved...'
                    )
                    cls._onEnterRoomFailed(
                        msg, TYRoom.ENTER_ROOM_REASON_FRIEND_DISSOLVE, userId,
                        clientId, roomId)
                    return

                if lgameId == gameId and lroomId > 0:
                    roomId = lroomId
                    tableId = ltableId
                    isReconnect = True
                    ftlog.debug(
                        'MajiangQuickStartV4_0.onCmdQuickStart old client roomId:',
                        roomId,
                        ' tableId:',
                        tableId,
                        caller=cls)

        if (not isReconnect) and roomId > 0 and tableId > 0:
            reason = cls._canQuickEnterRoom(userId, gameId, roomId, 1)
            if reason != TYRoom.ENTER_ROOM_REASON_OK:
                cls._onEnterRoomFailed(msg, reason, userId, gameId, clientId,
                                       roomId)
                return

        if roomId == 0:  # 玩家点击快速开始
            chosenRoomId, checkResult = cls._chooseRoom(
                userId, gameId, playMode)
            ftlog.info(
                "MajiangQuickStartV4_0.onCmdQuickStart after choose room userId:",
                userId,
                " chosenRoomId:",
                chosenRoomId,
                " checkResult:",
                checkResult,
                caller=cls)
            if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                #找到合适的房间 根据roomId找到合适的table
                TYRoomMixin.queryRoomQuickStartReq(msg, chosenRoomId,
                                                   0)  # 请求转给GR
            else:
                candidateRoomIds = cls._getCandidateRoomIds(gameId, playMode)
                if candidateRoomIds:
                    rid = candidateRoomIds[0]
                    msg.setParam('candidateRoomId', rid)
                cls._onEnterRoomFailed(msg, checkResult, userId, clientId,
                                       roomId)
            return

        if tableId == 0:  # 玩家只选择了房间
            bigRoomId = gdata.getBigRoomId(roomId)
            if bigRoomId == 0:
                cls._onEnterRoomFailed(msg,
                                       TYRoom.ENTER_ROOM_REASON_ROOM_ID_ERROR,
                                       userId, gameId, clientId, roomId)
                return
            ctrRoomIds = gdata.bigRoomidsMap()[bigRoomId]
            ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]

            reason = cls._canQuickEnterRoom(userId, gameId, ctrlRoomId, 1)
            if reason == TYRoom.ENTER_ROOM_REASON_OK:
                TYRoomMixin.queryRoomQuickStartReq(msg, ctrlRoomId,
                                                   0)  # 请求转给GR或GT
            else:
                cls._onEnterRoomFailed(msg, reason, userId, gameId, clientId,
                                       roomId)
            return

        if tableId == roomId * 10000:  # 玩家在队列里断线重连
            TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId)  # 请求转给GR
            return

        onlineSeat = onlinedata.getOnlineLocSeatId(userId, roomId, tableId)

        if onlineSeat:
            extParam = {}
            extParam['seatId'] = onlineSeat
            moParams = msg.getKey('params')
            for k, v in moParams.items():
                if not k in extParam:
                    extParam[k] = v
            ftlog.debug('extParam=', extParam)
            TYRoomMixin.querySitReq(userId, roomId, tableId, clientId,
                                    extParam)  # 玩家断线重连,请求转给GT
        else:  # 玩家选择了桌子,
            shadowRoomId = tableId / 10000
            ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
            TYRoomMixin.queryRoomQuickStartReq(
                msg, ctrRoomId, tableId, shadowRoomId=shadowRoomId)  # 请求转给GR
Ejemplo n.º 30
0
    def createTableQuickStart(cls, msg, itemParams, userId, roomId, tableId,
                              playMode, clientId):
        '''UT server中处理来自客户端的create_table请求  
        Args:
            msg
                cmd : create_table
                if roomId == 0:
                    表示玩家创建房间,服务器为玩家选择房间,然后将请求转给GR
                    
                if roomId > 0 and tableId == 0 : 
                    表示玩家选择了房间,将请求转给GR
                    
                if roomId > 0 and tableId == roomId * 10000 :
                    表示玩家在队列里断线重连,将请求转给GR
                    
                if roomId > 0 and tableId > 0:
                    if onlineSeatId > 0: 
                        表示玩家在牌桌里断线重连,将请求转给GT
                    else:
                        表示玩家选择了桌子,将请求转给GR
        '''
        assert isinstance(userId, int) and userId > 0
        assert isinstance(roomId, int) and roomId >= 0
        assert isinstance(tableId, int) and tableId >= 0
        ftlog.debug("<< |clientId:",
                    clientId,
                    "|userId, roomId, tableId:",
                    userId,
                    roomId,
                    tableId,
                    "|gameId, playMode:",
                    playMode,
                    caller=cls)

        isReconnect = False
        gameId = msg.getResult('gameId')

        # 单开, 无论何时quick_start进入都检查loc
        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, gameId)
            ftlog.debug('old client, checkUserLoc->', loc, caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
                    lgameId, lroomId, ltableId, lseatId)
                if lgameId == gameId and lroomId > 0:
                    roomId = lroomId
                    tableId = ltableId
                    isReconnect = True
                    ftlog.debug('old client, reset roomId, tableId->',
                                roomId,
                                tableId,
                                caller=cls)

        if (not isReconnect) and roomId > 0 and tableId > 0:
            reason = cls._canQuickEnterCreateRoom(userId, gameId, roomId)
            if reason != TYRoom.ENTER_ROOM_REASON_OK:
                cls._onEnterCreateRoomFailed(reason, userId, gameId, clientId,
                                             roomId)
                return
        tempShadowRoomId = 0
        if roomId == 0:  # 第一个玩家创建房间牌桌
            chosenRoomId, checkResult = cls._chooseCreateRoom(
                userId, gameId, playMode)
            ftlog.info("after choose room",
                       "|userId, chosenRoomId, checkResult:",
                       userId,
                       chosenRoomId,
                       checkResult,
                       caller=cls)
            if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                #得到房间ID,找合适的tableId
                roomDef = gdata.roomIdDefineMap()[chosenRoomId]
                shadowRoomIds = roomDef.shadowRoomIds
                if shadowRoomIds:
                    for shadowRoomId in shadowRoomIds:
                        tableId = table_rpc.getTableByRoomId(shadowRoomId)
                        if isinstance(tableId, int) and tableId > 0:
                            tempShadowRoomId = shadowRoomId
                            break

                shadowRoomId = tableId / 10000
                if shadowRoomId == tempShadowRoomId:  # 验证
                    ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
                    TYRoomMixin.queryRoomQuickStartReq(
                        msg, ctrRoomId, tableId,
                        shadowRoomId=shadowRoomId)  # 请求转给GR
                    return
                else:
                    cls._onEnterCreateRoomFailed(checkResult, userId, gameId,
                                                 clientId, roomId)
                    return
            else:
                cls._onEnterCreateRoomFailed(checkResult, userId, gameId,
                                             clientId, roomId)
                return
        else:
            onlineSeat = onlinedata.getOnlineLocSeatId(userId, gameId, roomId,
                                                       tableId)
            if onlineSeat:
                extParam = {}
                extParam['seatId'] = onlineSeat
                moParams = msg.getKey('params')
                for k, v in moParams.items():
                    if not k in extParam:
                        extParam[k] = v
                ftlog.debug('extParam=', extParam)
                TYRoomMixin.querySitReq(userId, roomId, tableId, clientId,
                                        extParam)  # 玩家断线重连,请求转给GT
                return
        if tableId == roomId * 10000:  # 玩家在队列里断线重连
            TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId)  # 请求转给GR
            return
        # 玩家选择了桌子,进桌
        shadowRoomId = tableId / 10000
        ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
        TYRoomMixin.queryRoomQuickStartReq(msg,
                                           ctrRoomId,
                                           tableId,
                                           shadowRoomId=shadowRoomId)  # 请求转给GR
Ejemplo n.º 31
0
    def onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, playMode, clientId):
        '''UT server中处理来自客户端的quick_start请求  
        Args:
            msg
                cmd : quick_start
                if roomId == 0:
                    表示快速开始,服务器为玩家选择房间,然后将请求转给GR
                    
                if roomId > 0 and tableId == 0 : 
                    表示玩家选择了房间,将请求转给GR
                    
                if roomId > 0 and tableId == roomId * 10000 :
                    表示玩家在队列里断线重连,将请求转给GR
                    
                if roomId > 0 and tableId > 0:
                    if onlineSeatId > 0: 
                        表示玩家在牌桌里断线重连,将请求转给GT
                    else:
                        表示玩家选择了桌子,将请求转给GR
        '''
        assert isinstance(userId, int) and userId > 0
        assert isinstance(roomId, int) and roomId >= 0
        assert isinstance(tableId, int) and tableId >= 0

        ftlog.debug("<< |clientId:", clientId,
                    "|userId, roomId, tableId:", userId, roomId, tableId,
                    "|gameId, playMode:", gameId, playMode, caller=cls)

        isReconnect = False

        # 单开, 无论何时quick_start进入都检查loc
        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, clientId, gameId)
            ftlog.debug('old client, checkUserLoc->', loc, caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
                if lgameId == gameId and lroomId > 0:
                    roomId = lroomId
                    tableId = ltableId
                    isReconnect = True
                    ftlog.debug('old client, reset roomId, tableId->', roomId, tableId, caller=cls)

        if (not isReconnect) and roomId > 0 and tableId > 0:
            reason = cls._canQuickEnterRoom(userId, gameId, roomId, 1)
            if reason != TYRoom.ENTER_ROOM_REASON_OK:
                cls._onEnterRoomFailed(msg, reason, userId, gameId, clientId, roomId)
                return

        if roomId == 0:  # 玩家点击快速开始
            chosenRoomId, checkResult = cls._chooseRoom(userId, gameId, playMode)
            ftlog.info("after choose room", "|userId, chosenRoomId, checkResult:", userId, chosenRoomId, checkResult,
                       caller=cls)
            if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                # 找到合适的房间 根据roomId找到合适的table

                TYRoomMixin.queryRoomQuickStartReq(msg, chosenRoomId, 0)  # 请求转给GR
            else:
                candidateRoomIds = cls._getCandidateRoomIds(gameId, playMode)
                if candidateRoomIds:
                    rid = candidateRoomIds[0]
                    msg.setParam('candidateRoomId', rid)
                cls._onEnterRoomFailed(msg, checkResult, userId, clientId, roomId)
            return

        if tableId == 0:  # 玩家只选择了房间
            bigRoomId = gdata.getBigRoomId(roomId)
            if bigRoomId == 0:
                cls._onEnterRoomFailed(msg, TYRoom.ENTER_ROOM_REASON_ROOM_ID_ERROR, userId, gameId, clientId, roomId)
                return
            ctrRoomIds = gdata.bigRoomidsMap()[bigRoomId]
            ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]

            reason = cls._canQuickEnterRoom(userId, gameId, ctrlRoomId, 1)
            if reason == TYRoom.ENTER_ROOM_REASON_OK:
                TYRoomMixin.queryRoomQuickStartReq(msg, ctrlRoomId, 0)  # 请求转给GR或GT
            else:
                cls._onEnterRoomFailed(msg, reason, userId, gameId, clientId, roomId)
            return

        if tableId == roomId * 10000:  # 玩家在队列里断线重连
            TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId)  # 请求转给GR
            return

        onlineSeat = onlinedata.getOnlineLocSeatId(userId, roomId, tableId)

        if onlineSeat:
            extParam = {}
            extParam['seatId'] = onlineSeat
            moParams = msg.getKey('params')
            for k, v in moParams.items():
                if not k in extParam:
                    extParam[k] = v
            ftlog.debug('extParam=', extParam)
            TYRoomMixin.querySitReq(userId, roomId, tableId, clientId, extParam)  # 玩家断线重连,请求转给GT
        else:  # 玩家选择了桌子, 
            shadowRoomId = tableId / 10000
            ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
            TYRoomMixin.queryRoomQuickStartReq(msg, ctrRoomId, tableId, shadowRoomId=shadowRoomId)  # 请求转给GR
Ejemplo n.º 32
0
    def createTableQuickStart(cls, msg, itemParams, userId, roomId, tableId, playMode, clientId):
        """
        UT server中处理来自客户端的create_table请求
        Args:
            msg
                cmd : create_table
                if roomId == 0:
                    表示玩家创建房间,服务器为玩家选择房间,然后将请求转给GR

                if roomId > 0 and tableId == 0 :
                    表示玩家选择了房间,将请求转给GR

                if roomId > 0 and tableId == roomId * 10000 :
                    表示玩家在队列里断线重连,将请求转给GR

                if roomId > 0 and tableId > 0:
                    if onlineSeatId > 0:
                        表示玩家在牌桌里断线重连,将请求转给GT
                    else:
                        表示玩家选择了桌子,将请求转给GR
        """
        assert isinstance(userId, int) and userId > 0
        assert isinstance(roomId, int) and roomId >= 0
        assert isinstance(tableId, int) and tableId >= 0
        ftlog.debug("<< |clientId:", clientId,
                    "|userId, roomId, tableId:", userId, roomId, tableId,
                    "|gameId, playMode:", playMode, caller=cls)

        isReconnect = False
        gameId = msg.getResult('gameId')

        # 单开, 无论何时quick_start进入都检查loc
        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, gameId)
            ftlog.debug('old client, checkUserLoc->', loc, caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
                if lgameId == gameId and lroomId > 0:
                    roomId = lroomId
                    tableId = ltableId
                    isReconnect = True
                    ftlog.debug('old client, reset roomId, tableId->', roomId, tableId, caller=cls)

        if (not isReconnect) and roomId > 0 and tableId > 0:
            reason = cls._canQuickEnterCreateRoom(userId, gameId, roomId)
            if reason != TYRoom.ENTER_ROOM_REASON_OK:
                cls._onEnterCreateRoomFailed(reason, userId, gameId, clientId, roomId)
                return
        tempShadowRoomId = 0
        if roomId == 0:  # 第一个玩家创建房间牌桌
            chosenRoomId, checkResult = cls._chooseCreateRoom(userId, gameId, playMode)
            ftlog.info("after choose room", "|userId, chosenRoomId, checkResult:", userId, chosenRoomId, checkResult,
                       caller=cls)
            if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                # 得到房间ID,找合适的tableId
                roomDef = gdata.roomIdDefineMap()[chosenRoomId]
                shadowRoomIds = roomDef.shadowRoomIds
                if shadowRoomIds:
                    for shadowRoomId in shadowRoomIds:
                        tableId = table_rpc.getTableByRoomId(shadowRoomId)
                        if isinstance(tableId, int) and tableId > 0:
                            tempShadowRoomId = shadowRoomId
                            break

                shadowRoomId = tableId / 10000
                if shadowRoomId == tempShadowRoomId:  # 验证
                    ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
                    TYRoomMixin.queryRoomQuickStartReq(msg, ctrRoomId, tableId, shadowRoomId=shadowRoomId)  # 请求转给GR
                    return
                else:
                    cls._onEnterCreateRoomFailed(checkResult, userId, gameId, clientId, roomId)
                    return
            else:
                cls._onEnterCreateRoomFailed(checkResult, userId, gameId, clientId, roomId)
                return
        else:
            onlineSeat = onlinedata.getOnlineLocSeatId(userId, gameId, roomId, tableId)
            if onlineSeat:
                extParam = {}
                extParam['seatId'] = onlineSeat
                moParams = msg.getKey('params')
                for k, v in moParams.items():
                    if not k in extParam:
                        extParam[k] = v
                ftlog.debug('extParam=', extParam)
                TYRoomMixin.querySitReq(userId, roomId, tableId, clientId, extParam)  # 玩家断线重连,请求转给GT
                return
        if tableId == roomId * 10000:  # 玩家在队列里断线重连
            TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId)  # 请求转给GR
            return
        # 玩家选择了桌子,进桌
        shadowRoomId = tableId / 10000
        ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
        TYRoomMixin.queryRoomQuickStartReq(msg, ctrRoomId, tableId, shadowRoomId=shadowRoomId)  # 请求转给GR
Ejemplo n.º 33
0
    def doCreateTable(self, userId, gameId, clientId, roomId0, tableId0, playMode):
        """
        房主创建牌桌
        """
        if not playMode:
            ftlog.error('game_handler, cat not create table without playMode...')

        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        lgameId, lroomId, ltableId, lseatId = loc.split('.')
        lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
        if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >= 0:
            ftlog.warn('create_table error, user in table', lgameId, lroomId, ltableId, lseatId)
            sendPopTipMsg(userId, "请稍候,正在进桌...")
            config = {
                "type": "quickstart",
                "pluginParams": {
                    "roomId": lroomId,
                    "tableId": ltableId,
                    "seatId": lseatId
                }
            }
            todotask = TodoTaskEnterGameNew(lgameId, config)
            mo = MsgPack()
            mo.setCmd('todo_tasks')
            mo.setResult('gameId', gameId)
            mo.setResult('pluginId', lgameId)
            mo.setResult('userId', userId)
            mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask))
            router.sendToUser(mo, userId)
        elif self._canEnterGame(userId, gameId):
            # 保存建桌时间戳
            gamedata.setGameAttr(userId, gameId, 'createTableTime', pktimestamp.getCurrentTimestamp())

            msg = runcmd.getMsgPack()
            itemParams = msg.getParam("itemParams")
            # cardCount为总局数
            if "cardCount" in itemParams:
                cardCountId = itemParams.get('cardCount', 0)
                cardCountConfig = majiang_conf.getCreateTableConfig(gameId, playMode, 'cardCount', cardCountId)
                fangka_count = cardCountConfig.get('fangka_count', 1)
                ftlog.debug('MajiangCreateTable.create_table fangka_count:', fangka_count)

                playerCount = 4
                playerTypeId = itemParams.get('playerType', 1)
                if playerTypeId:
                    playerTypeConfig = majiang_conf.getCreateTableConfig(gameId, playMode, 'playerType', playerTypeId)
                    playerCount = playerTypeConfig.get('count', 4)
                    ftlog.debug('MajiangCreateTable.create_table playerCount:', playerCount)

                msg.setParam('isCreateTable', 1)  # 标记创建的桌子是 自建桌
                from poker.entity.game.rooms.room import TYRoom
                roomId, checkResult = MajiangCreateTable._chooseCreateRoom(userId, gameId, playMode, playerCount)
                ftlog.debug('MajiangCreateTable._chooseCreateRoom roomId:', roomId, ' checkResult:', checkResult)

                if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                    msg = runcmd.getMsgPack()
                    msg.setCmdAction("room", "create_table")
                    msg.setParam("roomId", roomId)
                    msg.setParam("itemParams", itemParams)
                    msg.setParam('needFangka', fangka_count)
                    ftlog.debug('MajiangCreateTable._chooseCreateRoom send message to room:', msg)

                    router.sendRoomServer(msg, roomId)
                else:
                    sendPopTipMsg(userId, "暂时无法创建请稍后重试")
            else:
                sendPopTipMsg(userId, "暂时无法创建请稍后重试")

            if router.isQuery():
                mo = runcmd.newOkMsgPack(1)
                router.responseQurery(mo, '', str(userId))
        else:
            ftlog.info('majiang2 game_handler, ignore enter game request...')
Ejemplo n.º 34
0
    def doCreateTable(self,
                      userId,
                      gameId,
                      clientId,
                      roomId0,
                      tableId0,
                      playMode,
                      hasRobot=0):

        #临时硬编码,解决91晃晃提审问题
        if gameId == 791 and playMode == "queshou-lianjiang" and clientId == "IOS_3.901_weixin.appStore,weixinPay.0-hall791.queshou.iostsljmj":
            hasRobot = 1
        if gameId == 790 and playMode == 'luosihu-luosihuts' and clientId == "IOS_3.901_weixin.appStore,weixinPay.0-hall790.laodao.iostsxjmj":
            hasRobot = 1
        """房主创建牌桌"""
        if not playMode:
            ftlog.error(
                'game_handler, cat not create table without playMode...')

        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        lgameId, lroomId, ltableId, lseatId = loc.split('.')
        lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
            lgameId, lroomId, ltableId, lseatId)
        if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >= 0:
            ftlog.warn('create_table error, user in table', lgameId, lroomId,
                       ltableId, lseatId)
            sendPopTipMsg(userId, "请稍候,正在进桌...")
            config = {
                "type": "quickstart",
                "pluginParams": {
                    "roomId": lroomId,
                    "tableId": ltableId,
                    "seatId": lseatId
                }
            }
            todotask = TodoTaskEnterGameNew(lgameId, config)
            mo = MsgPack()
            mo.setCmd('todo_tasks')
            mo.setResult('gameId', gameId)
            mo.setResult('pluginId', lgameId)
            mo.setResult('userId', userId)
            mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask))
            router.sendToUser(mo, userId)
        elif self._canEnterGame(userId, gameId):
            # 保存建桌时间戳
            gamedata.setGameAttr(userId, gameId, 'createTableTime',
                                 pktimestamp.getCurrentTimestamp())

            msg = runcmd.getMsgPack()
            itemParams = msg.getParam("itemParams")

            playerCount = 4
            playerTypeId = itemParams.get(MFTDefine.PLAYER_TYPE, 1)
            playerTypeConfig = majiang_conf.getCreateTableConfig(
                gameId, playMode, MFTDefine.PLAYER_TYPE, playerTypeId)
            if not playerTypeConfig:
                sendPopTipMsg(userId, '人数配置有误,请稍后重试')
                return

            playerCount = playerTypeConfig.get('count', 4)
            ftlog.debug('MajiangCreateTable.create_table playerCount:',
                        playerCount)
            cardCountKey = playerTypeConfig.get(MFTDefine.CARD_COUNT,
                                                MFTDefine.CARD_COUNT)

            cardCountId = itemParams.get(cardCountKey, 0)
            cardCountConfig = majiang_conf.getCreateTableConfig(
                gameId, playMode, cardCountKey, cardCountId)
            if not cardCountConfig:
                sendPopTipMsg(userId, '房卡配置有误,请稍后重试')
                return

            if hasRobot == 1 and 'hasRobot' in cardCountConfig:
                cardCountConfig = cardCountConfig.get('hasRobot', {})
                ftlog.debug('MajiangCreateTable.create_table hasRobot == 1:')
            fangka_count = cardCountConfig.get('fangka_count', 1)
            ftlog.debug('MajiangCreateTable.create_table fangka_count:',
                        fangka_count, ' cardCountConfig:', cardCountConfig)

            msg.setParam('isCreateTable', 1)  #标记创建的桌子是 自建桌
            from poker.entity.game.rooms.room import TYRoom
            '''
            根据五个因素筛选合适的房间
            1)gameId         游戏ID
            2)playMode       游戏玩法
            3)playerCount    玩家个数
            4)hasRobot       是否有机器人
            5)itemId         房卡道具
            '''
            itemId = hall_fangka.queryFangKaItem(gameId, userId, clientId)
            if itemId:
                ftlog.debug(
                    'MajiangCreateTable._chooseCreateRoom fangKa itemId:',
                    itemId)
            roomId, checkResult = MajiangCreateTable._chooseCreateRoom(
                userId, gameId, playMode, playerCount, hasRobot, itemId)
            ftlog.debug('MajiangCreateTable._chooseCreateRoom roomId:', roomId,
                        ' checkResult:', checkResult)

            if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                msg = runcmd.getMsgPack()
                msg.setCmdAction("room", "create_table")
                msg.setParam("roomId", roomId)
                msg.setParam("itemParams", itemParams)
                msg.setParam('needFangka', fangka_count)
                ftlog.debug(
                    'MajiangCreateTable._chooseCreateRoom send message to room:',
                    msg)

                router.sendRoomServer(msg, roomId)
            else:
                sendPopTipMsg(userId, "暂时无法创建请稍后重试")

            if router.isQuery():
                mo = runcmd.newOkMsgPack(1)
                router.responseQurery(mo, '', str(userId))
        else:
            ftlog.info('majiang2 game_handler, ignore enter game request...')
Ejemplo n.º 35
0
    def onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, playMode,
                        clientId):
        '''UT server中处理来自客户端的quick_start请求
        Args:
            msg
                cmd : quick_start
                if roomId == 0:
                    表示快速开始,服务器为玩家选择房间,然后将请求转给GR

                if roomId > 0 and tableId == 0 :
                    表示玩家选择了房间,将请求转给GR

                if roomId > 0 and tableId == roomId * 10000 :
                    表示玩家在队列里断线重连,将请求转给GR

                if roomId > 0 and tableId > 0:
                    if onlineSeatId > 0:
                        表示玩家在牌桌里断线重连,将请求转给GT
                    else:
                        表示玩家选择了桌子,将请求转给GR
        '''
        assert isinstance(userId, int) and userId > 0
        assert isinstance(roomId, int) and roomId >= 0
        assert isinstance(tableId, int) and tableId >= 0

        if ftlog.is_debug():
            ftlog.debug("<< |clientId:",
                        clientId,
                        "|userId, roomId, tableId:",
                        userId,
                        roomId,
                        tableId,
                        "|gameId, playMode:",
                        gameId,
                        playMode,
                        caller=cls)

        # 单开, 无论何时quick_start进入都检查loc
        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, clientId, gameId)
            if ftlog.is_debug():
                ftlog.debug('old client, checkUserLoc->', loc, caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(
                    lgameId, lroomId, ltableId, lseatId)

                if lgameId == gameId and lroomId > 0:
                    ftlog.debug('onCmdQuickStart re-connected |userId, loc:',
                                userId,
                                loc,
                                '|roomId, tableId:',
                                roomId,
                                tableId,
                                caller=cls)
                    roomId = lroomId
                    tableId = ltableId
                    msg.setParam('isReConnected', True)
                    if ftlog.is_debug():
                        ftlog.debug('old client, reset roomId, tableId->',
                                    roomId,
                                    tableId,
                                    caller=cls)

        if roomId == 0:  # 玩家点击快速开始
            chosenRoomId, checkResult = cls._chooseRoom(
                userId, gameId, playMode)
            ftlog.debug("after choose room",
                        "|userId, chosenRoomId, checkResult:",
                        userId,
                        chosenRoomId,
                        checkResult,
                        caller=cls)
            if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                TYRoomMixin.queryRoomQuickStartReq(msg, chosenRoomId,
                                                   0)  # 请求转给GR
            else:
                candidateRoomIds = cls._getCandidateRoomIds(gameId, playMode)
                if candidateRoomIds:
                    rid = candidateRoomIds[0]
                    msg.setParam('candidateRoomId', rid)
                cls._onEnterRoomFailed(msg, checkResult, userId, clientId,
                                       roomId)
                return

        bigRoomId = gdata.getBigRoomId(roomId)
        ftlog.debug('bigRoomId:', bigRoomId)
        if bigRoomId == 0:
            cls._onEnterRoomFailed(msg, TYRoom.ENTER_ROOM_REASON_ROOM_ID_ERROR,
                                   userId, clientId, roomId)
            return

        if strutil.getGameIdFromBigRoomId(bigRoomId) != gameId:
            cls._onEnterRoomFailed(msg, TYRoom.ENTER_ROOM_REASON_ROOM_ID_ERROR,
                                   userId, clientId, roomId)
            return

        if tableId == 0:  # 玩家只选择了房间
            if gameId == 6 and roomId != bigRoomId:
                ctrlRoomId = gdata.roomIdDefineMap()[roomId].parentId or roomId
                queryRoomId = roomId
            else:
                ctrRoomIds = gdata.bigRoomidsMap()[bigRoomId]
                ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]
                queryRoomId = ctrlRoomId
            reason = cls._canQuickEnterRoom(userId, gameId, ctrlRoomId, 1)
            if reason == TYRoom.ENTER_ROOM_REASON_OK:
                if gameId == 6:
                    TYRoomMixin.queryRoomQuickStartReq(msg, queryRoomId,
                                                       0)  # 请求转给GR或GT
                else:
                    TYRoomMixin.queryRoomQuickStartReq(msg, ctrlRoomId,
                                                       0)  # 请求转给GR或GT
            elif reason == TYRoom.ENTER_ROOM_REASON_LESS_MIN or reason == TYRoom.ENTER_ROOM_REASON_GREATER_MAX:
                if gameId == 6:
                    innerTable = msg.getParam("innerTable",
                                              0)  # innerTable 区分不同版本弹窗
                    if innerTable == 1:
                        roomDef = gdata.roomIdDefineMap()[ctrlRoomId]
                        playMode = roomDef.configure.get('playMode', None)
                        if ftlog.is_debug():
                            ftlog.debug('enter_less_min userId=', userId,
                                        'roomId=', ctrlRoomId, 'msg=', msg,
                                        'playmode=', playMode)
                        msgpack = MsgPack()
                        msgpack.setCmd("quick_start")
                        msgpack.setParam("userId", userId)
                        msgpack.setParam("gameId", gameId)
                        msgpack.setParam("clientId", clientId)
                        msgpack.setParam("innerTable", 1)
                        msgpack.setParam("apiver", msg.getParam("apiver",
                                                                3.7))  # 驱动
                        cls.onCmdQuickStart(msgpack, userId, gameId, 0, 0,
                                            playMode, clientId)
                        if ftlog.is_debug():
                            ftlog.debug('reenter_less_min userId=', userId,
                                        'roomId=', ctrlRoomId, 'msgpack=',
                                        msgpack.pack())
                    else:
                        cls._onEnterRoomFailed(msg, reason, userId, clientId,
                                               roomId)
                else:
                    cls._onEnterRoomFailed(msg, reason, userId, clientId,
                                           roomId)
            else:
                cls._onEnterRoomFailed(msg, reason, userId, clientId, roomId)
            return

        if tableId == roomId * 10000:  # 玩家在队列里断线重连 4400150010001
            TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId)  # 请求转给GR
            return

        onlineSeat = onlinedata.getOnlineLocSeatId(userId, roomId, tableId)

        if onlineSeat:
            if onlineSeat == gdata.roomIdDefineMap(
            )[roomId].configure['tableConf']['maxSeatN'] + 1:
                # 牌桌里旁观的玩家断线重连,请求转给GT
                TYRoomMixin.sendTableCallObserveReq(userId, roomId, tableId,
                                                    clientId)
            else:
                # 牌桌里坐着的玩家断线重连,请求转给GT
                # TYRoomMixin.querySitReq(userId, roomId, tableId, clientId) # GT人多时会有超时异常
                TYRoomMixin.sendSitReq(userId, roomId, tableId, clientId)
        else:  # 玩家选择了桌子,
            shadowRoomId = tableId / 10000
            ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
            TYRoomMixin.queryRoomQuickStartReq(
                msg, ctrRoomId, tableId, shadowRoomId=shadowRoomId)  # 请求转给GR
Ejemplo n.º 36
0
def _getFriendGameInfo(userId, gameIds, for_level_info, for_winchip, for_online_info=1):
    uid = int(userId)
    datas = {}
    gid, rid, tid, sid = 0, 0, 0, 0
    state = daoconst.OFFLINE
    if for_online_info:
        loclist = onlinedata.getOnlineLocList(uid)
        state = onlinedata.getOnlineState(uid)
        if len(loclist) > 0:
            _rid, _tid, _sid = loclist[0]
            # gid表示用户在哪个游戏中
            gid = strutil.getGameIdFromInstanceRoomId(_rid)
            # 检查是否可加入游戏
            if TYGame(gid).canJoinGame(userId, _rid, _tid, _sid):
                # rid/tid/sid表示用户所在的游戏是否可加入游戏
                # 分享出来的都是可以加入游戏的牌桌信息
                rid = _rid
                tid = _tid
                sid = _sid
            if ftlog.is_debug():
                ftlog.debug('getFriendGameInfo userId:', userId, ' gameId:', gid, ' roomId:', _rid, ' tableId:', _tid,
                            ' seatId:', _sid, ' can not join game....')
        if state == daoconst.OFFLINE:
            offline_time = gamedata.getGameAttr(uid, HALL_GAMEID, 'offlineTime')
            if not offline_time:  # 取不到离线时间,取上线时间
                offline_time = userdata.getAttr(uid, 'authorTime')
            if offline_time:
                offline_time = pktimestamp.parseTimeMs(offline_time)
                delta = datetime.now() - offline_time
                delta = delta.days * 24 * 60 + delta.seconds / 60  # 分钟数
            else:  # 异常情况
                delta = 24 * 60
            datas['offline_time'] = delta if delta > 0 else 1
        if rid > 0:
            try:
                room = gdata.roomIdDefineMap().get(rid, None)
                if room:
                    datas['room_name'] = room.configure['name']
            except:
                ftlog.error()
    # 构造回传给SDK的游戏数据
    datas.update({'uid': uid, 'gid': gid, 'rid': rid, 'tid': tid, 'sid': sid, 'state': state})

    if for_level_info:
        datas['level_game_id'] = 0
        datas['level'] = 0
        datas['level_pic'] = ''
        try:
            for gameId in gameIds:
                if gameId not in gdata.games():
                    continue
                dashifen_info = gdata.games()[gameId].getDaShiFen(uid, '')
                if dashifen_info:
                    level = dashifen_info['level']
                    if level > 0 and level > datas['level']:
                        datas['level_game_id'] = gameId
                        datas['level'] = level
                        level_pic = dashifen_info.get('picbig')
                        datas['level_pic'] = level_pic if level_pic else dashifen_info.get('pic')
        except:
            ftlog.error()

    if for_winchip:
        datas['winchip'] = 0
        datas['winchips'] = 0
        try:
            for gameId in gameIds:
                winchips, todaychips = gamedata.getGameAttrs(userId, gameId, ['winchips', 'todaychips'], False)
                winchips = strutil.parseInts(winchips)
                yest_winchip = 0
                todaychips = strutil.loads(todaychips, ignoreException=True)
                if todaychips and 'today' in todaychips and 'chips' in todaychips and 'last' in todaychips:
                    if pktimestamp.formatTimeDayInt() == todaychips['today']:
                        yest_winchip = todaychips['last']
                    elif pktimestamp.formatTimeYesterDayInt() == todaychips['today']:
                        yest_winchip = todaychips['chips']
                datas['winchip'] += yest_winchip
                datas['winchips'] += winchips
        except:
            ftlog.error()
    return datas
Ejemplo n.º 37
0
    def onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, playMode, clientId):
        '''UT server中处理来自客户端的quick_start请求  
        Args:
            msg
                cmd : quick_start
                if roomId == 0:
                    表示快速开始,服务器为玩家选择房间,然后将请求转给GR
                    
                if roomId > 0 and tableId == 0 : 
                    表示玩家选择了房间,将请求转给GR
                    
                if roomId > 0 and tableId == roomId * 10000 :
                    表示玩家在队列里断线重连,将请求转给GR
                    
                if roomId > 0 and tableId > 0:
                    if onlineSeatId > 0: 
                        表示玩家在牌桌里断线重连,将请求转给GT
                    else:
                        表示玩家选择了桌子,将请求转给GR
        '''
        assert isinstance(userId, int) and userId > 0
        assert isinstance(roomId, int) and roomId >= 0
        assert isinstance(tableId, int) and tableId >= 0

        if ftlog.is_debug():
            ftlog.debug("<< |clientId:", clientId,
                        "|userId, roomId, tableId:", userId, roomId, tableId,
                        "|gameId, playMode:", gameId, playMode, caller=cls)

        # 单开, 无论何时quick_start进入都检查loc
        if not pokerconf.isOpenMoreTable(clientId):
            loc = onlinedata.checkUserLoc(userId, clientId, gameId)
            if ftlog.is_debug():
                ftlog.debug('old client, checkUserLoc->', loc, caller=cls)
            if isinstance(loc, basestring):
                lgameId, lroomId, ltableId, lseatId = loc.split('.')
                lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
                if lgameId == gameId and lroomId > 0:
                    ftlog.debug('onCmdQuickStart re-connected |userId, loc:', userId, loc,
                                '|roomId, tableId:', roomId, tableId, caller=cls)
                    roomId = lroomId
                    tableId = ltableId
                    msg.setParam('isReConnected', True)
                    if ftlog.is_debug():
                        ftlog.debug('old client, reset roomId, tableId->', roomId, tableId, caller=cls)

        if roomId == 0:  # 玩家点击快速开始
            chosenRoomId, checkResult = cls._chooseRoom(userId, gameId, playMode)
            ftlog.debug("after choose room", "|userId, chosenRoomId, checkResult:", userId, chosenRoomId, checkResult,
                        caller=cls)
            if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                TYRoomMixin.queryRoomQuickStartReq(msg, chosenRoomId, 0)  # 请求转给GR
            else:
                candidateRoomIds = cls._getCandidateRoomIds(gameId, playMode)
                if candidateRoomIds:
                    rid = candidateRoomIds[0]
                    msg.setParam('candidateRoomId', rid)
                cls._onEnterRoomFailed(msg, checkResult, userId, clientId, roomId)
            return

        bigRoomId = gdata.getBigRoomId(roomId)
        ftlog.debug('bigRoomId:', bigRoomId)
        if bigRoomId == 0:
            cls._onEnterRoomFailed(msg, TYRoom.ENTER_ROOM_REASON_ROOM_ID_ERROR, userId, clientId, roomId)
            return

        if strutil.getGameIdFromBigRoomId(bigRoomId) != gameId:
            cls._onEnterRoomFailed(msg, TYRoom.ENTER_ROOM_REASON_ROOM_ID_ERROR, userId, clientId, roomId)
            return

        if tableId == 0:  # 玩家只选择了房间
            if gameId == 6 and roomId != bigRoomId:
                ctrlRoomId = gdata.roomIdDefineMap()[roomId].parentId
                queryRoomId = roomId
            else:
                ctrRoomIds = gdata.bigRoomidsMap()[bigRoomId]
                ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]
                queryRoomId = ctrlRoomId
            reason = cls._canQuickEnterRoom(userId, gameId, ctrlRoomId, 1)
            if reason == TYRoom.ENTER_ROOM_REASON_OK:
                if gameId == 6:
                    TYRoomMixin.queryRoomQuickStartReq(msg, queryRoomId, 0)  # 请求转给GR或GT
                else:
                    TYRoomMixin.queryRoomQuickStartReq(msg, ctrlRoomId, 0)  # 请求转给GR或GT
            elif reason == TYRoom.ENTER_ROOM_REASON_LESS_MIN or reason == TYRoom.ENTER_ROOM_REASON_GREATER_MAX:
                if gameId == 6:
                    innerTable = msg.getParam("innerTable", 0)  # innerTable 区分不同版本弹窗
                    if innerTable == 1:
                        roomDef = gdata.roomIdDefineMap()[ctrlRoomId]
                        playMode = roomDef.configure.get('playMode', None)
                        if ftlog.is_debug():
                            ftlog.debug('enter_less_min userId=', userId, 'roomId=', ctrlRoomId, 'msg=', msg,
                                        'playmode=', playMode)
                        msgpack = MsgPack()
                        msgpack.setCmd("quick_start")
                        msgpack.setParam("userId", userId)
                        msgpack.setParam("gameId", gameId)
                        msgpack.setParam("clientId", clientId)
                        msgpack.setParam("innerTable", 1)
                        msgpack.setParam("apiver", msg.getParam("apiver", 3.7))
                        cls.onCmdQuickStart(msgpack, userId, gameId, 0, 0, playMode, clientId)
                        if ftlog.is_debug():
                            ftlog.debug('reenter_less_min userId=', userId, 'roomId=', ctrlRoomId, 'msgpack=',
                                        msgpack.pack())
                    else:
                        cls._onEnterRoomFailed(msg, reason, userId, clientId, roomId)
                else:
                    cls._onEnterRoomFailed(msg, reason, userId, clientId, roomId)
            else:
                cls._onEnterRoomFailed(msg, reason, userId, clientId, roomId)
            return

        if tableId == roomId * 10000:  # 玩家在队列里断线重连
            TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId)  # 请求转给GR
            return

        onlineSeat = onlinedata.getOnlineLocSeatId(userId, roomId, tableId)

        if onlineSeat:
            if onlineSeat == gdata.roomIdDefineMap()[roomId].configure['tableConf']['maxSeatN'] + 1:
                # 牌桌里旁观的玩家断线重连,请求转给GT
                TYRoomMixin.sendTableCallObserveReq(userId, roomId, tableId, clientId)
            else:
                # 牌桌里坐着的玩家断线重连,请求转给GT
                # TYRoomMixin.querySitReq(userId, roomId, tableId, clientId) # GT人多时会有超时异常
                TYRoomMixin.sendSitReq(userId, roomId, tableId, clientId)
        else:  # 玩家选择了桌子, 
            shadowRoomId = tableId / 10000
            ctrRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId
            TYRoomMixin.queryRoomQuickStartReq(msg, ctrRoomId, tableId, shadowRoomId=shadowRoomId)  # 请求转给GR
Ejemplo n.º 38
0
    def doCreateTable(self, userId, gameId, clientId, roomId0, tableId0, playMode, hasRobot = 0):
        
        #临时硬编码,解决91晃晃提审问题
        if gameId==791 and playMode=="queshou-lianjiang" and clientId=="IOS_3.901_weixin.appStore,weixinPay.0-hall791.queshou.iostsljmj":
            hasRobot=1
	if gameId == 790 and playMode == 'luosihu-luosihuts' and clientId=="IOS_3.901_weixin.appStore,weixinPay.0-hall790.laodao.iostsxjmj":
	    hasRobot=1
        """房主创建牌桌"""
        if not playMode:
            ftlog.error('game_handler, cat not create table without playMode...')
        
        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        lgameId, lroomId, ltableId, lseatId = loc.split('.')
        lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
        if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >=0:
            ftlog.warn('create_table error, user in table',lgameId, lroomId, ltableId, lseatId)
            sendPopTipMsg(userId, "请稍候,正在进桌...")
            config = {
                      "type":"quickstart",
                      "pluginParams": {
                          "roomId": lroomId,
                          "tableId": ltableId,
                          "seatId": lseatId
                          }
                      }
            todotask = TodoTaskEnterGameNew(lgameId, config)
            mo = MsgPack()
            mo.setCmd('todo_tasks')
            mo.setResult('gameId', gameId)
            mo.setResult('pluginId', lgameId)
            mo.setResult('userId', userId)
            mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask))
            router.sendToUser(mo, userId)
        elif self._canEnterGame(userId, gameId):
            # 保存建桌时间戳
            gamedata.setGameAttr(userId, gameId, 'createTableTime', pktimestamp.getCurrentTimestamp())
            
            msg = runcmd.getMsgPack()
            itemParams = msg.getParam("itemParams")
            
            playerCount = 4
            playerTypeId = itemParams.get(MFTDefine.PLAYER_TYPE, 1)
            playerTypeConfig = majiang_conf.getCreateTableConfig(gameId, playMode, MFTDefine.PLAYER_TYPE, playerTypeId)
            if not playerTypeConfig:
                sendPopTipMsg(userId, '人数配置有误,请稍后重试')
                return
            
            playerCount = playerTypeConfig.get('count', 4)
            ftlog.debug('MajiangCreateTable.create_table playerCount:', playerCount)
            cardCountKey = playerTypeConfig.get(MFTDefine.CARD_COUNT, MFTDefine.CARD_COUNT)

            cardCountId = itemParams.get(cardCountKey, 0)
            cardCountConfig = majiang_conf.getCreateTableConfig(gameId, playMode, cardCountKey, cardCountId)
            if not cardCountConfig:
                sendPopTipMsg(userId, '房卡配置有误,请稍后重试')
                return
            
            if hasRobot == 1 and 'hasRobot' in cardCountConfig:
                cardCountConfig = cardCountConfig.get('hasRobot', {})
                ftlog.debug('MajiangCreateTable.create_table hasRobot == 1:')
            fangka_count = cardCountConfig.get('fangka_count', 1)
            ftlog.debug('MajiangCreateTable.create_table fangka_count:', fangka_count
                        , ' cardCountConfig:', cardCountConfig)
            
            msg.setParam('isCreateTable', 1) #标记创建的桌子是 自建桌
            from poker.entity.game.rooms.room import TYRoom
            '''
            根据五个因素筛选合适的房间
            1)gameId         游戏ID
            2)playMode       游戏玩法
            3)playerCount    玩家个数
            4)hasRobot       是否有机器人
            5)itemId         房卡道具
            '''
            itemId = hall_fangka.queryFangKaItem(gameId, userId, clientId)
            if itemId:
                ftlog.debug('MajiangCreateTable._chooseCreateRoom fangKa itemId:', itemId)
            roomId, checkResult = MajiangCreateTable._chooseCreateRoom(userId, gameId, playMode, playerCount, hasRobot, itemId)
            ftlog.debug('MajiangCreateTable._chooseCreateRoom roomId:', roomId, ' checkResult:', checkResult)

            if checkResult==TYRoom.ENTER_ROOM_REASON_OK:
                msg = runcmd.getMsgPack()
                msg.setCmdAction("room", "create_table")
                msg.setParam("roomId", roomId)
                msg.setParam("itemParams", itemParams)
                msg.setParam('needFangka', fangka_count)
                ftlog.debug('MajiangCreateTable._chooseCreateRoom send message to room:', msg)

                router.sendRoomServer(msg, roomId)
            else:
                sendPopTipMsg(userId, "暂时无法创建请稍后重试")
                
            if router.isQuery() :
                mo = runcmd.newOkMsgPack(1)
                router.responseQurery(mo, '', str(userId))
        else:
            ftlog.info('majiang2 game_handler, ignore enter game request...')
Ejemplo n.º 39
0
def _getFriendGameInfo(userId,
                       gameIds,
                       for_level_info,
                       for_winchip,
                       for_online_info=1):
    uid = int(userId)
    datas = {}
    gid, rid, tid, sid = 0, 0, 0, 0
    state = daoconst.OFFLINE
    if for_online_info:
        loclist = onlinedata.getOnlineLocList(uid)
        state = onlinedata.getOnlineState(uid)
        if len(loclist) > 0:
            _rid, _tid, _sid = loclist[0]
            # gid表示用户在哪个游戏中
            gid = strutil.getGameIdFromInstanceRoomId(_rid)
            # 检查是否可加入游戏
            if TYGame(gid).canJoinGame(userId, _rid, _tid, _sid):
                # rid/tid/sid表示用户所在的游戏是否可加入游戏
                # 分享出来的都是可以加入游戏的牌桌信息
                rid = _rid
                tid = _tid
                sid = _sid
            if ftlog.is_debug():
                ftlog.debug('getFriendGameInfo userId:', userId, ' gameId:',
                            gid, ' roomId:', _rid, ' tableId:', _tid,
                            ' seatId:', _sid, ' can not join game....')
        if state == daoconst.OFFLINE:
            offline_time = gamedata.getGameAttr(uid, HALL_GAMEID,
                                                'offlineTime')
            if not offline_time:  # 取不到离线时间,取上线时间
                offline_time = userdata.getAttr(uid, 'authorTime')
            if offline_time:
                offline_time = pktimestamp.parseTimeMs(offline_time)
                delta = datetime.now() - offline_time
                delta = delta.days * 24 * 60 + delta.seconds / 60  # 分钟数
            else:  # 异常情况
                delta = 24 * 60
            datas['offline_time'] = delta if delta > 0 else 1
        if rid > 0:
            try:
                room = gdata.roomIdDefineMap().get(rid, None)
                if room:
                    datas['room_name'] = room.configure['name']
            except:
                ftlog.error()
    # 构造回传给SDK的游戏数据
    datas.update({
        'uid': uid,
        'gid': gid,
        'rid': rid,
        'tid': tid,
        'sid': sid,
        'state': state
    })

    if for_level_info:
        datas['level_game_id'] = 0
        datas['level'] = 0
        datas['level_pic'] = ''
        try:
            for gameId in gameIds:
                if gameId not in gdata.games():
                    continue
                dashifen_info = gdata.games()[gameId].getDaShiFen(uid, '')
                if dashifen_info:
                    level = dashifen_info['level']
                    if level > 0 and level > datas['level']:
                        datas['level_game_id'] = gameId
                        datas['level'] = level
                        level_pic = dashifen_info.get('picbig')
                        datas[
                            'level_pic'] = level_pic if level_pic else dashifen_info.get(
                                'pic')
        except:
            ftlog.error()

    if for_winchip:
        datas['winchip'] = 0
        datas['winchips'] = 0
        try:
            for gameId in gameIds:
                winchips, todaychips = gamedata.getGameAttrs(
                    userId, gameId, ['winchips', 'todaychips'], False)
                winchips = strutil.parseInts(winchips)
                yest_winchip = 0
                todaychips = strutil.loads(todaychips, ignoreException=True)
                if todaychips and 'today' in todaychips and 'chips' in todaychips and 'last' in todaychips:
                    if pktimestamp.formatTimeDayInt() == todaychips['today']:
                        yest_winchip = todaychips['last']
                    elif pktimestamp.formatTimeYesterDayInt(
                    ) == todaychips['today']:
                        yest_winchip = todaychips['chips']
                datas['winchip'] += yest_winchip
                datas['winchips'] += winchips
        except:
            ftlog.error()
    return datas