Ejemplo n.º 1
0
    def putTiles(self):
        if not self._passThis():
            return {'info': 'can not use this tool !', 'code': 1}

        play_mode = runhttp.getParamStr('play_mode')
        seat1 = runhttp.getParamStr('seat1', '')
        seat2 = runhttp.getParamStr('seat2', '')
        seat3 = runhttp.getParamStr('seat3', '')
        seat4 = runhttp.getParamStr('seat4', '')
        jing  = runhttp.getParamStr('jing', '')
        laizi = runhttp.getParamStr('laizi', '')
        pool  = runhttp.getParamStr('pool')
        ftlog.debug('play_mode =', play_mode, 'seat1 =', seat1, 'seat2 =', seat2, 'seat3 =', seat3,
                    'seat4 =', seat4, 'jing=', jing,'laizi=',laizi, 'pool =', pool, caller=self)

        tile_info = {
                     'seat1':       self._splitTiles(seat1),
                     'seat2':       self._splitTiles(seat2),
                     'seat3':       self._splitTiles(seat3),
                     'seat4':       self._splitTiles(seat4),
                     'jing':        self._splitTiles(jing),
                     'pool':        self._splitTiles(pool),
                     'laizi':       self._splitTiles(laizi)
                     }
        key = 'put_card:' + play_mode
        daobase.executeMixCmd('set', key, json.dumps(tile_info))
        return {'info': 'ok', 'code': 0}
Ejemplo n.º 2
0
 def signout(self, userId, matchId, ctrlRoomId, instId, feeContentItem):
     '''
     '''
     # 去UT退报名费,并删除用户报名记录
     # 删除用户报名记录
     contentItem = {
         'itemId': feeContentItem.assetKindId,
         'count': feeContentItem.count
     } if feeContentItem else None
     try:
         key = 'msignin3:%s:%s:%s' % (self._room.gameId, instId, ctrlRoomId)
         daobase.executeMixCmd('zrem', key, userId)
         daobase.executeTableCmd(self._room.roomId, 0, 'SREM',
                                 'signs:' + str(self._room.roomId), userId)
     except:
         self._logger.error('SignIFDizhu.signout error', 'userId=', userId,
                            'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId,
                            'instId=', instId, 'fee=', contentItem)
     try:
         match_remote.signoutMatch(DIZHU_GAMEID, userId, contentItem,
                                   self._room.bigRoomId, instId,
                                   self._room.roomId)
         self._logger.info('SignIFDizhu.signout ok', 'userId=', userId,
                           'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId,
                           'instId=', instId, 'fee=', contentItem)
     except:
         self._logger.error('SignIFDizhu.signout fail', 'userId=', userId,
                            'matchId=', matchId, 'ctrlRoomId=', ctrlRoomId,
                            'instId=', instId, 'fee=', contentItem)
Ejemplo n.º 3
0
def make_order_id(appId, orderIdVer62, httpcallback=None, isRemote=False):
    if gdata.mode() == gdata.RUN_MODE_ONLINE or isRemote:
        appId = int(appId)
        seqNum = daobase.executeMixCmd('INCR', 'global.orderid.seq.' + orderIdVer62)
        # orderId构成:<1位API版本号>+<4位APPID>+DD+<5位序号>,共14位
        ct = datetime.now()
        dd = ct.strftime('%d')
        a = hex(appId)[2:][-4:]
        a = '0' * (4 - len(a)) + a
        b = hex(seqNum)[2:][-7:]
        b = '0' * (7 - len(b)) + b
        oid = orderIdVer62 + a + dd + b
        # 记录单号回应的回调地址
        if httpcallback != None and isinstance(httpcallback, (str, unicode)) and httpcallback.find('http://') == 0:
            daobase.executeMixCmd('HSET', 'global.orderid.callback', oid, httpcallback)
        return oid
    else:
        # 通知订单数据中心(线上GATEWAY服务), 产生了一个新订单, 需要进行 单号<->回调服务的记录
        httpurl = gdata.httpOnlieGateWay() + '/_testorder_make_id'
        datas = {
            'appId': appId,
            'orderIdVer62': orderIdVer62,
            'httpcallback': gdata.httpSdk()
        }
        result, _ = webpage.webgetJson(httpurl, datas, None, 10)
        return result['orderPlatformId']
Ejemplo n.º 4
0
    def exchange_prize_code(cls, excode, mobile=0):
        """
        兑换奖品
        """
        ret, prize_id = cls.check_excode(excode)
        info = ''
        if ret != 0:
            if ret == 2:
                info = '已经兑换过了哦'
            else:
                info = '兑换失败'
            return ret, prize_id, info
        excode_str = daobase.executeMixCmd('hget', cls.key_excodes, excode)
        excode_json = json.loads(excode_str)
        excode_json['finish'] = 1
        uid = excode_json['uid']
        prize_id = excode_json.get('prize_id', 0)
        daobase.executeMixCmd('hset', cls.key_excodes, excode,
                              json.dumps(excode_json))

        ftlog.debug('exchange_prize_code', excode)
        if prize_id == 3:
            info = '恭喜获得7天优酷VIP,激活码是7676,请登录优酷官网进行激活'
            smsdown.SmsDownManDao.sendSms(mobile, info)
        return 0, prize_id, '兑换成功'
Ejemplo n.º 5
0
    def exchange_user_vip_charge(cls, gameId, userId, grade):
        """
        用户兑换vip充值金币
        """
        ftlog.debug('exchange_user_vip_charge', gameId, userId, grade)
        grade = str(grade)
        vip_charge_info = cls.get_user_vip_charge(userId)
        if not vip_charge_info:
            return 1

        grade_data = vip_charge_info.get(str(grade))
        if not grade_data:
            return 1

        ftlog.debug('exchange_user_vip_charge exchanged',
                    grade_data['exchanged'])
        if grade_data['exchanged']:
            return 2

        grade_data['exchanged'] = 1
        daobase.executeMixCmd('hset', cls.key_vip_charge, userId,
                              json.dumps(vip_charge_info))

        chip = cls.VIP_COIN_CONFIG[grade]
        try:
            userchip.incrChip(userId, gameId, chip, 0,
                              'H5_YOUKU_DIZHU_VIP_EXCHANGE_CHIP', 0, None)
        except:
            import traceback
            traceback.print_exc()
        datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
        return 0
Ejemplo n.º 6
0
def httpTodayCallback(httpObj):
    if httpObj:
        ftlog.info('hallsportlottery.httpTodayCallback', 'httpObj=', httpObj,
                   'httpContents=', httpObj.httpContents)

        global _sportlotteryMap

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

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

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

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

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

        del httpObj
Ejemplo n.º 7
0
def getGlobal(gameId, userId, pageNo=1):
    """
    已废弃,待删除
    取得当前用户的全局未读私信的内容
    """
    maxMsgId = daobase.executeMixCmd('HGET', 'msg',
                                     'msg.id.max.' + str(gameId))
    readMaxId = gamedata.getGameAttrs(userId, gameId, 'msg.id.global')
    rediskey = 'msg:' + str(gameId)

    maxMsgId, readMaxId = strutil.parseInts(maxMsgId, readMaxId)
    msglist = []
    maxId = readMaxId
    if pageNo < 1:
        pageNo = 1
    lstart = (pageNo - 1) * 20
    lend = lstart + 20 - 1
    datas = daobase.executeMixCmd('LRANGE', rediskey, lstart, lend)
    count = 0
    if datas:
        for msgstr in datas:
            msg = strutil.loads(msgstr, ignoreException=True)
            if msg:
                maxId = max(maxId, msg['id'])
                msglist.append(msg)
                count += 1
    if maxId > readMaxId:
        gamedata.setGameAttr(userId, gameId, 'msg.id.global', maxId)
    return {
        'count': count,
        'maxId': maxMsgId,
        'readId': readMaxId,
        'pageNo': pageNo,
        'list': msglist
    }
Ejemplo n.º 8
0
def _initialize():
    """初始化100万个自建桌房号"""
    if gdata.serverType() != gdata.SRV_TYPE_CENTER:
        return

    ftlog.debug(
        'hall_friend_table._initialize check friend table randoms in process CT'
    )
    randomLen = daobase.executeMixCmd('LLEN', FRIEND_TABLE_RANDOM_KEY)
    ftlog.debug('hall_friend_table._initialize randomLen:', randomLen)

    if randomLen != FRIEND_TABLE_RANDOM_COUNT:
        ftlog.debug('hall_friend_table._initialize push random begin:',
                    pktimestamp.getCurrentTimestamp())

        daobase.executeMixCmd('DEL', FRIEND_TABLE_RANDOM_KEY)
        rList = [x for x in range(0, 1000000)]
        random.shuffle(rList)

        # 每次PUSH 100个
        for index in range(0, 10000):
            begin = index * 100
            daobase.executeMixCmd(
                'LPUSH', FRIEND_TABLE_RANDOM_KEY, rList[begin],
                rList[begin + 1], rList[begin + 2], rList[begin + 3],
                rList[begin + 4], rList[begin + 5], rList[begin + 6],
                rList[begin + 7], rList[begin + 8], rList[begin + 9],
                rList[begin + 10], rList[begin + 11], rList[begin + 12],
                rList[begin + 13], rList[begin + 14], rList[begin + 15],
                rList[begin + 16], rList[begin + 17], rList[begin + 18],
                rList[begin + 19], rList[begin + 20], rList[begin + 21],
                rList[begin + 22], rList[begin + 23], rList[begin + 24],
                rList[begin + 25], rList[begin + 26], rList[begin + 27],
                rList[begin + 28], rList[begin + 29], rList[begin + 30],
                rList[begin + 31], rList[begin + 32], rList[begin + 33],
                rList[begin + 34], rList[begin + 35], rList[begin + 36],
                rList[begin + 37], rList[begin + 38], rList[begin + 39],
                rList[begin + 40], rList[begin + 41], rList[begin + 42],
                rList[begin + 43], rList[begin + 44], rList[begin + 45],
                rList[begin + 46], rList[begin + 47], rList[begin + 48],
                rList[begin + 49], rList[begin + 50], rList[begin + 51],
                rList[begin + 52], rList[begin + 53], rList[begin + 54],
                rList[begin + 55], rList[begin + 56], rList[begin + 57],
                rList[begin + 58], rList[begin + 59], rList[begin + 60],
                rList[begin + 61], rList[begin + 62], rList[begin + 63],
                rList[begin + 64], rList[begin + 65], rList[begin + 66],
                rList[begin + 67], rList[begin + 68], rList[begin + 69],
                rList[begin + 70], rList[begin + 71], rList[begin + 72],
                rList[begin + 73], rList[begin + 74], rList[begin + 75],
                rList[begin + 76], rList[begin + 77], rList[begin + 78],
                rList[begin + 79], rList[begin + 80], rList[begin + 81],
                rList[begin + 82], rList[begin + 83], rList[begin + 84],
                rList[begin + 85], rList[begin + 86], rList[begin + 87],
                rList[begin + 88], rList[begin + 89], rList[begin + 90],
                rList[begin + 91], rList[begin + 92], rList[begin + 93],
                rList[begin + 94], rList[begin + 95], rList[begin + 96],
                rList[begin + 97], rList[begin + 98], rList[begin + 99])

        ftlog.debug('hall_friend_table._initialize push random end:',
                    pktimestamp.getCurrentTimestamp())
Ejemplo n.º 9
0
def sportlotteryBet(gameId, clientId, userId, date, matchId, party, coin):
    if coin <= 0:
        raise SportlotteryBadBetException()

    if party not in (1, 2, 3):
        raise SportlotteryBetPosErrorException()

    jstr = daobase.executeMixCmd('hget', leagueDaykey % date, matchId)
    leagueId = 0  #
    homewin = 0.0
    if jstr:
        j = strutil.loads(jstr)
        leagueId = int(j.get('leagueId', 0))
        homewin = float(j.get('odds', ['0', '0', '0'])[0])
        if j.get('status') not in BET_STATUS:
            raise SportlotteryForbidBetException()
    else:
        raise SportlotteryMatchOverException()

    homeBet = daobase.executeUserCmd(userId, 'hget', betHomeKey % userId,
                                     '%s:%s' % (date, matchId)) or 0
    aveBet = daobase.executeUserCmd(userId, 'hget', betAveKey % userId,
                                    '%s:%s' % (date, matchId)) or 0
    awayBet = daobase.executeUserCmd(userId, 'hget', betAwayKey % userId,
                                     '%s:%s' % (date, matchId)) or 0

    # 获取总金额
    totalBet = int(homeBet) + int(aveBet) + int(awayBet)
    if totalBet + coin > SportlotteryConf.totalBetLimit():
        tips = SportlotteryConf.totalBetLimitTips()
        if tips:
            raise SportlotteryBetOverLimitException(tips)
        raise SportlotteryBetOverLimitException()

    trueDelta, final = addChip(userId, gameId, clientId, -coin, leagueId,
                               homewin, party)

    if abs(trueDelta) < coin:
        raise SportlotteryChipNotEnoughException()

    if party == 1:
        daobase.executeUserCmd(userId, 'hincrby', betHomeKey % userId,
                               '%s:%s' % (date, matchId), coin)
    elif party == 2:
        daobase.executeUserCmd(userId, 'hincrby', betAveKey % userId,
                               '%s:%s' % (date, matchId), coin)
    elif party == 3:
        daobase.executeUserCmd(userId, 'hincrby', betAwayKey % userId,
                               '%s:%s' % (date, matchId), coin)
    else:
        raise SportlotteryBetPosErrorException()

    # 联赛下注总人数
    daobase.executeMixCmd('sadd', leagueBetPlayersKey % (date, matchId),
                          userId)
    # 联赛下注总钱数
    daobase.executeMixCmd('hincrby', leagueBetChipsKey % (date, matchId),
                          party, coin)

    return final
Ejemplo n.º 10
0
def make_order_id(appId, orderIdVer62, httpcallback=None, isRemote=False):
    if gdata.mode() == gdata.RUN_MODE_ONLINE or isRemote:
        appId = int(appId)
        seqNum = daobase.executeMixCmd('INCR',
                                       'global.orderid.seq.' + orderIdVer62)
        # orderId构成:<1位API版本号>+<4位APPID>+DD+<5位序号>,共14位
        ct = datetime.now()
        dd = ct.strftime('%d')
        a = hex(appId)[2:][-4:]
        a = '0' * (4 - len(a)) + a
        b = hex(seqNum)[2:][-7:]
        b = '0' * (7 - len(b)) + b
        oid = orderIdVer62 + a + dd + b
        # 记录单号回应的回调地址
        if httpcallback != None and isinstance(
                httpcallback,
            (str, unicode)) and httpcallback.find('http://') == 0:
            daobase.executeMixCmd('HSET', 'global.orderid.callback', oid,
                                  httpcallback)
        return oid
    else:
        # 通知订单数据中心(线上GATEWAY服务), 产生了一个新订单, 需要进行 单号<->回调服务的记录
        httpurl = gdata.httpOnlieGateWay() + '/_testorder_make_id'
        datas = {
            'appId': appId,
            'orderIdVer62': orderIdVer62,
            'httpcallback': gdata.httpSdk()
        }
        result, _ = webpage.webgetJson(httpurl, datas, None, 10)
        return result['orderPlatformId']
Ejemplo n.º 11
0
def releaseFTId(ftId):
    try:
        daobase.executeMixCmd('del', 'ft:6:%s' % (ftId))
        hall_friend_table.releaseFriendTable(DIZHU_GAMEID, ftId)
    except:
        ftlog.error('ft_service.releaseFTId',
                    'ftId=', ftId)
Ejemplo n.º 12
0
 def autoRemoveOvertopReocrdIfNeed(cls):
     '''
     如果需要就会自动删除超出`leastRecordNumber`个数的元素
     '''
     length = daobase.executeMixCmd('llen', cls.recordUniqueKey)
     if length > cls.removeTriggerLimitNumber:
         daobase.executeMixCmd('ltrim', cls.recordUniqueKey, 0, cls.leastRecordNumber - 1)
Ejemplo n.º 13
0
 def assignFriendTableId(self, gameId, tableId):
     '''分配房间号, 并将房间号保存到redis中,方便查找'''
     ftId = hall_friend_table.createFriendTable(gameId)
     if ftId:
         daobase.executeMixCmd('HSET', self.REDIS_KEY_ROOM_NO_TO_TABLE_ID + str(gameId), ftId, tableId)
     else:
         ftlog.error("assign roomNo error! |gameId, tableId:", gameId, tableId)
     return ftId
Ejemplo n.º 14
0
 def removeAll(self, matchId, instId):
     try:
         key = 'msignin2:%s:%s' % (self._room.gameId, instId)
         daobase.executeMixCmd('del', key)
         daobase.executeTableCmd(self._room.roomId, 0, 'DEL',
                                 'signs:' + str(self._room.roomId))
     except:
         ftlog.error()
Ejemplo n.º 15
0
 def _doExchange(self, userId, gameId, clientId, activityId, excode):
     if len(excode) != 16 and len(excode) != 5 and len(excode) != 18: 
         self.sendTodoTask(gameId, userId,"兑换码错误!")
         return {"exchangeInfo":"兑换码错误!"}
     if len(excode) == 5:
         rdskey = activityId          
     else:
         excode = excode.upper()
         rdskey = excode[0:6]
     ftlog.debug('this exchange rdskey = ', rdskey,
                 'this exchange clientId = ',clientId)
     #核对公共配置信息,返回(核对结果,错误信息,unique,可领取次数) 2018-3-20 xy
     result_, errdes_, unique_, receive_num_ = self.__commonCheck(rdskey, clientId)
     if result_ != 0:
         self.sendTodoTask(gameId, userId,errdes_)
         return {"exchangeInfo":errdes_}
     #修改兑换流程,新添加两个参数 clientId,receive_num 2018-3-20 xy
     deviceId = sessiondata.getDeviceId(userId)
     result_ , errdes_ = self.__exchange(rdskey, userId, excode, deviceId, receive_num_, unique_)
     if result_ != 0:
         self.sendTodoTask(gameId, userId, errdes_)
         return {"exchangeInfo":errdes_}
     _rewards = self.__getReward(rdskey,userId, gameId, activityId,excode)
     
     if len(excode) == 18 :
         #将用户Id和推广人Id进行绑定
         common_ = daobase.executeMixCmd('HGET', 'excodeinfo:' + rdskey, 'common')
         try:
             common_ = json.loads(common_)
         except:
             return {}
         nowPromoteId = pkgamedata.getGameAttr(userId, gameId, 'promoteId') or 0
         ftlog.debug('__getReward.userId=', userId,
                     'gameId=', gameId,
                     'common_=', common_,
                     'nowPromoteId=', nowPromoteId)
         if int(nowPromoteId) <= 0 and int(userId) != int(common_.get('promoteId', 0)):
             pkgamedata.setGameAttr(userId, gameId, 'promoteId', common_.get('promoteId', 0))
     
     resultInfo = '恭喜您兑换成功,获得:' + _rewards
     self.sendTodoTask(gameId, userId, resultInfo)
     #兑换码使用成功,记录在用户里
     messageUser = daobase.executeMixCmd('HGET', 'userID:' + str(userId),'common')
     if isinstance(messageUser, (str, unicode)) :
         messageUser = json.loads(messageUser)
     else:
         messageUser = {}
     if 'excode' not in messageUser :
         messageUser = {
                        'userId':userId,
                        'excode':[excode],
                        'time':[datetime.now().strftime('%Y-%m-%d %H:%M:%S')]
                        }
     else:
         messageUser['excode'].append(excode)
         messageUser['time'].append(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
     daobase.executeMixCmd('HSET', 'userID:' + str(userId),'common' ,json.dumps(messageUser))
     return {"exchangeInfo": resultInfo}
Ejemplo n.º 16
0
def gameBegin(tableNo, seats, gameId, roomId, tableId):
    """开局日志"""
    ftlog.info('hall_friend_table.gameBegin tableNo=', tableNo, ' seats=',
               seats, ' gameId=', gameId, ' roomId=', roomId, ' tableId=',
               tableId, ' time=', pktimestamp.getCurrentTimestamp())
    daobase.executeMixCmd('HSET', FRIEND_TABLE_MAIN_KEY + tableNo,
                          FRIEND_TABLE_ROOMID, roomId)
    daobase.executeMixCmd('HSET', FRIEND_TABLE_MAIN_KEY + tableNo,
                          FRIEND_TABLE_TABLEID, tableId)
Ejemplo n.º 17
0
def releaseFriendTable(pluginId, ftId):
    '''
    回收大厅自建桌房号
    pluginId 插件游戏ID
    ftId 大厅自建桌房号
    '''
    ftlog.info('hall_friend_table.releaseFriendTable pluginId:', pluginId
            , ' ftId:', ftId)
    daobase.executeMixCmd('DEL', FRIEND_TABLE_MAIN_KEY + ftId)
Ejemplo n.º 18
0
def releaseFriendTable(pluginId, ftId):
    '''
    回收大厅自建桌房号
    pluginId 插件游戏ID
    ftId 大厅自建桌房号
    '''
    ftlog.info('hall_friend_table.releaseFriendTable pluginId:', pluginId
               , ' ftId:', ftId)
    daobase.executeMixCmd('DEL', FRIEND_TABLE_MAIN_KEY + ftId)
Ejemplo n.º 19
0
 def removeAll(self, matchId, instId, ctrlRoomId):
     key = self.buildKey(matchId, instId, ctrlRoomId)
     if self._logger.isDebug():
         self._logger.debug('SigninRecordDaoRedis.removeAll',
                            'matchId=', matchId,
                            'instId=', instId,
                            'ctrlRoomId=', ctrlRoomId,
                            'key=', key)
     daobase.executeMixCmd('del', key)
Ejemplo n.º 20
0
    def save(self):
        date = datetime.datetime.fromtimestamp(
            self.timestamp).strftime('%Y-%m-%d')
        daobase.executeMixCmd('hset', leagueDaykey % date, self.matchId,
                              strutil.dumps(self.toDict()))

        if ftlog.is_debug():
            ftlog.debug('Sportlottery save', 'date=', date, 'matchId=',
                        self.matchId, 'toDict=', self.toDict())
Ejemplo n.º 21
0
 def findMessageForCdkey(cls, cdkey):
     # 兑换码的信息
     exchange_code = {}
     exchange_code["rewards"] = daobase.executeMixCmd('HGET', 'excodeinfo:' + cdkey, 'rewards')  # list
     exchange_code["common"] = daobase.executeMixCmd('HGET', 'excodeinfo:' + cdkey, 'common')  # Dict
     exchange_code["excodeuser"] = daobase.executeMixCmd('SMEMBERS', 'excodeuser:'******'SMEMBERS', 'excodeready:' + cdkey)  # list
     exchange_code["excodefinish"] = daobase.executeMixCmd('SMEMBERS', 'excodefinish:' + cdkey)  # list
     return exchange_code
Ejemplo n.º 22
0
    def devidePackage(self):
        '''
        将整体红包按照配置分成随机的份数
        '''
        global _redEnvelopeConfig

        # 划分红包
        prizePool = []
        for item in self.contents:
            for _ in range(1, item['count'] + 1):
                prizePool.append(item['itemId'])

        countTotal = len(prizePool)
        random.shuffle(prizePool)

        index = 0

        while index < countTotal:
            # 随机获得红包的个数
            count = random.randint(self.minCount, self.maxCount)
            if index + count >= countTotal:
                count = countTotal - index
            if ftlog.is_debug():
                ftlog.debug('count:', count)

            prizes = {}
            for i in range(0, count):
                # 领取红包
                itemId = prizePool[index + i]
                if itemId in prizes:
                    prizes[itemId] += 1
                else:
                    prizes[itemId] = 1

            if ftlog.is_debug():
                ftlog.debug('prizes:', prizes)

            # 写数据库
            daobase.executeMixCmd('LPUSH',
                                  self.dbPrefix + self.id + self.PACKAGES,
                                  json.dumps(prizes))
            # 记录分包信息
            self.packages_his.append(prizes)

            index += count

        # 设置过期时间
        daobase.executeMixCmd('expire',
                              self.dbPrefix + self.id + self.PACKAGES,
                              self.expiredTime)

        # save result to log
        if ftlog.is_debug():
            checksJson = daobase.executeMixCmd(
                'LRANGE', self.dbPrefix + self.id + self.PACKAGES, 0, -1)
            ftlog.debug('TYRedEnvelope.devidePackage packages: ', checksJson)
Ejemplo n.º 23
0
 def cancelPutTiles(self):
     """ 撤销摆牌
     """
     if not self._passThis():
         return {'info': 'f**k you!', 'code': 1}
     
     play_mode = runhttp.getParamStr('play_mode')
     key = 'put_card:' + play_mode
     daobase.executeMixCmd('del', key)
     return {'info': 'ok', 'code': 0}
Ejemplo n.º 24
0
def gameBegin(tableNo, seats, gameId, roomId, tableId):
    """开局日志"""
    ftlog.info('hall_friend_table.gameBegin tableNo=', tableNo
               , ' seats=', seats
               , ' gameId=', gameId
               , ' roomId=', roomId
               , ' tableId=', tableId
               , ' time=', pktimestamp.getCurrentTimestamp())
    daobase.executeMixCmd('HSET', FRIEND_TABLE_MAIN_KEY + tableNo, FRIEND_TABLE_ROOMID, roomId)
    daobase.executeMixCmd('HSET', FRIEND_TABLE_MAIN_KEY + tableNo, FRIEND_TABLE_TABLEID, tableId)
Ejemplo n.º 25
0
    def cancelPutTiles(self):
        """ 撤销摆牌
        """
        if not self._passThis():
            return {'info': 'f**k you!', 'code': 1}

        play_mode = runhttp.getParamStr('play_mode')
        key = 'put_card:' + play_mode
        daobase.executeMixCmd('del', key)
        return {'info': 'ok', 'code': 0}
Ejemplo n.º 26
0
    def _doExchange(self, userId, gameId, clientId, activityId, excode):
        if len(excode) != 16 and len(excode) != 5 and len(excode) != 18:
            self.sendTodoTask(gameId, userId, "兑换码错误!")
            return {"exchangeInfo": "兑换码错误!"}
        if len(excode) == 5:
            rdskey = activityId
        else:
            excode = excode.upper()
            rdskey = excode[0:6]
        ftlog.debug('this exchange rdskey = ', rdskey,
                    'this exchange clientId = ', clientId)
        result_, errdes_, unique_ = self.__commonCheck(rdskey, clientId)
        if result_ != 0:
            self.sendTodoTask(gameId, userId, errdes_)
            return {"exchangeInfo": errdes_}
        result_, errdes_ = self.__exchange(rdskey, userId, excode, unique_)
        if result_ != 0:
            self.sendTodoTask(gameId, userId, errdes_)
            return {"exchangeInfo": errdes_}
        _rewards = self.__getReward(rdskey, userId, gameId, activityId, excode)

        if len(excode) == 18:
            # 将用户Id和推广人Id进行绑定
            common_ = daobase.executeMixCmd('HGET', 'excodeinfo:' + rdskey, 'common')
            try:
                common_ = json.loads(common_)
            except:
                return {}
            nowPromoteId = pkgamedata.getGameAttr(userId, gameId, 'promoteId') or 0
            ftlog.debug('__getReward.userId=', userId,
                        'gameId=', gameId,
                        'common_=', common_,
                        'nowPromoteId=', nowPromoteId)
            if int(nowPromoteId) <= 0 and int(userId) != int(common_.get('promoteId', 0)):
                pkgamedata.setGameAttr(userId, gameId, 'promoteId', common_.get('promoteId', 0))

        resultInfo = '恭喜您兑换成功,获得:' + _rewards
        self.sendTodoTask(gameId, userId, resultInfo)
        # 兑换码使用成功,记录在用户里
        messageUser = daobase.executeMixCmd('HGET', 'userID:' + str(userId), 'common')
        if isinstance(messageUser, (str, unicode)):
            messageUser = json.loads(messageUser)
        else:
            messageUser = {}
        if 'excode' not in messageUser:
            messageUser = {
                'userId': userId,
                'excode': [excode],
                'time': [datetime.now().strftime('%Y-%m-%d %H:%M:%S')]
            }
        else:
            messageUser['excode'].append(excode)
            messageUser['time'].append(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        daobase.executeMixCmd('HSET', 'userID:' + str(userId), 'common', json.dumps(messageUser))
        return {"exchangeInfo": resultInfo}
Ejemplo n.º 27
0
def sendGlobal(gameId, msg, button=None):
    """
    已废弃,待删除
    发送站内消息到全体游戏用户
    """
    maxid = daobase.executeMixCmd('HINCRBY', 'msg',
                                  'msg.id.max.' + str(gameId))
    ct = timestamp.formatTimeSecond()
    msg = {'id': maxid, 'from': 0, 'time': ct, 'msg': msg}
    daobase.executeMixCmd('LPUSH', 'msg:' + str(gameId), strutil.dumps(msg))
    return 1
Ejemplo n.º 28
0
 def save(self, status):
     '''
     保存比赛信息
     '''
     try:
         key = 'mstatus:%s' % (self._room.gameId)
         d = {'seq': status.sequence, 'startTime': status.startTime}
         jstr = json.dumps(d)
         daobase.executeMixCmd('hset', key, status.matchId, jstr)
     except:
         ftlog.error()
Ejemplo n.º 29
0
 def generate_excode(cls):
     char1 = random.choice(cls.wordlist)
     char2 = random.choice(cls.wordlist)
     key = 'h5:excode:cursor'
     cursor = int(daobase.executeMixCmd('incr', key))
     if cursor < 2:
         cursor = 100
         daobase.executeMixCmd('set', key, cursor)
     code = strutil.tostr62(cursor) + str(char1) + str(char2)
     ftlog.debug('generateExcode', code)
     return code
Ejemplo n.º 30
0
 def removeSignin(self, matchId, instId, userId):
     '''
     删除报名信息
     '''
     try:
         key = 'msignin2:%s:%s' % (self._room.gameId, instId)
         daobase.executeMixCmd('hdel', key, userId)
         daobase.executeTableCmd(self._room.roomId, 0, 'SREM',
                                 'signs:' + str(self._room.roomId), userId)
     except:
         ftlog.error()
Ejemplo n.º 31
0
 def _getPrize(self, itemId=""):
     key = self.dbPrefix + self.id + self.PACKAGES
     if not itemId:
         prizesJson = daobase.executeMixCmd('LPOP', key)
     else:
         global get_content_by_item_sha
         if not get_content_by_item_sha:
             luaName = 'hall_red_envelope_get_content_by_item'
             get_content_by_item_sha = daobase.loadLuaScripts(luaName, get_content_by_item_script)
         prizesJson = daobase.executeMixCmd("EVALSHA", get_content_by_item_sha, 1, key, itemId)
     return prizesJson
Ejemplo n.º 32
0
def getIssue(issueType):
    '''
    期号的统一管理
    '''
    result = ''
    issue = int(daobase.executeMixCmd('HGET', 'allSoldier', 'rouletteIssue') or 0)
    if not issue or issueType:
        count = daobase.executeMixCmd('hincrby', 'allSoldier', 'rouletteIssue', 1)
        result = '%04d' % (count)
    elif not issueType:
        result = '%04d' % (issue)
    return result
Ejemplo n.º 33
0
def getOrderIdHttpCallBack(orderId):
    # 取得单号对应的callback地址, 如果没有Name意味就是本机线上服务单号
    httpcallback = daobase.executeMixCmd('HGET', 'global.orderid.callback', orderId)
    if httpcallback != None and isinstance(httpcallback, (str, unicode)) and httpcallback.find('http://') == 0:
        nsize = daobase.executeMixCmd('HLEN', 'global.orderid.callback')
        if nsize > 10000:
            daobase.executeMixCmd('DEL', 'global.orderid.callback')
            ftlog.error('the test order "global.orderid.callback" too much (> 10000) !! ' +
                        'auto clean up !! some test order maybe callback to online !' +
                        'this is not an error, just a warring !!')
        return httpcallback
    return gdata.httpSdkInner()
Ejemplo n.º 34
0
def sendGiftsToUser(userId, gameId, clientId, items):
    '''
        多个奖品时的发奖,或者一个奖品的发奖,items为数组
    '''
    contentItemList = []
    rouletteMap = getRouletteMap()

    for item in items:
        itemMap = rouletteMap.get(item, {})
        if itemMap:
            #添加判断流程,判断奖励是否需要发送led
            if itemMap.get('isSendLed', False):
                userInfo = halluser.getUserInfo(userId, gameId, clientId)
                msgstr = '恭喜玩家' + userInfo.get(
                    'name', '') + '在幸运大转盘中,抽中了' + itemMap.get(
                        'itemDesc', '') + '大奖!快来参与,大奖得主就是你!'
                hallled.sendLed(HALL_GAMEID, msgstr, 0, 'hall')

                # 轮播LED仅保留最近10条中奖记录
                doRouletteRecordKey = "roulette:recordLed"
                try:
                    datas = {
                        'name': userInfo.get('name', ''),
                        'itemDesc': itemMap.get('itemDesc', '')
                    }
                    recordledLen = daobase.executeMixCmd(
                        'RPUSH', doRouletteRecordKey, json.dumps(datas))
                    if recordledLen > 10:
                        # 超过10个就截取后10个
                        daobase.executeMixCmd('LTRIM', doRouletteRecordKey,
                                              -10, -1)
                except:
                    ftlog.warn("redis rpush|ltrim roulette:recordLed error",
                               gameId, userId, clientId, msgstr)

                ftlog.debug("sendGiftsToUser|1", userId, gameId, clientId,
                            msgstr)
            ftlog.debug("sendGiftsToUser|2", userId, gameId, clientId,
                        itemMap.get('isSendLed'))

            # 添加中奖内容
            contentItemList.append(
                TYContentItem.decodeFromDict({
                    'itemId': itemMap.get('itemId'),
                    'count': itemMap.get('count')
                }))

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    results = userAssets.sendContentItemList(gameId, contentItemList, 1, True,
                                             int(time.time()), 'ROULETTE_GOLD',
                                             0)
    datachangenotify.sendDataChangeNotify(
        gameId, userId, TYAssetUtils.getChangeDataNames(results))
Ejemplo n.º 35
0
 def recordSignin(self, matchId, instId, userId, timestamp, signinParams):
     '''
     记录报名信息
     '''
     try:
         key = 'msignin2:%s:%s' % (self._room.gameId, instId)
         jstr = json.dumps({'st': timestamp, 'sp': signinParams})
         daobase.executeMixCmd('hset', key, userId, jstr)
         daobase.executeTableCmd(self._room.roomId, 0, 'SADD',
                                 'signs:' + str(self._room.roomId), userId)
     except:
         ftlog.error()
Ejemplo n.º 36
0
 def checkMatchingSequence(cls, room, matchId):
     key = 'matchingId:%s' % (room.gameId)
     sequence = daobase.executeMixCmd('hget', key, matchId)
     if not sequence:
         sequence = daobase.executeMixCmd('hget', key, '%s01' % (matchId))
         if sequence:
             daobase.executeMixCmd('hset', key, matchId, sequence)
         ftlog.info('ErdayiMatch.checkMatchingSequence', 'matchId=',
                    matchId, 'key=', key, 'moveSequence=', sequence)
     else:
         ftlog.info('ErdayiMatch.checkMatchingSequence', 'matchId=',
                    matchId, 'key=', key, 'seq=', sequence)
Ejemplo n.º 37
0
 def save(self, status):
     '''
     保存比赛信息
     '''
     try:
         key = 'mstatus:%s' % (self._room.gameId)
         d = {'seq': status.sequence, 'startTime': status.startTime}
         jstr = json.dumps(d)
         daobase.executeMixCmd('hset', key, status.matchId, jstr)
     except:
         self._logger.error('MatchStatusDaoDizhu.save', 'matchId=',
                            status.matchId, 'instId=', status.instId,
                            'startTime=', status.startTime)
Ejemplo n.º 38
0
    def devidePackage(self):
        '''
        将整体红包按照配置分成随机的份数
        '''
        global _redEnvelopeConfig

        # 划分红包
        prizePool = []
        for item in self.contents:
            for _ in range(1, item['count'] + 1):
                prizePool.append(item['itemId'])

        countTotal = len(prizePool)
        random.shuffle(prizePool)

        index = 0

        while index < countTotal:
            # 随机获得红包的个数
            count = random.randint(self.minCount, self.maxCount)
            if index + count >= countTotal:
                count = countTotal - index;
            if ftlog.is_debug():
                ftlog.debug('count:', count)

            prizes = {}
            for i in range(0, count):
                # 领取红包
                itemId = prizePool[index + i]
                if itemId in prizes:
                    prizes[itemId] += 1
                else:
                    prizes[itemId] = 1

            if ftlog.is_debug():
                ftlog.debug('prizes:', prizes)

            # 写数据库
            daobase.executeMixCmd('LPUSH', self.dbPrefix + self.id + self.PACKAGES, json.dumps(prizes))
            # 记录分包信息
            self.packages_his.append(prizes)

            index += count

        # 设置过期时间
        daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.PACKAGES, self.expiredTime)

        # save result to log    
        if ftlog.is_debug():
            checksJson = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.PACKAGES, 0, -1)
            ftlog.debug('TYRedEnvelope.devidePackage packages: ', checksJson)
Ejemplo n.º 39
0
 def getTableSitdown(self, player):
     self._logger.info('TableManager.getTableSitdown player.userId=',
                       player.userId, 'idleTableCount=',
                       self.idleTableCount, 'allTableCount=',
                       self.allTableCount)
     for countN in xrange(5):
         isLock = daobase.executeMixCmd('HGET', RELAXATION_MATCH_LOCK_KEY,
                                        str(self._room.roomId))
         if isLock:
             FTTasklet.getCurrentFTTasklet().sleepNb(0.2)
             if countN >= 4:
                 return None
         else:
             break
     try:
         # 加锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY,
                               str(self._room.roomId), 1)
         sitTable = None
         for t in xrange(self.waitTableCount):
             table = self.waitTableList[t]
             playerList = table.getPlayerList()
             isMeet = False
             isSameIp = False
             # 休闲赛中,桌子内不能匹配当场比赛已经在一起打过的人,同时相同ip的不会坐在一起
             for onePlayer in playerList:
                 if sessiondata.getClientIp(
                         onePlayer.userId) == sessiondata.getClientIp(
                             player.userId):
                     isSameIp = True
                 if onePlayer.meetPlayersMap.get(player.userId,
                                                 None) == player:
                     isMeet = True
             if (not isMeet) and (not isSameIp) and table.idleSeatCount > 0:
                 table.sitdown(player)
                 sitTable = table
                 if table.idleSeatCount <= 0:
                     self._busyTableList.append(table)
                     del self.waitTableList[t]
                 break
                 # 如果在self.waitTableList 找到位置,那么就取self._idleTables里的
         if not sitTable:
             sitTable = self._borrowOneTable()
             if sitTable:
                 sitTable.sitdown(player)
                 self.waitTableList.append(sitTable)
         return sitTable
     finally:
         # 解锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY,
                               str(self._room.roomId), 0)
Ejemplo n.º 40
0
def get_short_order_id(orderPlatformId):
    if gdata.mode() == gdata.RUN_MODE_ONLINE:
        # 若是线上正式服, 那么再mix库中生成短单号
        shortOrderId = daobase.executeMixCmd('INCR', 'global.orderid.seq.sort')
        shortOrderId = str(100000 + shortOrderId)[-6:]
        daobase.executeMixCmd('HSET', 'sort.orderid.map', shortOrderId,
                              orderPlatformId)
        return shortOrderId
    else:
        # 若是测试服务, 那么调用正式服远程API生成单号
        httpurl = gdata.httpOnlieGateWay() + '/_testorder_get_short_id'
        datas = {'orderPlatformId': orderPlatformId}
        result, _ = webpage.webgetJson(httpurl, datas, None, 10)
        return result['sortOrderPlatformId']
Ejemplo n.º 41
0
def get_short_order_id(orderPlatformId):
    if gdata.mode() == gdata.RUN_MODE_ONLINE:
        # 若是线上正式服, 那么再mix库中生成短单号
        shortOrderId = daobase.executeMixCmd('INCR', 'global.orderid.seq.sort')
        shortOrderId = str(100000 + shortOrderId)[-6:]
        daobase.executeMixCmd('HSET', 'sort.orderid.map', shortOrderId, orderPlatformId)
        return shortOrderId
    else:
        # 若是测试服务, 那么调用正式服远程API生成单号
        httpurl = gdata.httpOnlieGateWay() + '/_testorder_get_short_id'
        datas = {
            'orderPlatformId': orderPlatformId
        }
        result, _ = webpage.webgetJson(httpurl, datas, None, 10)
        return result['sortOrderPlatformId']
Ejemplo n.º 42
0
 def doDataToRedis(self):
     ftlog.debug('doDataToRedis..is..ok')
     DataList = runhttp.getParamStr('listData', '')
     DataList = json.loads(DataList)
     ftlog.debug('DataList =', DataList)
     DataName = runhttp.getParamStr('itemList', '')
     ftlog.debug('DataName =', DataName)
     mo = MsgPack()
     mo.setCmd('insertToredis')
     daobase.executeMixCmd('del', DataName)
     for ecode in DataList:
         ftlog.debug('value =', ecode)
         daobase.executeMixCmd('lpush', DataName, ecode)
     mo.setResult('ok', 1)
     return mo
Ejemplo n.º 43
0
def doGoldLottery(userId, gameId, clientId, number):
    '''
        金盘抽奖
    '''
    if number <= 0 or number > 50:
        ftlog.error('doGoldLottery number best be > 0 or <= 50, the msg is fake')
        return

    if ftlog.is_debug():
        ftlog.debug('hallroulette.doGoldLottery userId:', userId,
                    ' gameId:', gameId,
                    ' clientId:', clientId,
                    ' number:', number
                    )

    # 减少钻石
    result = {}
    count = -(number * 20)
    trueDelta, _finalCount = userchip.incrDiamond(userId, gameId, count, daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                                  'HALL_ROULETTE', 0, 0)
    if not trueDelta:
        # 消费失败 
        return toShop()
    # 将抽奖数进行存储,满足bigRewardNumber,使用大奖概率,否则使用小奖概率
    addBigRewardToPool(userId, gameId, clientId, number)
    # 抽奖
    items = []
    for _num in range(0, number):
        items.append(doRouletteLottery(userId, gameId, clientId))

    result['items'] = items
    # 对抽奖进行修改,连抽的话进行统一的数据库操作
    sendGiftsToUser(userId, gameId, clientId, items)
    # 更新钻石
    datachangenotify.sendDataChangeNotify(gameId, userId, ['udata'])
    # 抽奖成功,进行小兵的下发
    for _ in range(0, number):
        daobase.executeMixCmd('RPUSH', CURKEY, userId)

    # 统计需求
    ftlog.hinfo('doGoldLottery.userId=', userId,
                'gameId=', gameId,
                'clientId=', clientId,
                'number=', number,
                'rouletteType=', 2,
                'rewardItem=', items)
    TGHall.getEventBus().publishEvent(TYEventRouletteDiamond(userId, gameId, number))
    return result
Ejemplo n.º 44
0
 def generateSeries(cls, codeType, nowDate, useGameId):
     if codeType == 'ct_number':
         nowDateStr = nowDate.strftime('%Y%m%d')
         dateSeqKey = daobase.executeMixCmd('hincrby', 'excodenum', nowDateStr, 1)
         if dateSeqKey > 10:
             return 1, '每天最多生成10组兑换码'
         dateSeqKey -= 1
         yearStartDate = nowDate.replace(month=1, day=1)
         _days = '%03d' % ((nowDate - yearStartDate).days)
         _year = '%02d' % (nowDate.year % 100)
         nowSeries = daobase.executeMixCmd('hincrby', 'excodeSeries', useGameId, 1)
         if nowSeries >= 10000:
             raise Exception('游戏' + str(useGameId) + '兑换码生成已满,请联系大厅')
         return dateSeqKey, '%s%04d' % (useGameId, nowSeries)
     else:
         return 10, cls.__generateSeries()
Ejemplo n.º 45
0
def doGetBeforeReward(userId, gameId, clientId):
    '''
        获取往期中奖人的信息
        以及即将开奖的信息
    '''
    result = {}
    result['reward'] = '暂时没有开奖'
    rewardlist = []

    issues = daobase.executeMixCmd('LRANGE', HISKEY, 0, -1)

    if issues:
        for issue in issues:
            issueResult, reward, rewardTime = doGetSoldierIdForUser(userId, gameId, clientId, issue)
            reward['isCheckin'] = len(issueResult[issue])
            obj = {}
            obj['reward'] = reward
            obj['time'] = rewardTime
            rewardlist.append(obj)

    result['reward'] = rewardlist
    if ftlog.is_debug():
        ftlog.debug('hallroulette.doGetBeforeReward result:', result)

    return result
Ejemplo n.º 46
0
    def initTiles(self):
        """初始化手牌,用于摆牌测试"""
        key = 'put_card:' + self.playMode
        ftlog.debug('MTableTileTestLongNet key:', key)

        tile_info = daobase.executeMixCmd('get', key)
        ftlog.debug('MTableTileTestLongNet.initTiles tile_info:', tile_info)
        if not tile_info:
            return False

        tileObj = json.loads(tile_info)

        seat1 = tileObj.get('seat1', [])
        seat2 = tileObj.get('seat2', [])
        seat3 = tileObj.get('seat3', [])
        seat4 = tileObj.get('seat4', [])
        pool = tileObj.get('pool', [])
        # 数据校验
        if len(seat1) > 13:
            return False
        if len(seat2) > 13:
            return False
        if len(seat3) > 13:
            return False
        if len(seat4) > 13:
            return False

        self.setHandTiles([seat1, seat2, seat3, seat4])
        self.setTiles(pool)

        return True
Ejemplo n.º 47
0
Archivo: gm.py Proyecto: zhaozw/hall37
    def _do_http_gm_table_detail(self, gameId, httpRequest, httpArgs, httpResult):
        '''获取某牌桌的详情'''

        roomId = int(httpArgs['roomId'])
        tableId = int(httpArgs['tableId'])
        username = httpArgs.get('username')
        password = httpArgs.get('password')
        if username and password:
            token = daobase.executeMixCmd('HGET', '8:gm:token', username) == password
        else:
            token = False

        ftlog.info('GM._do_http_gm_table_detail << |',
                   'roomId, tableId, username, token', roomId, tableId, username, token)

        msg = utils.updateMsg(cmd='table', params={
            'action': 'gm',
            'sa': 'tableDetail',
            'gameId': gameId,
            'roomId': roomId,
            'tableId': tableId,
            'token': token,
        })
        ret = strutil.loads(router.queryTableServer(msg, roomId))
        ftlog.debug('_do_http_gm_table_detail| roomId, tableId, ret:', roomId, tableId, ret)
        tableDetail = strutil.loads(router.queryTableServer(msg, roomId))['result']['tableDetail']
        httpResult['tableDetail'] = tableDetail
Ejemplo n.º 48
0
 def initTiles(self):
     """初始化手牌,用于摆牌测试"""
     key = 'put_card:' + self.playMode
     ftlog.debug('MTableTileTestLongNet key:', key)
     
     tile_info = daobase.executeMixCmd('get', key)
     ftlog.debug('MTableTileTestLongNet.initTiles tile_info:', tile_info)
     if not tile_info:
         ftlog.debug('MTableTileTestLongNet.initTiles failed...')
         return False
     
     tileObj = json.loads(tile_info)
     handTiles = []
     ftlog.debug('MTableTileTestLongNet.playerCount:', self.playerCount)
     for index in range(1, self.playerCount+1):
         indexTiles = tileObj.get('seat'+str(index), [])
         ftlog.debug('MTableTileTestLongNet.initTiles seat'+str(index)+':', indexTiles, ' length:', len(indexTiles))
         #数据校验
         if len(indexTiles) > 16:
             return False
         handTiles.append(indexTiles)
     pool = tileObj.get('pool', [])
     ftlog.debug('MTableTileTestLongNet.initTiles pool:', pool, ' length:', len(pool))
     
     self.setHandTiles(handTiles)
     self.setTiles(pool)
     
     return True
Ejemplo n.º 49
0
    def __commonCheck(self, rdskey, clientId):
        config_ = daobase.executeMixCmd('HGET', 'excodeinfo:' + rdskey, 'common')
        ftlog.debug('this exchange config_ = ', config_)
        try:
            ftlog.debug('ExchangeCode->__commonCheck load common', config_)
            config_ = json.loads(config_)
        except:
            return 1, u'无效兑换码', 0

        unique = 0
        if 'unique' in config_:
            unique = int(config_['unique'])

        date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if 'begin_time' in config_:
            begin_time = config_['begin_time']
            if begin_time and (date_now < begin_time):
                return 1, u'活动还没开始', unique
        if 'end_time' in config_:
            end_time = config_['end_time']
            if end_time and (date_now > end_time):
                return 2, u'活动已经结束', unique
        if 'client_ids' in config_:
            client_ids = config_['client_ids']
            if 'ALL' not in client_ids:  # client_ids = ['ALL'],说明是全部ID都支持的
                if clientId not in client_ids:
                    return 3, u'不在活动条件内', unique
        return 0, '', unique
Ejemplo n.º 50
0
    def queryEnvelope(self):
        info = {}
        info['envelopeId'] = self.id
        info['contents'] = self.contents
        info['receiver'] = []
        receivers = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.RECEIVER, 0, -1)
        if receivers:
            for receiverJson in receivers:
                receiver = json.loads(receiverJson)
                # 补充昵称/头像/金币信息
                userId = receiver['userId']
                chip, name, purl = pkuserdata.getAttrs(userId, ['chip', 'name', 'purl'])
                if chip and name and purl:
                    if ftlog.is_debug():
                        ftlog.debug('TYRedEnvelope.queryEnvelope receiver userId:', userId, ' chip:', chip, ' name:',
                                    name, ' purl:', purl)
                    receiver['chip'] = chip
                    receiver['name'] = name
                    receiver['purl'] = purl

                info['receiver'].append(receiver)

        if ftlog.is_debug():
            ftlog.debug('TYRedEnvelope.queryEnvelope info:', info)

        return info
Ejemplo n.º 51
0
 def __init__(self, room, tableSeatCount):
     self._room = room
     # 重启的时候将锁清零初始化
     daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY, str(self._room.roomId), 0)
     self._tableSeatCount = tableSeatCount
     # 打牌的桌子
     self._busyTableList = []
     # 处于等待的桌子,已经有人但没有坐满
     self._waitTableList = []
     # 空闲的桌子        
     self._idleTables = []
     # 所有的桌子
     self._allTableMap = {}
     self._roomIds = set()
     self._logger = Logger()
     self._logger.add('roomId', self._room.roomId)
Ejemplo n.º 52
0
def doRouletteSilverLottery(userId, gameId, clientId):
    '''
    金盘抽奖
        每次一计算概率,防止连续开出大奖
    '''
    tempRouleteType = 'silver_items'
    tempResult = getWeightConfTemplate(userId, gameId, clientId)
    item = doWeightListForItem(userId, gameId, clientId, tempResult.get(tempRouleteType, []))
    if not item:
        raise Exception('配置信息出错,没有取到奖品配置')

    # 修改大奖个数
    if isBigRewardItem(item):
        daobase.executeMixCmd('hincrby', 'allSoldier', 'bigRewardNumber', -1)

    return item
Ejemplo n.º 53
0
 def save2DB(self):
     '''
     存储到数据库
     '''
     # 保存基本信息
     config = {}
     config['minCount'] = self.minCount
     config['maxCount'] = self.maxCount
     # 设置配置
     daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.CONFIG, json.dumps(config))
     # 设置红包内容
     daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.CONTENTS, json.dumps(self.contents))
     # 设置红包历史
     daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.PACKAGES_HIS, json.dumps(self.packages_his))
     # 设置状态
     daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.STATE, self.state)
     daobase.executeMixCmd('expire', self.dbPrefix + self.id, self.expiredTime)
Ejemplo n.º 54
0
def getFriendTableInfo(tableNo):
    """获取自建桌的参数"""
    params = {}
    pluginId = daobase.executeMixCmd('HGET', FRIEND_TABLE_MAIN_KEY + tableNo, FRIEND_TABLE_PLUGIN)
    if pluginId:
        params['pluginId'] = pluginId

    roomId = daobase.executeMixCmd('HGET', FRIEND_TABLE_MAIN_KEY + tableNo, FRIEND_TABLE_ROOMID)
    if roomId:
        params['roomId'] = roomId

    tableId = daobase.executeMixCmd('HGET', FRIEND_TABLE_MAIN_KEY + tableNo, FRIEND_TABLE_TABLEID)
    if tableId:
        params['tableId'] = tableId

    ftlog.debug('hall_friend_table.getFriendTableInfo params:', params)
    return params
Ejemplo n.º 55
0
 def getTableSitdown(self, player):
     self._logger.info('TableManager.getTableSitdown player.userId=', player.userId,
                       'idleTableCount=', self.idleTableCount,
                       'allTableCount=', self.allTableCount)
     for countN in xrange(5):
         isLock = daobase.executeMixCmd('HGET', RELAXATION_MATCH_LOCK_KEY, str(self._room.roomId))
         if isLock:
             FTTasklet.getCurrentFTTasklet().sleepNb(0.2)
             if countN >= 4:
                 return None
         else:
             break
     try:
         # 加锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY, str(self._room.roomId), 1)
         sitTable = None
         for t in xrange(self.waitTableCount):
             table = self.waitTableList[t]
             playerList = table.getPlayerList()
             isMeet = False
             isSameIp = False
             # 休闲赛中,桌子内不能匹配当场比赛已经在一起打过的人,同时相同ip的不会坐在一起
             for onePlayer in playerList:
                 if sessiondata.getClientIp(onePlayer.userId) == sessiondata.getClientIp(player.userId):
                     isSameIp = True
                 if onePlayer.meetPlayersMap.get(player.userId, None) == player:
                     isMeet = True
             if (not isMeet) and (not isSameIp) and table.idleSeatCount > 0:
                 table.sitdown(player)
                 sitTable = table
                 if table.idleSeatCount <= 0:
                     self._busyTableList.append(table)
                     del self.waitTableList[t]
                 break
                 # 如果在self.waitTableList 找到位置,那么就取self._idleTables里的
         if not sitTable:
             sitTable = self._borrowOneTable()
             if sitTable:
                 sitTable.sitdown(player)
                 self.waitTableList.append(sitTable)
         return sitTable
     finally:
         # 解锁
         daobase.executeMixCmd('HSET', RELAXATION_MATCH_LOCK_KEY, str(self._room.roomId), 0)
Ejemplo n.º 56
0
def getSoldierNumber():
    '''
    获取待开奖的小兵队列
    '''
    soldierNumber = daobase.executeMixCmd('LLEN', CURKEY)
    if soldierNumber:
        if ftlog.is_debug():
            ftlog.debug('hallroulette.getSoldierNumber number:', soldierNumber)
        return int(soldierNumber)
    return 0
Ejemplo n.º 57
0
def doGetSoldierInfo(userId, gameId, clientId):
    '''
        将小兵的配置信息进行解析,并且将需要下发的信息进行下发
        获取当前的时间,判断是否在时间区间内部,只返回当前的时间区间
    '''
    tempTemplate = getSnatchConf()
    soldierInfo = {}
    soldierInfo['desc'] = tempTemplate.get('desc', '')
    soldierInfo['picUrl'] = tempTemplate.get('picUrl', '')
    soldierInfo['endTime'] = tempTemplate.get('endTime', '')
    soldierInfo['startTime'] = tempTemplate.get('startTime', '')
    soldierInfo['needNumber'] = tempTemplate.get('needNumber', 0)
    nowPeople = []

    soldierInfo['issue'] = time.strftime("%Y%m%d", time.localtime()) + getIssue(False)

    tempNumber = getSoldierNumber()
    needNumber = tempTemplate.get('needNumber', 0)
    if tempNumber - needNumber > 0:
        tempNumber = needNumber

    soldierInfo['nowNumber'] = tempNumber

    mySoldier = []
    allSoldier = daobase.executeMixCmd('LRANGE', CURKEY, 0, needNumber - 1)
    if allSoldier:
        sLen = len(allSoldier)
        if ftlog.is_debug():
            ftlog.debug('hallroulette.doGetSoldierInfo allSoldier len:', sLen)
        for index in range(0, sLen):
            if ftlog.is_debug():
                ftlog.debug('hallroulette.doGetSoldierInfo now soldier index:', index
                            , ' soldier id:', allSoldier[index]
                            , ' userId:', userId)

            if allSoldier[index] == userId:
                sId = getSoldierIdByIndex(index)
                mySoldier.append(sId)

            if allSoldier[index] not in nowPeople:
                nowPeople.append(allSoldier[index])

    if ftlog.is_debug():
        ftlog.debug('hallroulette.doGetSoldierInfo mySoldiers:', mySoldier
                    , ' nowPeople:', nowPeople)

    soldierInfo['mySoldiers'] = mySoldier
    soldierInfo['nowPeople'] = len(nowPeople)

    result = {}
    result['soldierInfo'] = soldierInfo
    if ftlog.is_debug():
        ftlog.debug('hallroulette.doGetSoldierInfo result:', result)

    return result
Ejemplo n.º 58
0
def bigRewardOrReward(userId, gameId, clientId):
    '''
        判断用户金盘抽奖的概率池
    '''
    nowBigRewardNumber = daobase.executeMixCmd('HGET', 'allSoldier', 'bigRewardNumber') or 0
    if int(nowBigRewardNumber) > 0:
        if ftlog.is_debug():
            ftlog.debug('hallroulette.nowBigRewardNumber: ', nowBigRewardNumber, ' user goldBigRewardConfig...')
        return 'goldBigReward_items'

    return 'gold_items'