Beispiel #1
0
    def get_kvs(cls, tasklet, uid, gid):
        '''
        attrs = ['lastlogin', 'nslogin', 'play_game_count', 'win_game_count', 'draw_game_count',
                 'lose_game_count', 'bang_count', 'highest_lose_chip', 'highest_win_chip',
                 'highest_chip_record', 'day_win_game_count', 'day_win_sequence_count',
                 'day_max_win_sequence_count', 'big_pattern_history', 'best_pattern',
                 'online_records', 'guobiao_play_game_count', 'guobiao_win_game_count', 'guobiao_draw_game_count',
                 'guobiao_lose_game_count', 'guobiao_bang_count', 'guobiao_highest_lose_chip',
                 'guobiao_highest_win_chip', 'guobiao_highest_chip_record', 'win_sequence_count', 'max_win_sequence_count',
                 'guobiao_best_pattern', 'guobiao_online_records', 'max_degree_week_duration', 'max_degree_week_duration_ts',
                 'master_point', 'week_master_point', 'week_master_point_ts', 'day_play_game_count']
        '''
        attrs = ['win_sequence_count',  'max_win_sequence_count', 'guobiao_best_pattern']
        values = gamedata.getGameAttrs(uid, gid, attrs)
        for i, value in enumerate(values):
            if value is None:
                ftlog.debug(attrs[i], 'is None')
                values[i] = cls.get_default_value(attrs[i])[1]
            else:
                values[i] = cls.parse_content_from_redis(attrs[i], value)
        kvs = dict(zip(attrs, values))
        cls.check_attrs_timestamp(tasklet, uid, gid, kvs)

        kvs['chip'] = userchip.getChip(uid)
        kvs['exp'] = userdata.getExp(uid)
        kvs['charm'] = userdata.getCharm(uid)
        if not kvs['chip']:
            kvs['chip'] = 0
        if not kvs['exp']:
            kvs['exp'] = 0
        if not kvs['charm']:
            kvs['charm'] = 0
        return kvs
Beispiel #2
0
    def testQuickStart(self):
        '''测试快速开始'''
        gameId = 6
        userId = random.randint(10000, 20000)
        roomId = 0
        tableId = 0
        chip = 800
        clientId = "Android_3.501_tuyoo.YDJD.0-hall6.apphui.happy"
        playMode = "happy"
        
        onlinedata.setOnlineState(userId, onlinedata.ONLINE)
        onlinedata.cleanOnlineLoc(userId)
        
        userdata.setAttr(userId, "sessionClientId", clientId)
#         datas = sessiondata._getUserSessionValues(userId)
#         ftlog.debug("|userId, session:", userId, datas)
        
        oldChip = userchip.getChip(userId)
        userchip.incrChip(userId, gameId, chip - oldChip, 0, "GM_ADJUST_COIN", 0, clientId)
        
        msg = MsgPack()
        msg.setCmd("quick_start")
        msg.setParam("gameId", gameId)
        msg.setParam("userId", userId)
#         msg.setParam("roomId", roomId)
#         msg.setParam("tableId", tableId)
        msg.setParam("clientId", clientId)
        print '='*30
        print msg
        BaseQuickStartDispatcher.dispatchQuickStart(msg, userId, gameId, roomId, tableId, playMode, clientId)
        print '='*30
Beispiel #3
0
def getUserInfo(userId, gameId, clientId):
    '''
    取得用户的基本账户的信息
    '''
    ukeys = ['email', 'pdevid', 'mdevid', 'isbind', 'snsId', 'name',
             'source', 'diamond', 'address', 'sex', 'state',
             'payCount', 'snsinfo', 'vip', 'dayang', 'idcardno',
             'phonenumber', 'truename', 'detect_phonenumber',
             'lang', 'country', "signature", "set_name_sum", "coupon",
             'purl', 'beauty', 'charm', 'password', 'bindMobile']

    udataDb = userdata.getAttrs(userId, ukeys)

    udata = dict(zip(ukeys, udataDb))
    udata['coin'] = udata['diamond']  # 数据补丁: 再把diamond转换到coin返回, 老版本用的是coin
    udata['chip'] = userchip.getChip(userId)

    # 头像相关
    purl, isbeauty = getUserHeadUrl(userId, clientId, udata['purl'], udata['beauty'])
    udata['purl'] = purl
    udata['isBeauty'] = isbeauty

    # vip信息
    udata['vipInfo'] = hallvip.userVipSystem.getVipInfo(userId)
    # 江湖救急次数
    udata['assistance'] = {
        'count': hallvip.userVipSystem.getAssistanceCount(gameId, userId),
        'limit': hallvip.vipSystem.getAssistanceChipUpperLimit()
    }
    userdata.updateUserGameDataAuthorTime(userId, gameId)
    return udata
Beispiel #4
0
def _onUserLogin(event):
    timestamp = pktimestamp.getCurrentTimestamp()
    chip = userchip.getChip(event.userId)
    rankingSystem.setUserByInputType(event.gameId, TYRankingInputTypes.CHIP,
                                     event.userId, chip, timestamp)
    charm = userdata.getCharm(event.userId)
    rankingSystem.setUserByInputType(event.gameId, TYRankingInputTypes.CHARM,
                                     event.userId, charm, timestamp)
Beispiel #5
0
def getTotalChip(userId, gameId, tableId):
    user_chip = userchip.getChip(userId)
    if tableId == 0:
        table_chip = sum([pair[1] for pair in pairwise(userchip.getTableChipsAll(userId))])
        # table_chip = 0
        # for index, v in enumerate(userchip.getTableChipsAll(userId)):
        #    if index % 2:
        #        table_chip += v
    else:
        table_chip = userchip.getTableChip(userId, gameId, tableId)
    return user_chip + table_chip
Beispiel #6
0
 def reportBiGameEvent(self, eventId, userId, roomId, tableId, roundId, detalChip, state1, state2, cardlist, tag=''):
     try:
         finalUserChip = userchip.getChip(userId)
         finalTableChip = 0
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, self.gameId, roomId, tableId, roundId, detalChip,
                                  state1, state2, cardlist, clientId, finalTableChip, finalUserChip)
         if ftlog.is_debug():
             ftlog.debug('tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', self.gameId,
                         'roomId=', roomId, 'tableId=', tableId, 'roundId=', roundId, 'detalChip=', detalChip,
                         caller=self)
     except:
         ftlog.error(getMethodName(), 'tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', self.gameId)
Beispiel #7
0
 def testMoonbox(self):
     moonboxKind = hallitem.itemSystem.findItemKind(item_moonbox_id)
     # 获取用户背包
     userBag = hallitem.itemSystem.loadUserAssets(self.userId).getUserBag()
     self.assertEqual(userBag.getAllKindItem(moonboxKind), [])
     
     # 添加测试
     item = userBag.addItemUnitsByKind(self.gameId, moonboxKind, 1, self.timestamp, 0, 'TEST_ADJUST', 0)[0]
     self.assert_(item.remaining == 1)
     self.assert_(item.expiresTime == -1)
     
     # 非互斥的,每个背包里只存在一个实例
     item1 = userBag.addItemUnitsByKind(self.gameId, moonboxKind, 1, self.timestamp, 0, 'TEST_ADJUST', 0)[0]
     self.assert_(item.remaining == 2)
     self.assert_(item.expiresTime == -1)
     
     self.assert_(item == item1)
     
     self.assertRaises(TYBindingItemNotEnoughException, userBag.doAction, self.gameId, item, 'open')
     
     userBag.consumeUnitsCountByKind(self.gameId, moonboxKind, 2, self.timestamp, 0, 0)
     self.assertEqual(item.remaining, 0)
     
     moonkeyKind = hallitem.itemSystem.findItemKind(item_moonkey_id)
     
     openTimesLevel = [(4, 26000), (7, 30000), (100, 40000)]
     totalChip = 0
     totalOpenTimes = 0 
     for _, (openTimes, chipCount) in enumerate(openTimesLevel):
         moonkeyItem = userBag.addItemUnitsByKind(self.gameId, moonkeyKind, openTimes, self.timestamp, 0, 'TEST_ADJUST', 0)[0]
         self.assertEqual(moonkeyItem.remaining, openTimes)
         userBag.addItemUnitsByKind(self.gameId, moonboxKind, openTimes, self.timestamp, 0, 'TEST_ADJUST', 0)
         for i in xrange(openTimes):
             totalChip += chipCount
             totalOpenTimes += 1
             result = userBag.doAction(self.gameId, item, 'open').gotAssetList
             self.assertEqual(item.openTimes, totalOpenTimes)
             self.assertEqual(result[0][0].kindId, 'user:chip')
             self.assertEqual(result[0][1], chipCount)
             self.assertEqual(result[0][2], totalChip)
             
             self.assertEqual(item.remaining, openTimes - i - 1)
             self.assertEqual(moonkeyItem.remaining, openTimes - i - 1)
             self.assertEqual(pkuserchip.getChip(self.userId), totalChip)
     
     userBag = hallitem.itemSystem.loadUserAssets(self.userId).getUserBag()
     moonboxItem = userBag.findItem(item.itemId)
     self.assertEqual(moonboxItem.itemId, item.itemId)
     self.assertEqual(moonboxItem.remaining, 0)
     self.assertEqual(moonboxItem.openTimes, totalOpenTimes)
Beispiel #8
0
    def process_interactive_expression(cls, userId, gameId, seatId, chat_msg, target_player_uid, base_chip):
        """处理消费金币的表情"""
        config = cls.get_interactive_expression_config(base_chip)
        emoId = str(chat_msg.get('emoId', -1))
        if emoId not in config:
            ftlog.warn('chat msg illegal', chat_msg, config)
            return False

        info = config[emoId]
        # 底分限制
        chip = userchip.getChip(userId)
        if chip < info['chip_limit'] + info['cost']:
            ftlog.warn('insufficient', chip, info['chip_limit'], info['cost'])
            return False

        if TYPlayer.isHuman(userId):
            from difang.majiang2.entity.util import Util
            clientId = Util.getClientId(userId)
            trueDelta, _ = userchip.incrChip(userId
                                             , gameId
                                             , -info['cost']
                                             , 0
                                             , "EMOTICON_CONSUME"
                                             , chat_msg['emoId']
                                             , clientId
                                             )

            if trueDelta != -info['cost']:  # 失败
                ftlog.warn('coin not enougth: ', chip, info['chip_limit'], info['cost'])
                return False
            bireport.gcoin('out.interactive_expression', gameId, info['cost'])

            # 处理魅力值
        #             charm = incrCharm(userId, info['charm'])
        #             hallranking.rankingSystem.setUserByInputType(gameId
        #                     , TYRankingInputTypes.CHARM
        #                     , userId
        #                     , charm)

        #         if TYPlayer.isHuman(target_player_uid):
        #             charm = incrCharm(target_player_uid, info['ta_charm'])
        #             hallranking.rankingSystem.setUserByInputType(gameId
        #                     , TYRankingInputTypes.CHARM
        #                     , target_player_uid
        #                     , charm)

        return True
Beispiel #9
0
 def doGainNSLoginReward(self, userId, gameId, clientId):
     checkinOk, rewardAssetList, _checkinDays = \
         halldailycheckin.dailyCheckin.gainCheckinReward(gameId, userId)
     rewardChipCount = 0
     if checkinOk:
         datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(rewardAssetList))
         rewardChipCount = TYAssetUtils.getAssetCount(rewardAssetList, hallitem.ASSET_CHIP_KIND_ID)
     states = halldailycheckin.dailyCheckin.getStates(gameId, userId, pktimestamp.getCurrentTimestamp())
     mo = MsgPack()
     mo.setCmd('gain_nslogin_reward')
     mo.setResult('gameId', gameId)
     mo.setResult('userId', userId)
     mo.setResult('rewardstate', TodoTaskHelper.translateDailyCheckinStates(states))
     mo.setResult('success', True)
     mo.setResult('chip', userchip.getChip(userId))
     mo.setResult('rewardchip', rewardChipCount)
     router.sendToUser(mo, userId)
Beispiel #10
0
    def _canQuickEnterRoomBase(cls, userId, gameId, roomId, isOnly):
        try:
            chip = userchip.getChip(userId)
            if ftlog.is_debug():
                ftlog.debug(gdata.roomIdDefineMap()[roomId].configure)
            roomConfig = gdata.roomIdDefineMap()[roomId].configure
            if ftlog.is_debug():
                ftlog.debug('userId =', userId, 'minCoin =',
                            roomConfig.get('minCoin'), 'maxCoin =',
                            roomConfig.get('maxCoin'), 'minCoinQS =',
                            roomConfig.get('minCoinQS'), 'maxCoinQS =',
                            roomConfig.get('maxCoinQS'), 'chip =', chip,
                            'isOnly =', isOnly)
            if isOnly:
                minCoinQs = roomConfig['minCoin']
                maxCoinQs = roomConfig['maxCoin']
            else:
                minCoinQs = roomConfig['minCoinQS']
                maxCoinQs = roomConfig['maxCoinQS']
            ismatch = roomConfig.get('ismatch')

            if ismatch:
                return TYRoom.ENTER_ROOM_REASON_NOT_QUALIFIED

            if ftlog.is_debug():
                ftlog.debug('roomId =',
                            roomId,
                            'minCoinQs =',
                            minCoinQs,
                            'maxCoinQs =',
                            maxCoinQs,
                            'chip =',
                            chip,
                            caller=cls)

            if minCoinQs > 0 and chip < minCoinQs:
                return TYRoom.ENTER_ROOM_REASON_LESS_MIN
            if maxCoinQs > 0 and chip >= maxCoinQs:
                return TYRoom.ENTER_ROOM_REASON_GREATER_MAX

            return TYRoom.ENTER_ROOM_REASON_OK

        except Exception as e:
            ftlog.error(e)
            return TYRoom.ENTER_ROOM_REASON_INNER_ERROR
Beispiel #11
0
def _getQuickStartRoomList(cls, userId, playMode, **kwargs):
    # 判断userChip
    quickStartConf = dizhuconf.getQuickStart()
    userChip = userchip.getChip(userId)

    isMatch = 0
    # 比赛快开
    if playMode == dizhuconf.PLAYMODE_STRAIGHT_MATCH:
        matchStartChip = quickStartConf.get('matchStartChip', 0)
        isMatch = 1
        if userChip < matchStartChip:
            startRooms = quickStartConf.get('matchStartRooms', [])
            if startRooms:
                return [bigRoomId * 10000 + 1000 for bigRoomId in startRooms]
    # 大厅快开
    elif playMode == dizhuconf.PLAYMODE_DEFAULT:
        # 新手大厅快开必须进入配置指定的房间
        bigRoomIds = cls._getNewComerBigRoomIds(userId)
        if bigRoomIds:
            try:
                sessionRoomIds = cls.getMatchSessionRoomIds(userId)
                if not sessionRoomIds:  # 提审用
                    return [bigRoomIds[-1] * 10000 + 1000]
            except Exception, e:
                ftlog.error('DizhuQuickStart._getQuickStartRoomList',
                            'userId=', userId, 'playMode=', playMode,
                            'kwargs=', kwargs, 'bigRoomIds=', bigRoomIds,
                            'err=', e.message)
            return [bigRoomId * 10000 + 1000 for bigRoomId in bigRoomIds]
        hallStartChip = quickStartConf.get('hallStartChip', 0)
        if hallStartChip and userChip >= hallStartChip:
            playMode = dizhuconf.PLAYMODE_123
        else:
            startRooms = quickStartConf.get('hallStartRooms', [])
            if startRooms:
                try:
                    sessionRoomIds = cls.getMatchSessionRoomIds(userId)
                    if not sessionRoomIds:  # 提审用
                        return [startRooms[-1] * 10000 + 1000]
                except Exception, e:
                    ftlog.error('DizhuQuickStart._getQuickStartRoomList',
                                'userId=', userId, 'playMode=', playMode,
                                'kwargs=', kwargs, 'startRooms=', startRooms,
                                'err=', e.message)
                return [bigRoomId * 10000 + 1000 for bigRoomId in startRooms]
Beispiel #12
0
def _doTableWinloseUT(userId, roomId, tableId, roundNum, clientId, isWin,
                      winStreak, winUserId, isDizhu, fee, cardNoteFee, winlose,
                      systemPaid, winnerTax, baseScore, winDoubles, bomb,
                      chuntian, winslam, playMode, topCardList, **kwargs):
    bigRoomId = strutil.getBigRoomIdFromInstanceRoomId(roomId)
    treasurebox.updateTreasureBoxWin(DIZHU_GAMEID, userId,
                                     kwargs.get('mixConfRoomId') or bigRoomId)
    exp, deltaExp, _winrate = comm_table_remote.checkSetMedal(
        DIZHU_GAMEID, userId, baseScore, False, winlose)
    deltaItems = buildSettlementDeltaItems(
        kwargs.get('mixConfRoomId') or roomId, fee, cardNoteFee, winlose,
        winnerTax)
    skillScoreInfo = _caleSkillScoreByUser(
        userId, isWin, winStreak, isDizhu,
        kwargs.get('mixConfRoomId') or bigRoomId, winDoubles)
    skillLevelUp = skillScoreInfo.get('isLevelUp', False)

    _reportRoomDelta(userId, roomId, bigRoomId, clientId, systemPaid)
    finalTableChip = _settlement(userId,
                                 kwargs.get('mixConfRoomId') or roomId,
                                 tableId, roundNum, clientId, deltaItems)

    # 纪录连胜
    if isWin:
        gamedata.incrGameAttr(userId, DIZHU_GAMEID, 'winstreak', 1)
    else:
        gamedata.setGameAttr(userId, DIZHU_GAMEID, 'winstreak', 0)
    if ftlog.is_debug():
        winstreaklog = gamedata.getGameAttr(userId, DIZHU_GAMEID, 'winstreak')
        ftlog.debug('_doTableWinloseUT winstreak=', winstreaklog, 'UserID=',
                    userId, 'roomId=', roomId, 'tableId=', tableId, 'isWin=',
                    isWin)

    # 广播用户结算事件
    card = cardrules.CARD_RULE_DICT[playMode]
    topValidCard = card.validateCards(topCardList, None)
    finalUserChip = userchip.getChip(userId)
    _publishWinLoseEvent(roomId, tableId, userId, roundNum, isWin, isDizhu,
                         winUserId, winlose, finalTableChip, winDoubles, bomb,
                         chuntian, winslam, clientId, topValidCard,
                         skillLevelUp, **kwargs)
    # 更新排名相关数据
    _calRankInfoData(userId, winlose, winslam, winDoubles)

    return finalTableChip, finalUserChip, [exp, deltaExp], skillScoreInfo
Beispiel #13
0
def handleLotteryRequest(userId, gameId, clientId, msg):
    action = msg.getParam('action')
    ftlog.debug('handleLotteryRequest action=', action, 'userId=', userId,
                'gameId=', gameId, 'clientId=', clientId)
    if action == 'lottery_card':
        #减少抽奖卡,抽奖
        timestamp = pktimestamp.getCurrentTimestamp()
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        _, consumeCount, _final = userAssets.consumeAsset(
            gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, 1, timestamp,
            'HALL_LOTTERY', 0)
        if consumeCount < 1:
            #金币抽奖
            result = {}
            result["type"] = "chip"
            result["coinNum"] = 1000
            return result
        datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
        result = {}
        result = doLottery(gameId, clientId, userId)
        if result:
            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            timestamp = pktimestamp.getCurrentTimestamp()
            result["card"] = userAssets.balance(
                gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, timestamp)
        return result
    elif action == 'lottery_chip':
        #减少金币,抽奖
        chipNow = userchip.getChip(userId)
        if chipNow < 20000:
            #去商城
            ret = TodoTaskShowInfo('您的金币不足两万,请去商城购买', True)
            ret.setSubCmd(TodoTaskGotoShop('coin'))
            result = {}
            result["todotask"] = ret.toDict()
            return result
        else:
            #金币抽
            coinDel = -1000
            userchip.incrChip(userId, gameId, coinDel,
                              daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO,
                              'HALL_LOTTERY', 0, clientId)
            datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
            return doLottery(gameId, clientId, userId)
Beispiel #14
0
    def process_interactive_expression(cls, userId, gameId, seatId, chat_msg,
                                       target_player_uid, base_chip):
        """处理消费金币的表情"""
        config = cls.get_interactive_expression_config(base_chip)
        emoId = str(chat_msg.get('emoId', -1))
        if emoId not in config:
            ftlog.warn('chat msg illegal', chat_msg, config)
            return False

        info = config[emoId]
        # 底分限制
        chip = userchip.getChip(userId)
        if chip < info['chip_limit'] + info['cost']:
            ftlog.warn('insufficient', chip, info['chip_limit'], info['cost'])
            return False

        if TYPlayer.isHuman(userId):
            from difang.majiang2.entity.util import Util
            clientId = Util.getClientId(userId)
            trueDelta, _ = userchip.incrChip(userId, gameId, -info['cost'], 0,
                                             "EMOTICON_CONSUME",
                                             chat_msg['emoId'], clientId)

            if trueDelta != -info['cost']:  # 失败
                ftlog.warn('coin not enougth: ', chip, info['chip_limit'],
                           info['cost'])
                return False
            bireport.gcoin('out.interactive_expression', gameId, info['cost'])

            # 处理魅力值
        #             charm = incrCharm(userId, info['charm'])
        #             hallranking.rankingSystem.setUserByInputType(gameId
        #                     , TYRankingInputTypes.CHARM
        #                     , userId
        #                     , charm)

        #         if TYPlayer.isHuman(target_player_uid):
        #             charm = incrCharm(target_player_uid, info['ta_charm'])
        #             hallranking.rankingSystem.setUserByInputType(gameId
        #                     , TYRankingInputTypes.CHARM
        #                     , target_player_uid
        #                     , charm)

        return True
Beispiel #15
0
 def _do_room__signout(self, msg):
     userId = msg.getParam('userId')
     mo = MsgPack()
     mo.setCmd('m_signout')
     mo.setResult('gameId', self.gameId)
     mo.setResult('roomId', self.bigRoomId)
     mo.setResult('userId', userId)
     try:
         signer = self.match.signout(userId)
         if signer:
             finalUserChip = userchip.getChip(userId)
             try:
                 sequence = int(self.match.curInst.instId.split('.')[1])
             except:
                 sequence = 0
             bireport.reportGameEvent('MATCH_SIGN_OUT', userId, DIZHU_GAMEID, self.roomId,
                                      0, sequence, 0, 0, 0, [], signer.clientId, 0, finalUserChip)
     except MatchException, e:
         self._handleMatchException(e, userId, mo)
Beispiel #16
0
    def adjustChip(self, minCoin=None, maxCoin=None):
        if not isinstance(minCoin, int) or not isinstance(maxCoin, int) \
                or minCoin < 0 or maxCoin < 0 or minCoin >= maxCoin:
            roomDef = gdata.roomIdDefineMap()[self.roomId]
            roomConf = roomDef.configure
            maxCoin = roomConf['maxCoin']
            minCoin = roomConf['minCoin']
            maxCoin = maxCoin if maxCoin > 0 else minCoin + 100000

        uchip = userchip.getChip(self.userId)
        ftlog.debug('adjustChip->userId, uchip, minCoin, maxCoin =', self.snsId, self.userId, uchip, minCoin, maxCoin)
        if uchip < minCoin or uchip > maxCoin:
            nchip = random.randint(minCoin + 1, minCoin + 1000)
            dchip = nchip - uchip
            trueDelta, finalCount = userchip.incrChip(self.userId, self.gameId, dchip,
                                                      daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                                      'SYSTEM_ADJUST_ROBOT_CHIP',
                                                      self.roomId, self.clientId)
            ftlog.debug('adjustChip->userId, trueDelta, finalCount=', self.snsId, self.userId, trueDelta, finalCount)
Beispiel #17
0
    def _canQuickStartDizhuMatch(cls, userId, gameId, roomId, playMode):
        '''
        检测比赛房间是否符合快开条件
        @return ok{Bool} 是否满足条件进入地主比赛
        '''
        roomconf = gdata.roomIdDefineMap()[roomId].configure

        bigRoomId = gdata.getBigRoomId(roomId)
        ctrRoomIds = gdata.bigRoomidsMap()[bigRoomId]
        ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]
        reason = cls._canQuickEnterMatchRoom(userId, gameId, ctrlRoomId, 1)
        ftlog.debug(
            "DizhuQuickStartV4_0._canQuickStartDizhuMatch: roomCond|userId=",
            userId, "roomId=", roomId, "bigRoomId=", bigRoomId, "ctrlRoomId=",
            ctrlRoomId, "reason=", reason)
        if reason != TYRoom.ENTER_ROOM_REASON_OK:
            return False

        # 若不存在开关,或者开关为0,代表房间关闭比赛快开
        quickMatchToggle = roomconf.get("quickMatchToggle", 0)
        ftlog.debug("DizhuQuickStartV4_0._canQuickStartDizhuMatch: userId=",
                    userId, "roomId=", roomId, "quickMatchToggle=",
                    quickMatchToggle)
        if quickMatchToggle == 0:
            return False

        # 获取选择比赛快开的条件列表
        coin_toplimit = roomconf.get("quickMatchCoinTopLimit", 0)

        # 获得用户的coin
        chip = userchip.getChip(userId)
        ftlog.debug("DizhuQuickStartV4_0._canQuickStartDizhuMatch: userId=",
                    userId, "roomId=", roomId, "chip=", chip, "coin_toplimit",
                    coin_toplimit)

        # 直接去比赛,不判断金币
        if playMode == dizhuconf.PLAYMODE_STRAIGHT_MATCH:
            return True

        if chip < coin_toplimit:
            return True

        return False
Beispiel #18
0
 def _do_room__signout(self, msg):
     if ftlog.is_debug():
         ftlog.debug('DizhuErdayiMatchCtrlRoom._do_room__signout', msg)
     userId = msg.getParam('userId')
     mo = MsgPack()
     mo.setCmd('m_signout')
     mo.setResult('gameId', self.gameId)
     mo.setResult('roomId', self.bigRoomId)
     mo.setResult('userId', userId)
     try:
         signer = self.match.signout(userId)
         if signer:
             finalUserChip = userchip.getChip(userId)
             bireport.reportGameEvent('MATCH_SIGN_OUT', userId,
                                      DIZHU_GAMEID, self.roomId, 0, 0, 0, 0,
                                      0, [], signer.clientId, 0,
                                      finalUserChip)
     except MatchException, e:
         self._handleMatchException(e, userId, mo)
Beispiel #19
0
    def recommendProductIfNeed(self, gameId, userId, chip):
        # 当前金币足够则不用推荐商品
        curchip = userchip.getChip(userId)
        ftlog.debug('BetGuess.recommendProductIfNeed:', 'userId=', userId,
                    'curchip=', curchip, 'chip=', chip)
        if curchip >= chip:
            return False

        # 没有配置推荐商品,则不推荐
        payOrderMap = Tool.dictGet(self._clientConf,
                                   'config.server.payOrderMap')
        if not payOrderMap:
            return False

        # 没有找到推荐商品配置,则不推荐
        payOrder = payOrderMap.get(str(int(chip)))
        ftlog.debug('BetGuess.recommendProductIfNeed:', 'userId=', userId,
                    'payOrder=', payOrder)
        if not payOrder:
            return False

        clientId = sessiondata.getClientId(userId)
        product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId,
                                                     payOrder)
        ftlog.debug('BetGuess.recommendProductIfNeed:', 'userId=', userId,
                    'product=', product)
        # 没有在货架中找到商品
        if not product:
            return False

        translateMap = {
            'product.displayName': product.displayName,
            'product.price': product.price,
            'betchip': chip,
        }
        desc = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipDesc')
        note = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipNote')
        desc = strutil.replaceParams(desc, translateMap)
        note = strutil.replaceParams(note, translateMap)
        todotask = TodoTaskLessBuyOrder(desc, None, note, product)
        TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
        return True
Beispiel #20
0
    def checkSitCondition(self, userId):
        chip = userchip.getChip(userId)

        if chip < self.roomConf['minCoin']:
            ftlog.warn("chip not enough",
                       "|userId, roomId:",
                       userId,
                       self.roomId,
                       caller=self)
            return False, TYRoom.ENTER_ROOM_REASON_LESS_MIN

        if self.roomConf['maxCoin'] > 0 and chip > self.roomConf['maxCoin']:
            ftlog.warn("chip too much",
                       "|userId, roomId:",
                       userId,
                       self.roomId,
                       caller=self)
            return False, TYRoom.ENTER_ROOM_REASON_GREATER_MAX

        return True, TYRoom.ENTER_ROOM_REASON_OK
def fuzhou_sendStartChip(userId, gameId, clientId):
    '''
    抚州金币场发放启动资金
    :param userId:
    :param gameId:
    :param clientId:
    '''
    global fuzhou_startchip

    canGive = False
    startChip = 0
    final = 0
    try:
        if fuzhou_needSendStartChip(userId, clientId):
            gamedata.setGameAttr(userId, hallconf.HALL_GAMEID,
                                 "start_chip_dfchip", 1)
            canGive = True

        if ftlog.is_debug():
            ftlog.debug('hallstartchip_fuzhou.fuzhou_sendStartChip userId=',
                        userId, 'gameId=', gameId, 'clientId=', clientId,
                        'chip=', startChip, 'canGive=', canGive)

        if canGive:
            nowChip = userchip.getChip(userId)
            startChip = fuzhou_startchip
            trueDelta, final = userchip.incrChip(
                userId, gameId, startChip - nowChip,
                daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 'FUZHOU_START_CHIP', 0,
                clientId)
            datachangenotify.sendDataChangeNotify(gameId, userId, ['chip'])
            bireport.gcoin('in.chip.newuser.startchip', gameId, startChip)
            ftlog.debug('hallstartchip_fuzhou.fuzhou_sendStartChip userId=',
                        userId, 'gameId=', gameId, 'clientId=', clientId,
                        'chip=', startChip, 'startChip=', startChip,
                        'trueDelta=', trueDelta, 'final=', final)
        return canGive, trueDelta, final
    except:
        ftlog.error()

    return False, 0, 0
Beispiel #22
0
    def _canQuickEnterRoom(cls, userId, gameId, roomId, isOnly):

        try:
            chip = userchip.getChip(userId)
            if ftlog.is_debug():
                ftlog.debug(gdata.roomIdDefineMap()[roomId].configure)
            roomConfig = gdata.roomIdDefineMap()[roomId].configure
            if ftlog.is_debug():
                ftlog.debug('userId =', userId,
                            'minCoin =', roomConfig.get('minCoin'),
                            'maxCoin =', roomConfig.get('maxCoin'),
                            'minCoinQS =', roomConfig.get('minCoinQS'),
                            'maxCoinQS =', roomConfig.get('maxCoinQS'),
                            'chip =', chip,
                            'isOnly =', isOnly)
            if isOnly:
                minCoinQs = roomConfig['minCoin']
                maxCoinQs = roomConfig['maxCoin']
            else:
                minCoinQs = roomConfig['minCoinQS']
                maxCoinQs = roomConfig['maxCoinQS']
            ismatch = roomConfig.get('ismatch')

            if ismatch or minCoinQs <= 0:
                return TYRoom.ENTER_ROOM_REASON_NOT_QUALIFIED

            if ftlog.is_debug():
                ftlog.debug('roomId =', roomId, 'minCoinQs =', minCoinQs,
                            'maxCoinQs =', maxCoinQs, 'chip =', chip,
                            caller=cls)

            if chip < minCoinQs:
                return TYRoom.ENTER_ROOM_REASON_LESS_MIN
            if maxCoinQs > 0 and chip >= maxCoinQs:
                return TYRoom.ENTER_ROOM_REASON_GREATER_MAX

            return TYRoom.ENTER_ROOM_REASON_OK

        except Exception as e:
            ftlog.error(e)
            return TYRoom.ENTER_ROOM_REASON_INNER_ERROR
Beispiel #23
0
    def adjustChip(self, minCoin=None, maxCoin=None):
        if not isinstance(minCoin, int) or not isinstance(maxCoin, int) \
                or minCoin < 0 or maxCoin < 0 or minCoin >= maxCoin:
            roomDef = gdata.roomIdDefineMap()[self.roomId]
            roomConf = roomDef.configure
            maxCoin = roomConf['maxCoin']
            minCoin = roomConf['minCoin']
            maxCoin = maxCoin if maxCoin > 0 else minCoin + 100000

        uchip = userchip.getChip(self.userId)
        ftlog.debug('adjustChip->userId, uchip, minCoin, maxCoin =',
                    self.snsId, self.userId, uchip, minCoin, maxCoin)
        if uchip < minCoin or uchip > maxCoin:
            nchip = random.randint(minCoin + 1, minCoin + 1000)
            dchip = nchip - uchip
            trueDelta, finalCount = userchip.incrChip(
                self.userId, self.gameId, dchip,
                daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                'SYSTEM_ADJUST_ROBOT_CHIP', self.roomId, self.clientId)
            ftlog.debug('adjustChip->userId, trueDelta, finalCount=',
                        self.snsId, self.userId, trueDelta, finalCount)
Beispiel #24
0
def deductionVipComplement(event):
    userId = event.userId

    ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|enter", userId, event.rmbs)
    if event.rmbs and event.rmbs > 0:
        gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement_msg', 0)
        vip_complement = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement")
        vip_complement_max = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement_max")
        vipL = getVipLevel(userId)
        vipKey = "vip_" + str(vipL)
        max = 0
        if vipKey in vip_complement:
            max = vip_complement_max[vipKey]
        chargeDate = datetime.datetime.now().strftime('%Y-%m-%d')
        gamedata.setGameAttr(userId, HALL_GAMEID, 'chargeDate', chargeDate)
        vipcominfo = gamedata.getGameAttr(userId, HALL_GAMEID, 'vip_complement')
        ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|vipcominfo", userId, event.rmbs, vipcominfo)
        if vipcominfo:
            vipcominfo = json.loads(vipcominfo)
            vipcom = vipcominfo['vipcom']
            if vipcom == 0:
                ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|vipcom|zero", userId, event.rmbs, vipcominfo)
                return

            vip_complement_deduction = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement_deduction", 10000)
            deduction = int(event.rmbs) * vip_complement_deduction
            delta = vipcom - deduction
            ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement|vip_complement_deduction", userId, event.rmbs, vipcominfo, vip_complement_deduction, deduction, vipcom, delta)
            if delta < 0:
                delta = 0

            gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement',
                                 json.dumps({'vipLevel': vipcominfo['vipLevel'], 'vipcom': int(delta)}))
            final = userchip.getChip(userId)
            bireport.reportGameEvent('HALL_VIPCOMPLEMENT', userId, event.gameId, 0, 0, 0, 0, 0, 0,
                                     [vipL, 0, deduction, int(max - delta), final],
                                     event.clientId,
                                     0, 0)

            ftlog.hinfo("ChargeNotifyEvent|deductionVipComplement", userId, event.rmbs, vipcominfo['vipLevel'], vipcom, delta)
Beispiel #25
0
 def reportBiGameEvent(self,
                       eventId,
                       userId,
                       roomId,
                       tableId,
                       roundId,
                       detalChip,
                       state1,
                       state2,
                       cardlist,
                       tag=''):
     try:
         finalUserChip = userchip.getChip(userId)
         finalTableChip = 0
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, self.gameId, roomId,
                                  tableId, roundId, detalChip, state1,
                                  state2, cardlist, clientId,
                                  finalTableChip, finalUserChip)
         if ftlog.is_debug():
             ftlog.debug('tag=',
                         tag,
                         'eventId=',
                         eventId,
                         'userId=',
                         userId,
                         'gameId=',
                         self.gameId,
                         'roomId=',
                         roomId,
                         'tableId=',
                         tableId,
                         'roundId=',
                         roundId,
                         'detalChip=',
                         detalChip,
                         caller=self)
     except:
         ftlog.error(getMethodName(), 'tag=', tag, 'eventId=', eventId,
                     'userId=', userId, 'gameId=', self.gameId)
Beispiel #26
0
    def _canQuickEnterRoom(cls, userId, gameId, roomId, isOnly):
        try:
            chip = userchip.getChip(userId)
            ftlog.debug(gdata.roomIdDefineMap()[roomId].configure, caller=cls)
            roomConfig = gdata.roomIdDefineMap()[roomId].configure
            ismatch = roomConfig.get('ismatch')
            isBigMatch = False
            if roomConfig.get('typeName', '') == 'majiang_bigmatch':
                isBigMatch = True
            if ismatch and not isBigMatch:
                return cls._canQuickEnterMatch(userId, gameId, roomId, chip)

            if isOnly:
                minCoinQs = roomConfig['minCoin']
                maxCoinQs = roomConfig['maxCoin']
            else:
                minCoinQs = roomConfig['minCoinQS']
                maxCoinQs = roomConfig['maxCoinQS']

            ftlog.debug('MajiangQuickStartV4_0 roomId:',
                        roomId,
                        'minCoinQs:',
                        minCoinQs,
                        'maxCoinQs:',
                        maxCoinQs,
                        'chip:',
                        chip,
                        caller=cls)

            if chip < minCoinQs and (minCoinQs != -1):
                return TYRoom.ENTER_ROOM_REASON_LESS_MIN

            if maxCoinQs > 0 and chip >= maxCoinQs:
                return TYRoom.ENTER_ROOM_REASON_GREATER_MAX

            return TYRoom.ENTER_ROOM_REASON_OK

        except Exception as e:
            ftlog.error(e)
            return TYRoom.ENTER_ROOM_REASON_INNER_ERROR
Beispiel #27
0
 def doGainNSLoginReward(self, userId, gameId, clientId):
     checkinOk, rewardAssetList, _checkinDays = \
         halldailycheckin.dailyCheckin.gainCheckinReward(gameId, userId)
     rewardChipCount = 0
     if checkinOk:
         datachangenotify.sendDataChangeNotify(
             gameId, userId,
             TYAssetUtils.getChangeDataNames(rewardAssetList))
         rewardChipCount = TYAssetUtils.getAssetCount(
             rewardAssetList, hallitem.ASSET_CHIP_KIND_ID)
     states = halldailycheckin.dailyCheckin.getStates(
         gameId, userId, pktimestamp.getCurrentTimestamp())
     mo = MsgPack()
     mo.setCmd('gain_nslogin_reward')
     mo.setResult('gameId', gameId)
     mo.setResult('userId', userId)
     mo.setResult('rewardstate',
                  TodoTaskHelper.translateDailyCheckinStates(states))
     mo.setResult('success', True)
     mo.setResult('chip', userchip.getChip(userId))
     mo.setResult('rewardchip', rewardChipCount)
     router.sendToUser(mo, userId)
Beispiel #28
0
    def _do_room__signin(self, msg):
        userId = msg.getParam('userId')
        signinParams = msg.getParam('signinParams', {})
        feeIndex = msg.getParam('feeIndex', 0)
        
        if ftlog.is_debug():
            ftlog.debug('DizhuCtrlRoomArenaMatch._do_room__signin',
                        'roomId=', self.roomId,
                        'userId=', userId,
                        'signinParams=', signinParams,
                        'feeIndex=', feeIndex)

        mp = MsgPack()
        mp.setCmd('m_signin')
        try:
            # 检查服务器重启
            if game.isShutDown():
                raise MatchGameRestartException()

            # 检查禁赛
            res, remains = BanHelper.checkBanValid(userId, int(signinParams.get('mixId')) if signinParams.get('mixId') else self.bigRoomId)
            if res:
                raise MatchBanException(remains)

            # 检查开放时间
            for conf in self.matchConf.get('feeRewardList', []):
                if conf.get('mixId') and conf.get('mixId') == signinParams.get('mixId'):
                    if not dizhu_util.checkRoomOpenTime(conf, datetime.datetime.now().time()):
                        raise MatchExpiredException(matchId=self.match.matchId, message=conf.get('openTimeListTip', ''))

            self.ensureCanSignInMatch(userId, mp)
            player = self.match.signin(userId, signinParams, feeIndex)
            clientId = player.clientId if player else sessiondata.getClientId(userId)
            finalUserChip = userchip.getChip(userId)
            bireport.reportGameEvent('MATCH_SIGN_UP', userId, DIZHU_GAMEID, self.roomId, 0, 0, 0,
                                     0, 0, [], clientId, 0, finalUserChip)
        except (MatchException, MatchBanException, MatchGameRestartException), e:
            self._handleMatchException(e, userId, mp)
Beispiel #29
0
    def _canQuickEnterRoom(cls, userId, gameId, roomId, isOnly):

        try:
            chip = userchip.getChip(userId)
            ftlog.debug(gdata.roomIdDefineMap()[roomId].configure, caller=cls)
            roomConfig = gdata.roomIdDefineMap()[roomId].configure
            ismatch = roomConfig.get('ismatch')
            isBigMatch = False
            if roomConfig.get('typeName', '') == 'majiang_bigmatch':
                isBigMatch = True
            if ismatch and not isBigMatch:
                return cls._canQuickEnterMatch(userId, gameId, roomId, chip)

            if isOnly:
                minCoinQs = roomConfig['minCoin']
                maxCoinQs = roomConfig['maxCoin']
            else:
                minCoinQs = roomConfig['minCoinQS']
                maxCoinQs = roomConfig['maxCoinQS']

            if minCoinQs <= 0:
                return TYRoom.ENTER_ROOM_REASON_NOT_QUALIFIED

            ftlog.debug('roomId =', roomId, 'minCoinQs =', minCoinQs,
                        'maxCoinQs =', maxCoinQs, 'chip =', chip,
                        caller=cls)

            if chip < minCoinQs:
                return TYRoom.ENTER_ROOM_REASON_LESS_MIN
            if maxCoinQs > 0 and chip >= maxCoinQs:
                return TYRoom.ENTER_ROOM_REASON_GREATER_MAX

            return TYRoom.ENTER_ROOM_REASON_OK

        except Exception as e:
            ftlog.error(e)
            return TYRoom.ENTER_ROOM_REASON_INNER_ERROR
Beispiel #30
0
 def report_bi_game_event(self,
                          eventId,
                          userId,
                          roomId,
                          tableId,
                          roundId,
                          detalChip,
                          state1,
                          state2,
                          cardlist,
                          tag=''):
     try:
         finalUserChip = userchip.getChip(userId)
         finalTableChip = 0
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, 6, roomId, tableId,
                                  roundId, detalChip, state1, state2,
                                  cardlist, clientId, finalTableChip,
                                  finalUserChip)
         ftlog.debug('report_bi_game_event tag=',
                     tag,
                     'eventId=',
                     eventId,
                     'userId=',
                     userId,
                     'gameId=6',
                     'roomId=',
                     roomId,
                     'tableId=',
                     tableId,
                     'roundId=',
                     roundId,
                     caller=self)
     except:
         ftlog.error('report_bi_game_event error tag=', tag, 'eventId=',
                     eventId, 'userId=', userId, 'gameId=6', 'roomId=',
                     roomId, 'tableId=', tableId, 'roundId=', roundId)
def getCoinComplement(userId, coin=0):
    """
    获得金币补足
    :param userId:
    :param coin: 当处于渔场中时,使用渔场传过来的金币数
    """
    effect = {}
    userCoin = coin if coin > 0 else userchip.getChip(userId)
    treasureConf = config.getTreasureConf(effectType=EffectType.CoinComplement)
    if treasureConf:
        kindId = treasureConf["kindId"]
        level, levelConf = getTreasureInfo(userId, kindId)
        if not levelConf:
            return
        refreshTreasureState(userId, kindId)
        treasureData = getTreasure(userId, kindId)
        if treasureData[INDEX_FINISH_COUNT] >= treasureConf["limitCount"]:
            return
        coinComplement = levelConf.get("params", {}).get("value", 0)
        if coinComplement > userCoin:
            lang = util.getLanguage(userId)
            rewards = [{"name": config.CHIP_KINDID,
                        "count": coinComplement - userCoin,
                        "chgCount": [userCoin, coinComplement]}]
            util.addRewards(userId, rewards, "BI_NFISH_TREASURE_REWARDS", kindId)
            activeTreasure(userId, kindId, treasureData)
            treasureName = config.getMultiLangTextConf(treasureConf["name"], lang=lang)
            coinStr = util.formatScore(coinComplement, lang=lang)
            message = config.getMultiLangTextConf("ID_CONFIG_TREASURE_SUPPLY_101", lang=lang)
            message = message.format(coinStr, treasureName, coinStr)
            GameMsg.sendPrivate(FISH_GAMEID, userId, 0, message)
            effect = {
                "kindId": kindId,
                "level": level,
                "rewards": rewards
            }
    return effect
Beispiel #32
0
 def _chooseRoom(cls, userId, gameId, gameMode=config.MULTIPLE_MODE):
     """
     服务端为玩家选择房间
     """
     candidateRoomIds = cls._getCandidateRoomIds(gameId, "")
     newbieRoomId = config.getCommonValueByKey("newbieRoomId")
     if not util.isFinishAllNewbieTask(userId):
         return newbieRoomId, cls.ENTER_ROOM_REASON_OK
     uLevel = util.getUserLevel(userId)
     gunLevel = util.getGunLevel(userId, gameMode)
     userChip = userchip.getChip(userId)
     candidateRoomId = 0
     for roomId in sorted(candidateRoomIds, reverse=True):
         isOK = cls.matchEnterRoom(roomId, uLevel, gunLevel, userChip,
                                   gameMode)
         if isOK:
             candidateRoomId = roomId
             break
     if ftlog.is_debug():
         ftlog.debug("_chooseRoom", userId, gameId, gameMode,
                     candidateRoomId)
     if candidateRoomId > 0:
         return candidateRoomId, cls.ENTER_ROOM_REASON_OK
     return 0, cls.ENTER_ROOM_REASON_LESS_LEVEL
Beispiel #33
0
    def get_kvs(cls, tasklet, uid, gid):
        '''
        attrs = ['lastlogin', 'nslogin', 'play_game_count', 'win_game_count', 'draw_game_count',
                 'lose_game_count', 'bang_count', 'highest_lose_chip', 'highest_win_chip',
                 'highest_chip_record', 'day_win_game_count', 'day_win_sequence_count',
                 'day_max_win_sequence_count', 'big_pattern_history', 'best_pattern',
                 'online_records', 'guobiao_play_game_count', 'guobiao_win_game_count', 'guobiao_draw_game_count',
                 'guobiao_lose_game_count', 'guobiao_bang_count', 'guobiao_highest_lose_chip',
                 'guobiao_highest_win_chip', 'guobiao_highest_chip_record', 'win_sequence_count', 'max_win_sequence_count',
                 'guobiao_best_pattern', 'guobiao_online_records', 'max_degree_week_duration', 'max_degree_week_duration_ts',
                 'master_point', 'week_master_point', 'week_master_point_ts', 'day_play_game_count']
        '''
        attrs = [
            'win_sequence_count', 'max_win_sequence_count',
            'guobiao_best_pattern'
        ]
        values = gamedata.getGameAttrs(uid, gid, attrs)
        for i, value in enumerate(values):
            if value is None:
                ftlog.debug(attrs[i], 'is None')
                values[i] = cls.get_default_value(attrs[i])[1]
            else:
                values[i] = cls.parse_content_from_redis(attrs[i], value)
        kvs = dict(zip(attrs, values))
        cls.check_attrs_timestamp(tasklet, uid, gid, kvs)

        kvs['chip'] = userchip.getChip(uid)
        kvs['exp'] = userdata.getExp(uid)
        kvs['charm'] = userdata.getCharm(uid)
        if not kvs['chip']:
            kvs['chip'] = 0
        if not kvs['exp']:
            kvs['exp'] = 0
        if not kvs['charm']:
            kvs['charm'] = 0
        return kvs
Beispiel #34
0
def _moveChipToTablechipBuyUser(userId, roomId, tableId, seatId,
                                isSupportBuyin, buyinChip, minCoin, clientId):
    ftlog.debug(
        '_moveChipToTablechipBuyUser->userId, roomId, tableId, seatId, isSupportBuyin, buyinChip=',
        userId, roomId, tableId, seatId, isSupportBuyin, buyinChip, clientId)
    if isSupportBuyin:  # 坐下操作, 进行带入金币操作
        isbuyinall = dizhuconf.getIsTableBuyInAll(clientId)
        ftlog.debug('_moveChipToTablechipBuyUser->isbuyinall=', isbuyinall)
        if isbuyinall or buyinChip <= 0:
            chip, user_chip_final, delta_chip = userchip.moveAllChipToTableChip(
                userId, DIZHU_GAMEID, 'TABLE_SITDOWN_SET_TCHIP', roomId,
                clientId, tableId)
        else:
            minchip = min(minCoin, buyinChip)
            maxchip = max(minCoin, buyinChip)
            chip, user_chip_final, delta_chip = userchip.setTableChipToRange(
                userId, DIZHU_GAMEID, minchip, maxchip,
                'TABLE_SITDOWN_SET_TCHIP', roomId, clientId, tableId)
        ftlog.debug(
            '_moveChipToTablechipBuyUser->userId, roomId, tableId, chip, user_chip_final, delta_chip=',
            userId, roomId, tableId, chip, user_chip_final, delta_chip)
    else:
        chip = userchip.getChip(userId)
    return chip
Beispiel #35
0
                minQuickStartChip = roomdef.configure.get('mixConf')[0].get(
                    'minQuickStartChip', -1)
            elif ismatch and roomdef.configure.get(
                    'typeName'
            ) == 'dizhu_arena_match' and roomdef.configure.get(
                    'matchConf', {}).get('feeRewardList', []):
                startChip = roomdef.configure.get('matchConf', {}).get(
                    'feeRewardList', [])[0].get('minQuickStartChip', 0)
                minQuickStartChip = roomdef.configure.get('matchConf', {}).get(
                    'feeRewardList', [])[0].get('minQuickStartChip', -1)
            else:
                startChip = roomdef.configure.get('minQuickStartChip', 0)
                minQuickStartChip = roomdef.configure.get(
                    'minQuickStartChip', -1)

            if userchip.getChip(userId) < startChip:
                continue
            if minQuickStartChip == -1:
                continue
            ctrlroomid_quickstartchip_list.append(
                [ctrlroomid, minQuickStartChip])

    ctrlroomid_quickstartchip_list.sort(key=lambda x: x[1] * -1)
    ctrlRoomIds = []
    for ctrlRoom in ctrlroomid_quickstartchip_list:
        ctrlRoomIds.append(ctrlRoom[0])

    if ftlog.is_debug():
        ftlog.debug("DizhuQuickStart <<|selected candidateRoomIds:",
                    ctrlRoomIds,
                    'playMode=',
Beispiel #36
0
    def _getVipTableList(self,
                         userId,
                         clientId,
                         tag="",
                         isMasterRoom=False,
                         isLiveShowRoom=False):
        '''获取vip房间和游轮赛房间的桌子列表'''
        roomList = []
        vip_tableList = []
        chip = userchip.getChip(userId)

        if ftlog.is_debug():
            ftlog.debug("|roomIds:", gdata.rooms().keys(), caller=self)
        for room in gdata.rooms().values():
            if not isinstance(room, TYVipRoom):
                continue

            ftlog.debug("|roomId:", room.roomId, caller=self)
            if not room.roomConf.get('visible', True):
                if ftlog.is_debug():
                    ftlog.debug("not visible", caller=self)
                continue

            if isMasterRoom != bool(room.roomConf.get("isMasterRoom")):
                if ftlog.is_debug():
                    ftlog.debug("isMasterRoom not match", caller=self)
                continue

            if isLiveShowRoom != bool(room.roomConf.get("isLiveShowRoom")):
                if ftlog.is_debug():
                    ftlog.debug("isLiveShowRoom not match", caller=self)
                continue

            if tag != room.roomConf.get("tag", ""):
                if ftlog.is_debug():
                    ftlog.debug("tag not match", caller=self)
                continue

            roomSortId = room.roomConf.get("sortId", 0)
            roomIndex = room.bigRoomId % 1000
            if roomSortId > 0 and roomSortId < 1000:
                if chip >= self.VIP_ROOM_LIST_REVERSE_CHIPS:
                    roomSortId = roomIndex
                else:
                    roomSortId = 1000 - roomIndex
            roomInfo = {"roomId": room.bigRoomId, "roomSortId": roomSortId}
            roomList.append(roomInfo)

            if ftlog.is_debug():
                ftlog.debug("|roomId, secretConf:",
                            room.roomId,
                            room.roomConf.get("secretConf"),
                            caller=self)
            if room.isSecretRoom():

                if len(self.maptable) < 1:
                    continue

                table = room.maptable.values()[0]
                if not table.checkSecretCondition(userId, clientId):
                    continue

                tableinfo = {}
                tableinfo["maxPlayerNum"] = table.maxSeatN
                tableinfo["playerNum"] = 0
                tableinfo["tableId"] = 0
                tableinfo["roomId"] = room.roomId
                tableinfo["type"] = room.roomConf["typeName"]
                tableinfo["sortId"] = room.roomConf.get("sortId", 0)
                tableinfo["isSecrect"] = True
                table.updateTableListInfo(tableinfo, clientId)
                vip_tableList.append(tableinfo)
                continue

            if not room._activeTables:
                room._initActiveTables()

            for tableId, table in room.sortedActiveTablesWithId():
                tableinfo = {}
                tableinfo["maxPlayerNum"] = table.maxSeatN
                tableinfo["playerNum"] = table.playersNum
                tableinfo["tableId"] = tableId
                tableinfo["roomId"] = table.room.roomId
                tableinfo["type"] = table.room.roomConf["typeName"]
                tableinfo["sortId"] = table.room.roomConf.get("sortId", 0)
                tableinfo["listBG"] = room.roomConf.get("listBG", "normal")
                table.updateTableListInfo(tableinfo, clientId)
                if self.isLiveShowRoom() and not tableinfo.get("creatorId"):
                    continue
                vip_tableList.append(tableinfo)

                #         def tableListComparer(x, y):
                #             if x["playerNum"] == x["maxPlayerNum"] :
                #                 if y["playerNum"] == y["maxPlayerNum"] :
                #                     return y["sortId"] - x["sortId"]
                #                 else :
                #                     return 1
                #
                #             if y["playerNum"] == y["maxPlayerNum"] :
                #                 return -1
                #
                #             return x["sortId"] - y["sortId"]

                #         vip_tableList = sorted(vip_tableList, cmp=lambda x, y : tableListComparer(x, y))

        TYPluginCenter.event(
            TYPluginUtils.updateMsg(cmd='EV_GET_VIP_TABLE_LIST',
                                    params={
                                        'table': self,
                                        'vip_tableList': vip_tableList
                                    }), self.gameId)

        for t in vip_tableList:
            del t['sortId']

        results = {"gameId": self.gameId}
        results['tables'] = vip_tableList
        results['roomList'] = roomList

        return results
Beispiel #37
0
    def doTableSmiliesv3_775(self,
                             userId,
                             seatId,
                             smilie,
                             toSeatId,
                             player,
                             wcount=1):
        '''
        @param wcount: wantcount
        地主新版本支持,互动表情金币不足也可以发送,不过会存在冷却时间,所有互动表情只要使用一个,就会全部进入倒计时状态
        新版本新增了一个表情,为了兼容老版本,需要在新版本发送新增的表情时特殊处理
        '''
        ftlog.debug('doTableSmiliesv3_775:begin', 'userId=', userId, 'smilie=',
                    smilie, 'wcount=', wcount)
        other_uid = self.seats[toSeatId - 1].userId
        if other_uid <= 0:
            self.gamePlay.sender.sendSmilesResError(userId, '该玩家已经离开此桌子')
            return

        conf = smilies.getConfDict(self.bigRoomId, userId)
        conf = conf.get(smilie, None)
        if not conf:
            self.gamePlay.sender.sendSmilesResError(userId, '该房间不支持互动表情')
            return

        price = conf.get('price', 0)
        mychip = userchip.getChip(userId)

        # 金币不足时,进行冷却时间判断
        ftlog.debug('doTableSmiliesv3_775:chip+cd', 'userId=', userId,
                    'smilie=', smilie, 'wcount=', wcount)

        if mychip < price and (not self.checkCooldownStatus(
                userId, smilie, conf)):
            self.gamePlay.sender.sendSmilesResError(userId, '互动表情冷却时间未到')
            return

        price, self_charm, other_charm = conf['price'], conf[
            'self_charm'], conf['other_charm']
        if price == None or price < 0:
            self.gamePlay.sender.sendSmilesResError(userId, '该房间不支持互动表情')
            return

        minchip = self.runConfig.minCoin
        if player.isSupportBuyin:
            minchip = 0

        clientId = sessiondata.getClientId(userId)

        # 获得实际要发送的次数rcount(连续发送表情,为了性能一次性处理)
        rcount, deltaChip, finalChip = table_remote.doTableSmiliesFrom_v3_775(
            self.roomId, self.bigRoomId, self.tableId, userId, smilie, minchip,
            price, self_charm, clientId, wcount)
        ftlog.debug('doTableSmiliesv3_775:rcount', 'userId=', userId,
                    'rcount=', rcount, 'deltaChip=', deltaChip, 'finalChip=',
                    finalChip)
        table_remote.doTableSmiliesTo(other_uid, other_charm, rcount)

        # 互动表情
        if self.gameRound:
            self.gameRound.sendSmilies(seatId - 1, toSeatId - 1, smilie,
                                       rcount, deltaChip, finalChip)

        member = self.isMember(player)
        # 发送结果消息
        # 十连发为了支持老版本,只能多次发送协议
        self.gamePlay.sender.sendSmilesResOk(seatId, member, toSeatId, price,
                                             smilie, self_charm, other_charm,
                                             '', rcount)
        # 同步修改player中的魅力值信息
        if self.players[toSeatId - 1].userId == other_uid:  # 玩家可能已经离开或换人
            self.players[toSeatId - 1].adjustCharm(other_charm * rcount)
        if player.userId == userId:  # 玩家可能已经离开或换人
            player.adjustCharm(self_charm * rcount)

        ## 重置CD计时
        uniquekey = 'smile.emo'
        TimeCounter.resetingCounterToCurrentTimestamp(uniquekey, userId)
Beispiel #38
0
    def _doFlipcard(self, userId, gameId, clientId, activityId, coin):
        result = {}
        key = "TYActivity:%d:%d:%s:%s" % (gameId, userId, clientId, activityId)
        ftlog.debug("_doFlipcard key:", key)
        conf = {
            "design": {
                "1": {
                    "name": "豹子A",
                    "payrate": 20,
                    "probability": 0.0001
                },
                "2": {
                    "name": "豹子",
                    "payrate": 20,
                    "probability": 0.0012
                },
                "3": {
                    "name": "同花顺",
                    "payrate": 15,
                    "probability": 0.001
                },
                "4": {
                    "name": "同花",
                    "payrate": 3,
                    "probability": 0.01
                },
                "5": {
                    "name": "顺子",
                    "payrate": 3,
                    "probability": 0.01
                },
                "6": {
                    "name": "对子",
                    "payrate": 1.5,
                    "probability": 0.1
                },
                "7": {
                    "name": "K以上单张",
                    "payrate": 1.2,
                    "probability": 0.3
                },
                "8": {
                    "name": "单张",
                    "payrate": 0,
                    "probability": 0.5777
                }
            }
        }

        # 判断用户金币是否足够
        chipNow = userchip.getChip(userId)
        if coin == 1000 and chipNow < 5000:
            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 20,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        elif coin == 5000 and chipNow < 50000:

            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 80,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        elif coin == 10000 and chipNow < 50000:
            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 80,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        elif coin == 50000 and chipNow < 300000:
            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 300,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        else:
            result = doFlipCard(conf)
            ftlog.debug("_doFlipcard result..cardtype:", result["cardtype"])
            # 减金币操作
            coinDel = 0 - coin
            userchip.incrChip(userId, gameId, coinDel, daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO, 'HALL_FLIPCARD', 0,
                              clientId)
            datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
            ftlog.info("用户名,用户减少了金币,", userId, coinDel)
            if result["cardtype"] != '8':
                design = conf.get('design', {})
                cardTypeNumber = design[result["cardtype"]].get('payrate', 0)

                # 加金币操作
                coinAdd = int(coin * cardTypeNumber)
                cardText = "恭喜你赢得了%d" % coinAdd + "金币"
                ftlog.debug("_doFlipcard get money:", cardText)
                userchip.incrChip(userId, gameId, coinAdd, daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO, 'HALL_FLIPCARD',
                                  0, clientId)
                datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
                ftlog.info("用户名,用户增加了金币,", userId, coinAdd)
                result["todoTask"] = {"action": "pop_tip",
                                      "params": {
                                          "text": cardText,
                                          "duration": 2
                                      }
                                      }
                return result
            else:
                cardText = "再接再厉,下次就会赢哦";
                result["todoTask"] = {"action": "pop_tip",
                                      "params": {
                                          "text": cardText,
                                          "duration": 2
                                      }
                                      }
                ftlog.debug("_doFlipcard key over:", key)
                return result

        '''
Beispiel #39
0
    def _getVipTableList(self, userId, clientId, tag="", isMasterRoom=False, isLiveShowRoom=False):
        '''获取vip房间和游轮赛房间的桌子列表'''
        roomList = []
        vip_tableList = []
        chip = userchip.getChip(userId)

        if ftlog.is_debug():
            ftlog.debug("|roomIds:", gdata.rooms().keys(), caller=self)
        for room in gdata.rooms().values():
            if not isinstance(room, TYVipRoom):
                continue

            ftlog.debug("|roomId:", room.roomId, caller=self)
            if not room.roomConf.get('visible', True):
                if ftlog.is_debug():
                    ftlog.debug("not visible", caller=self)
                continue

            if isMasterRoom != bool(room.roomConf.get("isMasterRoom")):
                if ftlog.is_debug():
                    ftlog.debug("isMasterRoom not match", caller=self)
                continue

            if isLiveShowRoom != bool(room.roomConf.get("isLiveShowRoom")):
                if ftlog.is_debug():
                    ftlog.debug("isLiveShowRoom not match", caller=self)
                continue

            if tag != room.roomConf.get("tag", ""):
                if ftlog.is_debug():
                    ftlog.debug("tag not match", caller=self)
                continue

            roomSortId = room.roomConf.get("sortId", 0)
            roomIndex = room.bigRoomId % 1000
            if roomSortId > 0 and roomSortId < 1000:
                if chip >= self.VIP_ROOM_LIST_REVERSE_CHIPS:
                    roomSortId = roomIndex
                else:
                    roomSortId = 1000 - roomIndex
            roomInfo = {"roomId": room.bigRoomId, "roomSortId": roomSortId}
            roomList.append(roomInfo)

            if ftlog.is_debug():
                ftlog.debug("|roomId, secretConf:", room.roomId, room.roomConf.get("secretConf"), caller=self)
            if room.isSecretRoom():

                if len(self.maptable) < 1:
                    continue

                table = room.maptable.values()[0]
                if not table.checkSecretCondition(userId, clientId):
                    continue

                tableinfo = {}
                tableinfo["maxPlayerNum"] = table.maxSeatN
                tableinfo["playerNum"] = 0
                tableinfo["tableId"] = 0
                tableinfo["roomId"] = room.roomId
                tableinfo["type"] = room.roomConf["typeName"]
                tableinfo["sortId"] = room.roomConf.get("sortId", 0)
                tableinfo["isSecrect"] = True
                table.updateTableListInfo(tableinfo, clientId)
                vip_tableList.append(tableinfo)
                continue

            if not room._activeTables:
                room._initActiveTables()

            for tableId, table in room.sortedActiveTablesWithId():
                tableinfo = {}
                tableinfo["maxPlayerNum"] = table.maxSeatN
                tableinfo["playerNum"] = table.playersNum
                tableinfo["tableId"] = tableId
                tableinfo["roomId"] = table.room.roomId
                tableinfo["type"] = table.room.roomConf["typeName"]
                tableinfo["sortId"] = table.room.roomConf.get("sortId", 0)
                tableinfo["listBG"] = room.roomConf.get("listBG", "normal")
                table.updateTableListInfo(tableinfo, clientId)
                if self.isLiveShowRoom() and not tableinfo.get("creatorId"):
                    continue
                vip_tableList.append(tableinfo)

                #         def tableListComparer(x, y):
                #             if x["playerNum"] == x["maxPlayerNum"] :
                #                 if y["playerNum"] == y["maxPlayerNum"] :
                #                     return y["sortId"] - x["sortId"]
                #                 else :
                #                     return 1
                #
                #             if y["playerNum"] == y["maxPlayerNum"] :
                #                 return -1
                #
                #             return x["sortId"] - y["sortId"]

                #         vip_tableList = sorted(vip_tableList, cmp=lambda x, y : tableListComparer(x, y))

        TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_GET_VIP_TABLE_LIST', params={
            'table': self, 'vip_tableList': vip_tableList}), self.gameId)

        for t in vip_tableList:
            del t['sortId']

        results = {"gameId": self.gameId}
        results['tables'] = vip_tableList
        results['roomList'] = roomList

        return results
Beispiel #40
0
    def buildActivityInfo(self, userId, activityModel=None, userModel=None):
        clientconf = copy.deepcopy(self._clientConf)
        serverconf = self._serverConf
        ftlog.debug('BetGuess.buildActivityInfo:', 'userId=', userId,
                    'serverconf=', serverconf, 'clientconf=', clientconf)

        activityGameId = clientconf.get('activityGameId')
        activityId = self.getid()

        # 计算当前最新的期号(当前要执行的期)
        issueNumber = self.issueCalculator.getCurrentIssueNumber(
        ) or self.issueCalculator.getLastIssueNumber()
        ftlog.debug('BetGuess.buildActivityInfo:issueNumber=', issueNumber)

        # 加载活动数据
        activityModel = activityModel or ActivityModel.loadModel(
            activityGameId, activityId, issueNumber)
        userModel = userModel or ActivityUserModel.loadModel(
            userId, activityGameId, activityId)
        userModelItem = userModel.findOrCreateItemByIssueNumber(issueNumber)

        ftlog.debug('BetGuess.buildActivityInfo:activityModel=',
                    activityModel.__dict__)
        ftlog.debug('BetGuess.buildActivityInfo:userModel=',
                    userModel.__dict__)

        # 单期的配置
        issueConf = copy.deepcopy(
            self.issueCalculator.getCurrentIssueConf(issueNumber))
        ftlog.debug('BetGuess.buildActivityInfo:issueConf=', issueConf)

        # 抽水比例
        bankerPumping = issueConf.get('bankerPumping', 0)
        issueConf.pop('bankerPumping')
        # 奖池金额
        betPoolChip = int(
            (activityModel.countChipLeft + activityModel.countChipRight) *
            (1 - bankerPumping))
        # 左赔率
        leftBetOdds = betPoolChip / activityModel.countChipLeft if activityModel.countChipLeft > 0 else 0
        # 右赔率
        rightBetOdds = betPoolChip / activityModel.countChipRight if activityModel.countChipRight > 0 else 0

        activityClient = {}
        activityClient.update(issueConf)

        activityClient['leftSide']['betChip'] = userModelItem.leftBetValue
        activityClient['leftSide']['betOdds'] = leftBetOdds

        activityClient['rightSide']['betChip'] = userModelItem.rightBetValue
        activityClient['rightSide']['betOdds'] = rightBetOdds

        activityClient['userChip'] = userchip.getChip(userId)
        activityClient['betPoolChip'] = betPoolChip
        activityClient['currentIssueNumber'] = issueNumber

        issueDateFormat = Tool.dictGet(clientconf,
                                       'config.server.issueDateFormat',
                                       '%m月%d日%H:%M')
        issueDatetime = Tool.datetimeFromString(issueNumber)
        activityClient['issueDate'] = issueDatetime.strftime(issueDateFormat)
        activityClient['betRecords'] = self.buildHistoryRecordList(
            activityGameId, activityId, userModel)

        ftlog.debug('BetGuess.buildActivityInfo:activityClient=',
                    activityClient)

        clientconf['config']['client'].update(activityClient)
        return clientconf
def _canQuickEnterRoom(cls, userId, roomId, innerTable=0, mixId=''):
    try:
        clientId = sessiondata.getClientId(userId)
        ret = comm_table_remote.checkUserQuitLoc(DIZHU_GAMEID, userId, roomId,
                                                 clientId)
        if ret == -1:
            return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_INNER_ERROR
        elif ret == 1:
            return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_QUIT_ROOM_ERROR
        else:
            pass

        chip = userchip.getChip(userId)
        if ftlog.is_debug():
            ftlog.debug(gdata.roomIdDefineMap()[roomId].configure)

        roomConfig = gdata.roomIdDefineMap()[roomId].configure
        if roomConfig.get('isMix', 0):
            mixConf = cls.getMixConf(roomConfig,
                                     mixId) or roomConfig.get('mixConf')[0]
            minCoin = cls.getMixConf(roomConfig, mixId).get('minCoin', 0)
            kickOutCoin = cls.getMixConf(roomConfig,
                                         mixId).get('kickOutCoin', 0)
            roomConfig = mixConf

        elif roomConfig.get(
                'typeName') == 'dizhu_arena_match' and roomConfig.get(
                    'matchConf', {}).get('feeRewardList', []):
            mixConf = cls.getArenaMixConf(roomConfig, mixId) or roomConfig.get(
                'matchConf', {}).get('feeRewardList', [])[0]
            mixConfDisplayCond = mixConf.get('displayCond', {})
            if mixConfDisplayCond:
                displayCond = UserConditionRegister.decodeFromDict(
                    mixConfDisplayCond)
                ret = displayCond.check(DIZHU_GAMEID, userId, clientId,
                                        pktimestamp.getCurrentTimestamp())
                if not ret:
                    return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_NOT_OPEN

            # 准入时间判断
            if not cls._checkOpenTime(mixConf, datetime.now().time()):
                return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_NOT_OPEN
            minCoin = cls.getArenaMixConf(roomConfig, mixId).get('minCoin', 0)
            kickOutCoin = cls.getArenaMixConf(roomConfig,
                                              mixId).get('kickOutCoin', 0)
            minQuickStartChip = cls.getArenaMixConf(roomConfig, mixId).get(
                'minQuickStartChip', 0)
            userChip = userchip.getChip(userId)
            if userChip < minQuickStartChip:
                return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_LESS_MIN
        else:
            minCoin = roomConfig['minCoin']
            kickOutCoin = roomConfig.get('kickOutCoin', 0)

        if ftlog.is_debug():
            ftlog.debug('DizhuQuickStart._canEnterRoom roomId =',
                        roomId,
                        'minCoin =',
                        minCoin,
                        'chip =',
                        chip,
                        caller=cls)

        if innerTable == 0:
            if minCoin > 0 and chip < minCoin:
                return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_LESS_MIN
        else:
            if kickOutCoin > 0 and chip < kickOutCoin:
                return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_LESS_MIN

        # 房间开放判断
        if not dizhuhallinfo.canDisplayRoom(DIZHU_GAMEID, userId, clientId,
                                            roomId, roomConfig):
            if ftlog.is_debug():
                ftlog.debug('DizhuQuickStart._canEnterRoom NotCanDisplayRoom',
                            'gameId=', DIZHU_GAMEID, 'userId=', userId,
                            'clientId=', clientId, 'roomId=', roomId)
            return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_NOT_OPEN

        # 准入时间判断
        if not cls._checkOpenTime(roomConfig, datetime.now().time()):
            return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_NOT_OPEN

        # 其他条件判断,比如VIP, 大师分等
        result, msg = cls._validEnterRoomConditions(DIZHU_GAMEID, userId,
                                                    clientId, roomId,
                                                    roomConfig)
        if not result:
            return ENTER_ROOM_REASON_TYPE_CONDITION, msg
        return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_OK
    except Exception as e:
        ftlog.error(e)
        return ENTER_ROOM_REASON_TYPE_NORMAL, ENTER_ROOM_REASON_INNER_ERROR
def _quickStart(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

    mixId = msg.getParam('mixId', '')
    _, version, _ = strutil.parseClientId(clientId)
    if ftlog.is_debug():
        ftlog.debug("DizhuQuickStart._quickStart: clientId=", clientId,
                    "userId=", userId, "roomId=", roomId, "tableId=",
                    tableId, "mixId=", mixId, "version=", version, "type:",
                    type(version), "playMode=", playMode)

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

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

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

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

    if tableId == 0:  # 玩家只选择了房间
        if roomId != bigRoomId:
            ctrlRoomId = gdata.roomIdDefineMap()[roomId].parentId or roomId
            queryRoomId = roomId
        else:
            ctrRoomIds = gdata.bigRoomidsMap()[bigRoomId]
            ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]
            queryRoomId = ctrlRoomId

        buyin = msg.getParam("buyin", 0)  # 兼容 pc
        innerTable = msg.getParam("innerTable", 0)  # innerTable 区分不同版本弹窗

        if ftlog.is_debug():
            ftlog.debug('DizhuQuickStart._quickStart', 'buyin=', buyin,
                        'innerTable=', innerTable, 'mixId=', mixId)

        if buyin:
            innerTable = 1

        roomdef = gdata.roomIdDefineMap()[ctrlRoomId]
        roomConf = roomdef.configure

        # 免费场重起maxCoin配置
        maxCoin = roomConf.get('maxCoin', 0)
        userChip = userchip.getChip(userId)
        if maxCoin > 0 and userChip >= maxCoin and innerTable == 0:
            cls._onEnterRoomFailed(msg, ENTER_ROOM_REASON_GREATER_MAX, userId,
                                   clientId, roomId)
            return
        # 混房的话从大到小选择一个mixId
        if roomConf.get('isMix') and not mixId:
            _, _, mixId = cls._chooseRoom(userId, [ctrlRoomId])
            if mixId:
                msg.setParam('mixId', mixId)
            else:
                msg.setParam('mixId', roomConf.get('mixConf')[0].get('mixId'))
                if innerTable == 0:
                    cls._onEnterRoomFailed(msg, ENTER_ROOM_REASON_LESS_MIN,
                                           userId, clientId, roomId)
                else:
                    mixConf = cls.getMixConf(
                        roomConf,
                        roomConf.get('mixConf')[0].get('mixId'))
                    new_table_remote.processLoseRoundOver(
                        DIZHU_GAMEID,
                        userId,
                        clientId,
                        mixConf.get('roomId'),
                        minCoin=mixConf.get('minCoin'))
                return
        reasonType, reason = cls._canQuickEnterRoom(userId, ctrlRoomId,
                                                    innerTable, mixId)
        if reason == ENTER_ROOM_REASON_OK:
            TYRoomMixin.queryRoomQuickStartReq(msg, queryRoomId,
                                               0)  # 请求转给GR或GT
        else:
            if reasonType == ENTER_ROOM_REASON_TYPE_NORMAL:
                if reason == ENTER_ROOM_REASON_NOT_OPEN and innerTable == 1:
                    if ftlog.is_debug():
                        ftlog.debug(
                            'DizhuQuickStart._quickStart not open userId=',
                            userId, 'roomId=', ctrlRoomId, 'msg=', msg,
                            'playmode=', playMode)
                    # 直接踢出房间
                    mp = MsgPack()
                    mp.setCmd('room')
                    mp.setParam('action', 'leave')
                    mp.setParam('reason', TYRoom.LEAVE_ROOM_REASON_ACTIVE)
                    mp.setParam('gameId', gameId)
                    mp.setParam('roomId', roomId)
                    mp.setParam('userId', userId)
                    router.sendRoomServer(mp, roomId)
                    return

                if reason == ENTER_ROOM_REASON_LESS_MIN or reason == ENTER_ROOM_REASON_GREATER_MAX:
                    if innerTable == 1:
                        ctrRoomIds = gdata.bigRoomidsMap()[bigRoomId]
                        ctrlRoomId = ctrRoomIds[userId % len(ctrRoomIds)]
                        if roomdef.configure.get('isMix', 0):
                            continueLuckyGift = cls.getMixConf(
                                roomdef.configure,
                                mixId).get('continueLuckyGift', 0)
                            continueLuckyVer = cls.getMixConf(
                                roomdef.configure,
                                mixId).get('continueLuckyVer', 0)
                        else:
                            continueLuckyGift = roomdef.configure.get(
                                'continueLuckyGift', 0)
                            continueLuckyVer = roomdef.configure.get(
                                'continueLuckyVer', 0)
                        dizhuVersion = SessionDizhuVersion.getVersionNumber(
                            userId)
                        if continueLuckyGift and dizhuVersion >= continueLuckyVer:
                            # 发送转运礼包
                            if ftlog.is_debug():
                                ftlog.debug(
                                    'DizhuQuickStart._quickStart _less_min userId=',
                                    userId, 'roomId=', ctrlRoomId, 'msg=', msg,
                                    'playmode=', playMode,
                                    'continueLuckyGift=', continueLuckyGift,
                                    'continueLuckyVer=', continueLuckyVer,
                                    'dizhuVersion=', dizhuVersion)
                            if mixId and roomConf.get('isMix'):
                                mixConf = cls.getMixConf(roomConf, mixId)
                                new_table_remote.processLoseRoundOver(
                                    DIZHU_GAMEID,
                                    userId,
                                    clientId,
                                    mixConf.get('roomId'),
                                    minCoin=mixConf.get('minCoin'))
                            else:
                                new_table_remote.processLoseRoundOver(
                                    DIZHU_GAMEID, userId, clientId, roomId)
                        else:
                            roomDef = gdata.roomIdDefineMap()[ctrlRoomId]
                            playMode = roomDef.configure.get('playMode', None)
                            if ftlog.is_debug():
                                ftlog.debug(
                                    'DizhuQuickStart._quickStart _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(
                                    'DizhuQuickStart._quickStart 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._sendTodoTaskToUserWithTip(userId, reason)
        return

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

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

    if onlineSeat:
        # 牌桌里坐着的玩家断线重连,请求转给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
    return
Beispiel #43
0
 def getChip(cls, userId):
     '''
     获取用户的金币数
     '''
     return userchip.getChip(userId)
Beispiel #44
0
    def _doFlipcard(self, userId, gameId, clientId, activityId, coin):
        result = {}
        key = "TYActivity:%d:%d:%s:%s" % (gameId, userId, clientId, activityId)
        ftlog.debug("_doFlipcard key:", key)
        conf = {
            "design": {
                "1": {
                    "name": "豹子A",
                    "payrate": 20,
                    "probability": 0.0001
                },
                "2": {
                    "name": "豹子",
                    "payrate": 20,
                    "probability": 0.0012
                },
                "3": {
                    "name": "同花顺",
                    "payrate": 15,
                    "probability": 0.001
                },
                "4": {
                    "name": "同花",
                    "payrate": 3,
                    "probability": 0.01
                },
                "5": {
                    "name": "顺子",
                    "payrate": 3,
                    "probability": 0.01
                },
                "6": {
                    "name": "对子",
                    "payrate": 1.5,
                    "probability": 0.1
                },
                "7": {
                    "name": "K以上单张",
                    "payrate": 1.2,
                    "probability": 0.3
                },
                "8": {
                    "name": "单张",
                    "payrate": 0,
                    "probability": 0.5777
                }
            }
        }

        # 判断用户金币是否足够
        chipNow = userchip.getChip(userId)
        if coin == 1000 and chipNow < 5000:
            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 20,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(
                gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        elif coin == 5000 and chipNow < 50000:

            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 80,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(
                gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        elif coin == 10000 and chipNow < 50000:
            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 80,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(
                gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        elif coin == 50000 and chipNow < 300000:
            payOrder = {
                "shelves": ["coin"],
                "buyTypes": ["direct"],
                "priceDiamond": {
                    "count": 300,
                    "minCount": 0,
                    "maxCount": -1
                }
            }
            product, _ = hallstore.findProductByPayOrder(
                gameId, userId, clientId, payOrder)
            payOrder = TodoTaskPayOrder(product)
            result["tip"] = payOrder.toDict()
            return result
        else:
            result = doFlipCard(conf)
            ftlog.debug("_doFlipcard result..cardtype:", result["cardtype"])
            # 减金币操作
            coinDel = 0 - coin
            userchip.incrChip(userId, gameId, coinDel,
                              daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO,
                              'HALL_FLIPCARD', 0, clientId)
            datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
            ftlog.info("用户名,用户减少了金币,", userId, coinDel)
            if result["cardtype"] != '8':
                design = conf.get('design', {})
                cardTypeNumber = design[result["cardtype"]].get('payrate', 0)

                # 加金币操作
                coinAdd = int(coin * cardTypeNumber)
                cardText = "恭喜你赢得了%d" % coinAdd + "金币"
                ftlog.debug("_doFlipcard get money:", cardText)
                userchip.incrChip(userId, gameId, coinAdd,
                                  daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO,
                                  'HALL_FLIPCARD', 0, clientId)
                datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
                ftlog.info("用户名,用户增加了金币,", userId, coinAdd)
                result["todoTask"] = {
                    "action": "pop_tip",
                    "params": {
                        "text": cardText,
                        "duration": 2
                    }
                }
                return result
            else:
                cardText = "再接再厉,下次就会赢哦"
                result["todoTask"] = {
                    "action": "pop_tip",
                    "params": {
                        "text": cardText,
                        "duration": 2
                    }
                }
                ftlog.debug("_doFlipcard key over:", key)
                return result
        '''