コード例 #1
0
ファイル: hallneituiguang.py プロジェクト: zhaozw/hall37
 def doPromoteCodeCheck(cls, gameId, userId, clientId, action, promoteCode):
     '''
     验证兑换码ID,有效则获取用户手机绑定信息,若绑定手机,则发送奖励,并更新用户状态。若未绑定手机,则更新用户状态,返回未绑定手机code
     '''
     conf = hallconf.getNeiTuiGuangConf(clientId)
     if not conf:
         ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=',
                     clientId, 'action=', action)
         return
     mo = MsgPack()
     userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
     if userstate == 2:
         NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '已经领奖成功', mo)
     else:
         promoteCode = cls.intPromoteCode(promoteCode)
         if promoteCode == -1 or userId == promoteCode:
             NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo)
         else:
             userdata.checkUserData(promoteCode)
             createTime = userdata.getAttr(promoteCode, 'createTime')
             if createTime == None:
                 NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo)
             else:
                 olduser = cls.isOldUser(promoteCode, gameId, createTime, conf)
                 if not olduser:
                     NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo)
                 else:
                     gamedata.setGameAttr(userId, gameId, cls.attrname_promotecode, promoteCode)  # 记录兑换码
                     gamedata.setGameAttr(userId, gameId, cls.attrname_state, 1)  # 已输入兑换码
                     bindmobile = userdata.getAttr(userId, 'bindMobile')
                     if cls.bindOk(bindmobile):
                         NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '验证成功', mo)
                     else:
                         NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, cls.getprize(gameId, 2, conf), mo)
         return mo
コード例 #2
0
    def _processEventImpl(self, task, event):
        if isinstance(event, (UserBindWeixinEvent, EventUserLogin)):
            wxopenid = userdata.getAttr(event.userId, 'wxopenid')
            if wxopenid:
                return task.setProgress(task.progress + 1, event.timestamp)
            snsLoginType = userdata.getAttr(event.userId, 'snsLoginType')
            if snsLoginType and snsLoginType == 'wx':
                return task.setProgress(task.progress + 1, event.timestamp)

        return False, 0
コード例 #3
0
 def testOrderDelivery(self):
     userdata.setAttr(self.userId, 'chip', 100)
     TGHall.getEventBus().publishEvent(ChargeNotifyEvent(self.userId, self.gameId, 10, 100, 'T50K', self.clientId))
     self.assertEqual(userdata.getAttr(self.userId, 'chip'), 100)
     
     userAssets = hallitem.itemSystem.loadUserAssets(self.userId)
     userAssets.addAsset(self.gameId, 'item:4347', 1, int(time.time()), 'TEST', 0)
     
     TGHall.getEventBus().publishEvent(ChargeNotifyEvent(self.userId, self.gameId, 10, 100, 'T50K', self.clientId))
     self.assertEqual(userdata.getAttr(self.userId, 'chip'), 100)
     
     TGHall.getEventBus().publishEvent(ChargeNotifyEvent(self.userId, self.gameId, 30, 100, 'T50K', self.clientId))
     self.assertEqual(userdata.getAttr(self.userId, 'chip'), 200000+100)
     print userdata.getAttr(self.userId, 'chip')
コード例 #4
0
ファイル: hallneituiguang.py プロジェクト: zhaozw/hall37
    def doOldUserGetPrize(cls, gameId, userId, friendId, clientId, action):
        '''
        老用户领奖接口
        '''
        conf = hallconf.getNeiTuiGuangConf(clientId)
        if not conf:
            ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=',
                        clientId, 'action=', action)
            return

        mo = MsgPack()
        mpush = None
        userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
        bindmobile = userdata.getAttr(userId, 'bindMobile')
        if userstate == 2:
            if cls.bindOk(bindmobile):
                prizeGet = cls.sendOldUserPrize(userId, friendId, gameId, conf)
                NeiTuiGuangProtocolBuilder.buildOldUserPrize(0, action, cls.getprize(gameId, 0, prizeGet), friendId, mo)
                ##### 推一条用户奖励信息
                mpush = cls.doQueryPrize(gameId, userId, clientId, action)
            else:
                NeiTuiGuangProtocolBuilder.buildBindPrize(1, action, cls.getprize(gameId, 2), friendId, mo)
        else:
            NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, 'user state error: not support', mo)

        return mo, mpush
コード例 #5
0
    def doGetTaskReward(self, gameId, userId, taskId):
        '''
        获取活动奖励
        '''
        try:
            timestamp = pktimestamp.getCurrentTimestamp()
            taskModel = neituiguangtask.newUserTaskSystem.loadTaskModel(
                userId, timestamp)
            task = taskModel.userTaskUnit.findTask(taskId)
            if not task:
                raise TYBizException(-1, '未知的任务:%s' % (taskId))
            expiresTime = self.calcTaskExpires(userId)
            if timestamp >= expiresTime:
                raise TYBizException(-1, '任务已经过期')
            if not userdata.getAttr(userId, 'bindMobile'):
                conf = neituiguang.getConf()
                TodoTaskHelper.sendTodoTask(
                    gameId, userId, TodoTaskBindPhone(conf.pleaseBindPhone,
                                                      ''))
                return
            assetList = neituiguangtask.newUserTaskSystem.getTaskReward(
                task, timestamp, 'PROMOTE_TASK', taskId)
            router.sendToUser(self.buildTaskInfoResponse(userId), userId)

            rewardStr = TYAssetUtils.buildContentsString(assetList)
            mo = MsgPack()
            mo.setCmd('promote_info')
            mo.setResult('action', 'get_task_reward')
            mo.setResult('code', 0)
            mo.setResult('info', '恭喜您获得了%s' % rewardStr)
            router.sendToUser(mo, userId)
        except TYBizException, e:
            router.sendToUser(
                self.makeErrorResponse('get_task_reward', e.errorCode,
                                       e.message), userId)
コード例 #6
0
def _conform(self, gameId, userAssets, item, timestamp, params):
    wxOpenId = userdata.getAttr(userAssets.userId, 'wxOpenId')
    ftlog.info('TYItemActionConditionBindWeixin._conform', 'gameId=', gameId,
               'userId=', userAssets.userId, 'itemId=', item.itemId,
               'itemKindId=', item.kindId, 'wxOpenId=', wxOpenId, 'ret=',
               False if not wxOpenId else True)
    return False if not wxOpenId else True
コード例 #7
0
 def _getSurpassTarget(self):
     """
     获取要超越的玩家数据
     """
     timestamp = pktimestamp.getCurrentTimestamp()
     rankClass = RankingBase(self.userId,
                             RankType.TodayGrandPrix,
                             RankDefineIndex.GrandPrix,
                             clientId=None,
                             httpRequest=False)
     if rankClass:
         rankingList = rankClass.getTopNRankUsers(timestamp)
         surpassTarget = config.getGrandPrixConf(
             "surpassTarget")  # [100、80、... 3、2、1]
         masterSurpassTargets = []
         for rank in surpassTarget:
             idx = rank - 1
             if 0 <= idx < len(rankingList.rankingUserList):
                 player = rankingList.rankingUserList[idx]
                 name = util.getNickname(player.userId)
                 avatar = userdata.getAttr(player.userId, "purl")
                 masterSurpassTargets.append({
                     "userId": player.userId,
                     "name": name,
                     "score": player.score,
                     "rank": player.rank + 1,
                     "avatar": avatar
                 })
         self._rankListCache = masterSurpassTargets
コード例 #8
0
ファイル: hotfix_zhuanyun.py プロジェクト: zhaozw/hall37
def makeTodoTaskZhuanyun_(gameId, userId, clientId, benefitsSend, userBenefits,
                          roomId):
    from hall.entity import hallproductselector
    if ftlog.is_debug():
        ftlog.debug('hallpopwnd.makeTodoTaskZhuanyun gameId=', gameId,
                    'userId=', userId, 'clientId=', clientId, 'benefitsSend=',
                    benefitsSend, 'userBenefits=', userBenefits.__dict__,
                    'roomId=', roomId)
    clientOs, _clientVer, _ = strutil.parseClientId(clientId)
    clientOs = clientOs.lower()

    if clientOs != 'winpc':
        return TodoTaskHelper.makeZhuanyunTodoTaskNew(gameId, userId, clientId,
                                                      benefitsSend,
                                                      userBenefits, roomId)

    product, _ = hallproductselector.selectLessbuyProduct(
        gameId, userId, clientId, roomId)
    if not product:
        return None

    user_diamond = pkuserdata.getAttr(userId, 'diamond')
    if user_diamond >= int(product.priceDiamond):
        chip = product.getMinFixedAssetCount(hallitem.ASSET_CHIP_KIND_ID)
        show_str = u'运气不好,来个转运礼包!%s元得%s万金币。' % (product.price, chip)
        buy_type = 'consume'
        btn_txt = u'兑换'
    else:
        show_str = u'运气不好~,买点金币战个痛快吧!'
        buy_type = 'charge'
        btn_txt = u'去充值'
    orderShow = TodoTaskOrderShow.makeByProduct(show_str, '', product,
                                                buy_type)
    orderShow.setParam('sub_action_btn_text', btn_txt)
    return orderShow
コード例 #9
0
ファイル: dizhufishing.py プロジェクト: luningcowboy/tuyoo
    def getFishingInfo(cls, userId):
        # 获取鱼饵
        baits = cls.getUserBaits(userId)

        fishList = set()
        # 获取鱼饵普通鱼信息
        for bait in baits:
            for fish in bait.fishList:
                if fish.id == 0:
                    continue
                fishList.add(fish)

        fishDictList = [fish.toDict() for fish in fishList]

        # 珍珠鱼信息, 获取进度
        couponFish = cls.getCouponFishList()[0]
        couponFishDict = couponFish.toDict()
        couponFishDict['progress'] = loadUserFishingCount(
            userId, couponFish.id)
        fishDictList.append(couponFishDict)
        baitList = [bait.toDict() for bait in baits]
        return {
            'baits': baitList,
            'fish': fishDictList,
            'finalChip': userchip.getChip(userId),
            'tip': _fishingConf.tip,
            'finalCouponCount': userdata.getAttr(userId, 'coupon')
        }
コード例 #10
0
ファイル: mtt_room.py プロジェクト: zhaozw/hall37
    def __onMatchEnd(self):
        mconf = self.matchPlugin.match_room_confs[self.bigRoomId]

        rankinglist = daobase.executeRankCmd("LRANGE", self.matchPlugin.rankingKey(self.bigRoomId), 0, -1)
        getName = lambda userId: userdata.getAttr(userId, 'name')
        rankingListWithName = [(i + 1, userId, getName(userId)) for i, userId in enumerate(reversed(rankinglist))]
        bireport.matchFinish(self.gameId, self.roomId,
                             mconf['start_time'].strftime('%Y-%m-%d_%H:%M:%S_') + str(self.roomId),
                             mconf['name'].replace('\n', ' '),
                             matchTypeId=mconf['match_id'],
                             endTimestamp=time.time(),
                             rewardChip=self.matchCounter['rewardChip'],
                             rewardCoupon=self.matchCounter['rewardCoupon'],
                             rankingList=rankingListWithName,
                             usersLeaveMatchCount=self.matchCounter['usersLeaveMatchCount'],
                             rebuyChip=self.matchCounter['rebuyChip'],
                             addonChip=self.matchCounter['addonChip'],
                             )

        # for check MTT gameEnd
        TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_MATCH_END', params={'room': self}), self.gameId)

        if ftlog.is_debug():
            ftlog.debug("len(self.scheduler.activeTableIds):", len(self.scheduler.activeTableIds), caller=self)

        # 回收决赛桌和异常牌桌
        remainActiveTables = strutil.cloneData(self.scheduler.activeTableIds)
        for activeTableId in remainActiveTables:
            self.scheduler._recycleTable(activeTableId)

        if mconf.get('day1EndConf'):
            self.matchPlugin.saveDay2Players(self)

        self.state = self.MTT_STATE_READY
コード例 #11
0
    def doGetTaskReward(self, gameId, userId, taskId):
        '''
        获取活动奖励
        '''
        try:
            timestamp = pktimestamp.getCurrentTimestamp()
            taskModel = neituiguangtask.newUserTaskSystem.loadTaskModel(userId, timestamp)
            task = taskModel.userTaskUnit.findTask(taskId)
            if not task:
                raise TYBizException(-1, '未知的任务:%s' % (taskId))
            expiresTime = self.calcTaskExpires(userId)
            if timestamp >= expiresTime:
                raise TYBizException(-1, '任务已经过期')
            if not userdata.getAttr(userId, 'bindMobile'):
                conf = neituiguang.getConf()
                TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskBindPhone(conf.pleaseBindPhone, ''))
                return
            assetList = neituiguangtask.newUserTaskSystem.getTaskReward(task, timestamp, 'PROMOTE_TASK', taskId)
            router.sendToUser(self.buildTaskInfoResponse(userId), userId)

            rewardStr = TYAssetUtils.buildContentsString(assetList)
            mo = MsgPack()
            mo.setCmd('promote_info')
            mo.setResult('action', 'get_task_reward')
            mo.setResult('code', 0)
            mo.setResult('info', '恭喜您获得了%s' % rewardStr)
            router.sendToUser(mo, userId)
        except TYBizException, e:
            router.sendToUser(self.makeErrorResponse('get_task_reward', e.errorCode, e.message), userId)
コード例 #12
0
ファイル: hotfix_zhuanyun.py プロジェクト: zhaozw/hall37
def makeTodoTaskZhuanyun_(gameId, userId, clientId, benefitsSend, userBenefits, roomId):
    from hall.entity import hallproductselector
    if ftlog.is_debug():
        ftlog.debug('hallpopwnd.makeTodoTaskZhuanyun gameId=', gameId,
                    'userId=', userId,
                    'clientId=', clientId,
                    'benefitsSend=', benefitsSend,
                    'userBenefits=', userBenefits.__dict__,
                    'roomId=', roomId)
    clientOs, _clientVer, _ = strutil.parseClientId(clientId)
    clientOs = clientOs.lower()

    if clientOs != 'winpc':
        return TodoTaskHelper.makeZhuanyunTodoTaskNew(gameId, userId, clientId,
                                                      benefitsSend, userBenefits, roomId)

    product, _ = hallproductselector.selectLessbuyProduct(gameId, userId, clientId, roomId)
    if not product:
        return None

    user_diamond = pkuserdata.getAttr(userId, 'diamond')
    if user_diamond >= int(product.priceDiamond):
        chip = product.getMinFixedAssetCount(hallitem.ASSET_CHIP_KIND_ID)
        show_str = u'运气不好,来个转运礼包!%s元得%s万金币。' % (product.price, chip)
        buy_type = 'consume'
        btn_txt = u'兑换'
    else:
        show_str = u'运气不好~,买点金币战个痛快吧!'
        buy_type = 'charge'
        btn_txt = u'去充值'
    orderShow = TodoTaskOrderShow.makeByProduct(show_str, '', product, buy_type)
    orderShow.setParam('sub_action_btn_text', btn_txt)
    return orderShow
コード例 #13
0
    def _doUpdate(cls, userId, clientId, timestamp):
        mo = MsgPack()
        mo.setCmd('hall_rp_task')
        mo.setResult('action', 'update')
        mo.setResult('userId', userId)
        status = hall_red_packet_task.loadUserStatus(userId)
        curTime = timestamp
        expiresTime = curTime
        createTimeStr = None
        try:
            createTimeStr = userdata.getAttr(userId, 'createTime')
            createDT = datetime.strptime(createTimeStr, '%Y-%m-%d %H:%M:%S.%f')
            createTime = pktimestamp.datetime2Timestamp(createDT)
            expiresTime = pktimestamp.getDayStartTimestamp(
                createTime) + 86400 * 8
        except:
            ftlog.error('RedPacketTaskTcpHandler._doUpdate BadCreateTime',
                        'userId=', userId, 'createTime=', createTimeStr)

        mo.setResult('curTime', curTime)
        mo.setResult('expiresTime', expiresTime)
        if status.finished or not status.task:
            acts = hall_red_packet_task.getActs()
            mo.setResult('acts', cls.encodeActs(userId, clientId, acts))
        else:
            mo.setResult('task', cls.encodeTask(userId, clientId, status))

        mo.setResult('helpUrl',
                     hall_red_packet_task.getHelpUrl(userId, clientId))
        mo.setResult('tips',
                     hall_red_packet_task.getTaskTips(userId, clientId))
        mo.setResult('boardTip',
                     hall_red_packet_task.getBoardTip(userId, clientId))
        return mo
コード例 #14
0
def needSendStartChip(userId, gameId):
    '''是否发放启动资金
    '''
    global newuser_startchip

    return (1 == userdata.getAttr(userId,
                                  'sendMeGift')) and (newuser_startchip > 0)
コード例 #15
0
    def doOldUserGetPrize(cls, gameId, userId, friendId, clientId, action):
        '''
        老用户领奖接口
        '''
        conf = hallconf.getNeiTuiGuangConf(clientId)
        if not conf:
            ftlog.error('neituiguang doGetUserState conf not found gameId=',
                        gameId, 'userId=', userId, 'clientId=', clientId,
                        'action=', action)
            return

        mo = MsgPack()
        mpush = None
        userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
        bindmobile = userdata.getAttr(userId, 'bindMobile')
        if userstate == 2:
            if cls.bindOk(bindmobile):
                prizeGet = cls.sendOldUserPrize(userId, friendId, gameId, conf)
                NeiTuiGuangProtocolBuilder.buildOldUserPrize(
                    0, action, cls.getprize(gameId, 0, prizeGet), friendId, mo)
                ##### 推一条用户奖励信息
                mpush = cls.doQueryPrize(gameId, userId, clientId, action)
            else:
                NeiTuiGuangProtocolBuilder.buildBindPrize(
                    1, action, cls.getprize(gameId, 2), friendId, mo)
        else:
            NeiTuiGuangProtocolBuilder.buildBasicInfo(
                2, action, 'user state error: not support', mo)

        return mo, mpush
コード例 #16
0
    def doGetPrize(cls, gameId, userId, clientId, action):
        '''
        新用户领奖接口
        '''
        conf = hallconf.getNeiTuiGuangConf(clientId)
        if not conf:
            ftlog.error('neituiguang doGetUserState conf not found gameId=',
                        gameId, 'userId=', userId, 'clientId=', clientId,
                        'action=', action)
            return
        mo = MsgPack()
        bindmobile = userdata.getAttr(userId, 'bindMobile')
        userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
        if cls.bindOk(bindmobile):
            prizeGet = cls.sendBothUserPrize(gameId, userId, userstate, conf)

            if prizeGet == -1:  # 用户状态错误
                NeiTuiGuangProtocolBuilder.buildBasicInfo(
                    2, action, "用户状态错误", mo)
            else:  # 发送奖励成功
                NeiTuiGuangProtocolBuilder.buildBasicInfo(
                    0, action, cls.getprize(gameId, 0, conf, prizeGet), mo)
        else:  # 未绑定手机
            NeiTuiGuangProtocolBuilder.buildBasicInfo(
                1, action, cls.getprize(gameId, 2, conf), mo)

        return mo
コード例 #17
0
 def calcTaskExpires(cls, userId):
     '''
     结算新手任务是否过期
     '''
     createTimeStr = userdata.getAttr(userId, 'createTime')
     createTime = pktimestamp.timestrToTimestamp(createTimeStr, '%Y-%m-%d %H:%M:%S.%f')
     return pktimestamp.getDayStartTimestamp(createTime) + neituiguang.NEW_USER_DAYS * 86400
コード例 #18
0
ファイル: dizhuusercond.py プロジェクト: luningcowboy/tuyoo
    def check(self, gameId, userId, clientId, timestamp, **kwargs):
        # 通过 userId 获取用户位置信息
        userProvince = userdata.getAttr(userId, 'province')
        if not userProvince:
            return False

        try:
            userProvince = userProvince.encode('utf8') if isinstance(
                userProvince, unicode) else userProvince
        except:
            return False

        if ftlog.is_debug():
            isNotInProvince = True
            for province in self.provinces:
                if province in userProvince:
                    isNotInProvince = False
            ftlog.debug('UserConditionNotInProvinces userId=', userId,
                        'userProvince=', userProvince, 'provinces=',
                        self.provinces, 'isNotInProvince=', isNotInProvince)

        for province in self.provinces:
            if province in userProvince:
                return False
        return True
コード例 #19
0
 def encodeInvitation(cls, invitation):
     name = userdata.getAttr(invitation.userId, 'name')
     state = 0
     if invitation.state == Invitation.STATE_ACCEPT:
         state = 1
     elif invitation.state == Invitation.STATE_REWARD:
         state = 2
     return {'userId': invitation.userId, 'name': name, 'state': state}
コード例 #20
0
def isUser2018(userId):
    try:
        createTime = userdata.getAttr(userId, 'createTime')
        if createTime and str(createTime).find('2018') == 0 :
            return 1
    except:
        ftlog.error()
    return 0
コード例 #21
0
    def doGetUserState(cls, gameId, userId, clientId, action):
        '''
        获取用户信息,不存在则,验证用户状态,写入用户活动状态表,并返回用户状态
        '''
        conf = hallconf.getNeiTuiGuangConf(clientId)
        mo = MsgPack()
        if not conf:
            ftlog.error('neituiguang doGetUserState conf not found gameId=',
                        gameId, 'userId=', userId, 'clientId=', clientId,
                        'action=', action)
            return mo
        state = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
        createTime = userdata.getAttr(userId, 'createTime')
        if state == None:
            state = cls.initUserState(userId, gameId, createTime, conf)
            userdata.setAttr(userId, cls.attrname_state, state)
            inviteetip = cls.inviteeTip(userId, gameId, createTime, conf)
        else:
            if cls.isOldUser(userId, gameId, createTime, conf):
                state = 2
                userdata.setAttr(userId, cls.attrname_state, state)  # 老用户状态

        if state == 0:
            NeiTuiGuangProtocolBuilder.buildNewUserState(
                gameId, userId, action, state, inviteetip, mo)
        elif state == 1:
            bindmobile = userdata.getAttr(userId, 'bindMobile')
            bindok = cls.bindOk(bindmobile)
            NeiTuiGuangProtocolBuilder.buildBindUserState(
                gameId, userId, action, state, bindok, mo)
        elif state == 2:
            bindmobile = userdata.getAttr(userId, 'bindMobile')
            bindok = cls.bindOk(bindmobile)
            shareId = conf.get('shareId', -1)
            prizeinfo = conf.get('prize_info', [])
            weixintip = cls.getWeiXinTip(userId, conf)
            url = cls.getDownUrl(userId, conf)
            smstip = cls.getSMSTip(gameId, userId, conf)
            rules = conf.get('rules', [])
            NeiTuiGuangProtocolBuilder.buildOldUserState(
                gameId, userId, action, state, bindok, shareId, prizeinfo,
                weixintip, url, smstip, rules, mo)
        else:
            pass

        return mo
コード例 #22
0
 def encodeInvitation(cls, invitation):
     name = userdata.getAttr(invitation.userId, 'name')
     state = 0
     if invitation.state == Invitation.STATE_ACCEPT:
         state = 1
     elif invitation.state == Invitation.STATE_REWARD:
         state = 2
     return {'userId': invitation.userId, 'name': name, 'state': state}
コード例 #23
0
 def doPromoteCodeCheck(cls, gameId, userId, clientId, action, promoteCode):
     '''
     验证兑换码ID,有效则获取用户手机绑定信息,若绑定手机,则发送奖励,并更新用户状态。若未绑定手机,则更新用户状态,返回未绑定手机code
     '''
     conf = hallconf.getNeiTuiGuangConf(clientId)
     if not conf:
         ftlog.error('neituiguang doGetUserState conf not found gameId=',
                     gameId, 'userId=', userId, 'clientId=', clientId,
                     'action=', action)
         return
     mo = MsgPack()
     userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
     if userstate == 2:
         NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '已经领奖成功', mo)
     else:
         promoteCode = cls.intPromoteCode(promoteCode)
         if promoteCode == -1 or userId == promoteCode:
             NeiTuiGuangProtocolBuilder.buildBasicInfo(
                 1, action, cls.getprize(gameId, 1, conf), mo)
         else:
             userdata.checkUserData(promoteCode)
             createTime = userdata.getAttr(promoteCode, 'createTime')
             if createTime == None:
                 NeiTuiGuangProtocolBuilder.buildBasicInfo(
                     1, action, cls.getprize(gameId, 1, conf), mo)
             else:
                 olduser = cls.isOldUser(promoteCode, gameId, createTime,
                                         conf)
                 if not olduser:
                     NeiTuiGuangProtocolBuilder.buildBasicInfo(
                         1, action, cls.getprize(gameId, 1, conf), mo)
                 else:
                     gamedata.setGameAttr(userId, gameId,
                                          cls.attrname_promotecode,
                                          promoteCode)  # 记录兑换码
                     gamedata.setGameAttr(userId, gameId,
                                          cls.attrname_state, 1)  # 已输入兑换码
                     bindmobile = userdata.getAttr(userId, 'bindMobile')
                     if cls.bindOk(bindmobile):
                         NeiTuiGuangProtocolBuilder.buildBasicInfo(
                             0, action, '验证成功', mo)
                     else:
                         NeiTuiGuangProtocolBuilder.buildBasicInfo(
                             2, action, cls.getprize(gameId, 2, conf), mo)
         return mo
コード例 #24
0
 def calcTaskExpires(cls, userId):
     '''
     结算新手任务是否过期
     '''
     createTimeStr = userdata.getAttr(userId, 'createTime')
     createTime = pktimestamp.timestrToTimestamp(createTimeStr,
                                                 '%Y-%m-%d %H:%M:%S.%f')
     return pktimestamp.getDayStartTimestamp(
         createTime) + neituiguang.NEW_USER_DAYS * 86400
コード例 #25
0
    def processEnterGame(cls, evt):
        # # 检查当前已结束赛季并发放赛季奖励, 只发放上一期的
        if ftlog.is_debug():
            ftlog.debug('============= processEnterGame userId=', evt.userId)
        _, intClientId = sessiondata.getClientIdNum(evt.userId)
        if intClientId == 24105:
            latestTwoIssues = SegmentMatchHelper.getIssueStateList()[-2:]
            for issuestate in reversed(latestTwoIssues):
                if issuestate['state'] == 0:
                    continue

                # 判断用户有没有结算此赛季
                userData = SegmentMatchHelper.getUserSegmentDataIssue(
                    evt.userId, issuestate['issue']) or UserSegmentDataIssue()
                if userData and userData.segmentRewardsState == UserSegmentDataIssue.IDEAL:
                    # 结算 发奖
                    settlementRanking(evt.userId, issuestate['issue'])

        segmentConf = getSegmentConf()
        if segmentConf.closed:
            return

        if evt.dayFirst:
            # 检查用户是否已经发送
            if not gamedata.getGameAttrInt(evt.userId, DIZHU_GAMEID,
                                           'wxNotice'):
                # 保存消息记录
                gamedata.setGameAttr(evt.userId, DIZHU_GAMEID, 'wxNotice', 1)

                # 新用户发送一条额外消息
                mailstr = '游戏公告#如有任何意见建议,欢迎加客服微信:Tuyoo_taozi,进入官方群反馈'
                message.send(DIZHU_GAMEID, message.MESSAGE_TYPE_SYSTEM,
                             evt.userId, mailstr)

        # 同步钻石为用户道具
        if not segmentdata.getSegmentAttr(evt.userId, DIZHU_GAMEID,
                                          'diamondConvert'):
            segmentdata.setSegmentAttr(evt.userId, DIZHU_GAMEID,
                                       'diamondConvert', 1)
            userDiamond = userdata.getAttr(evt.userId, 'diamond')
            if userDiamond:
                # count
                user_remote.consumeAssets(DIZHU_GAMEID, evt.userId,
                                          [{
                                              'itemId': 'user:diamond',
                                              'count': userDiamond
                                          }], 'DIZHU_SEGMENT_DIAMOND_CONVERT',
                                          0)
                contentItems = TYContentItem.decodeList([{
                    'itemId': 'item:1311',
                    'count': userDiamond
                }])
                from dizhu.entity import dizhu_util
                dizhu_util.sendRewardItems(evt.userId, contentItems, None,
                                           'DIZHU_SEGMENT_DIAMOND_CONVERT', 0)
                ftlog.info('DizhuSegmentRewardsHelper diamondConvert userId=',
                           evt.userId, 'userDiamond=', userDiamond)
コード例 #26
0
 def _calcRegDays(self, userId, timestamp):
     registerTimeStr = pkuserdata.getAttr(userId, 'createTime')
     nowDT = datetime.fromtimestamp(timestamp)
     try:
         registerTime = datetime.strptime(registerTimeStr, '%Y-%m-%d %H:%M:%S.%f')
     except:
         registerTime = nowDT
     
     return max(0, (nowDT.date() - registerTime.date()).days)
コード例 #27
0
ファイル: toolbox.py プロジェクト: luningcowboy/tuyoo
 def getRegisterDays(cls, userId, timestamp):
     '''
     获取注册的天数
     :param userId:
     :param timestamp:当前时间戳
     '''
     nowDate = datetime.fromtimestamp(timestamp).date()
     createDate = datetime.strptime(userdata.getAttr(userId, 'createTime'),
                                    '%Y-%m-%d %H:%M:%S.%f').date()
     return max(0, (nowDate - createDate).days)
コード例 #28
0
ファイル: hallneituiguang.py プロジェクト: zhaozw/hall37
    def doGetUserState(cls, gameId, userId, clientId, action):
        '''
        获取用户信息,不存在则,验证用户状态,写入用户活动状态表,并返回用户状态
        '''
        conf = hallconf.getNeiTuiGuangConf(clientId)
        mo = MsgPack()
        if not conf:
            ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=',
                        clientId, 'action=', action)
            return mo
        state = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
        createTime = userdata.getAttr(userId, 'createTime')
        if state == None:
            state = cls.initUserState(userId, gameId, createTime, conf)
            userdata.setAttr(userId, cls.attrname_state, state)
            inviteetip = cls.inviteeTip(userId, gameId, createTime, conf)
        else:
            if cls.isOldUser(userId, gameId, createTime, conf):
                state = 2
                userdata.setAttr(userId, cls.attrname_state, state)  # 老用户状态

        if state == 0:
            NeiTuiGuangProtocolBuilder.buildNewUserState(gameId, userId, action, state, inviteetip, mo)
        elif state == 1:
            bindmobile = userdata.getAttr(userId, 'bindMobile')
            bindok = cls.bindOk(bindmobile)
            NeiTuiGuangProtocolBuilder.buildBindUserState(gameId, userId, action, state, bindok, mo)
        elif state == 2:
            bindmobile = userdata.getAttr(userId, 'bindMobile')
            bindok = cls.bindOk(bindmobile)
            shareId = conf.get('shareId', -1)
            prizeinfo = conf.get('prize_info', [])
            weixintip = cls.getWeiXinTip(userId, conf)
            url = cls.getDownUrl(userId, conf)
            smstip = cls.getSMSTip(gameId, userId, conf)
            rules = conf.get('rules', [])
            NeiTuiGuangProtocolBuilder.buildOldUserState(gameId, userId, action, state, bindok, shareId, prizeinfo,
                                                         weixintip, url, smstip, rules, mo)
        else:
            pass

        return mo
コード例 #29
0
ファイル: erdayi.py プロジェクト: luningcowboy/tuyoo
    def getInfo(cls, userId):
        '''
        牌手信息
        '''
        ftlog.debug('PlayerControl.getInfo:params', 'userId=', userId)
        response = cls.makeResponse(userId)

        # 1.获取玩家认证信息,获取身份证号码
        realinfo = PlayerData.getRealInfo(userId)

        # 2.获取玩家银行卡信息
        bankinfo = PlayerData.getBankInfo(userId)

        # 3.获得玩家大师分信息
        masterinfo = None
        if realinfo and realinfo.get('idNo'):
            master_resp = cls.getMasterInfo(userId)
            master_resp_code = master_resp.getResult('code')
            master_resp_msg = master_resp.getResult('info')
            masterinfo = master_resp.getResult('rating')
            if master_resp_code != ErrorEnum.ERR_OK:
                response = cls.makeResponse(userId, master_resp_code,
                                            master_resp_msg, True)

        # 4.获得玩家钱包信息,需要玩家认证才能获取
        walletinfo = None
        if realinfo:
            wallet_resp = cls.getWalletInfo(userId)
            wallet_resp_code = wallet_resp.getResult('code')
            wallet_resp_msg = wallet_resp.getResult('info')
            walletinfo = wallet_resp.getResult('wallet')
            if wallet_resp_code != ErrorEnum.ERR_OK:
                response = cls.makeResponse(userId, wallet_resp_code,
                                            wallet_resp_msg, True)

        # 组装
        if realinfo:
            response.setResult('realInfo', realinfo)
        if bankinfo:
            response.setResult('bank', bankinfo)
        if masterinfo:
            response.setResult('rating', masterinfo)
        if walletinfo:
            response.setResult('wallet', walletinfo)

        # 附加字段
        response.setResult('authRewardDesc', cls.getConf('auth_reward_desc'))

        bindMobile = pkuserdata.getAttr(userId, 'bindMobile')
        if isstring(bindMobile) and len(bindMobile) > 0:
            response.setResult('bindedMobile', bindMobile)

        return response
コード例 #30
0
ファイル: util.py プロジェクト: zhaozw/hall37
def logTableChat(gameId, roomId, tableId, senderUserId, chatText):
    if not chatText:
        return
    if senderUserId <= 0:
        return
    try:
        username = unicode(str(userdata.getAttr(senderUserId, 'name')))
        roomName = unicode(str(gdata.getRoomConfigure(roomId)['name']))
        ftlog.hinfo('tableChatLog gameId=%s; room="%s"; table=%s; userId=%s; name="%s"; msg="%s"' % (
            gameId, roomName, tableId, senderUserId, username, chatText))
    except Exception, e:
        ftlog.exception('exception locals():', locals())
コード例 #31
0
ファイル: dizhuled.py プロジェクト: luningcowboy/tuyoo
def _randName():
    uid = random.randrange(10000, 30000000)
    name = userdata.getAttr(uid, 'name')  #cls.getName(uid)
    if not name:
        pre = ['360', '91_', 'momo', 'ly_', 'tx_', 'kugou']
        tail = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ123456789'
        head = random.choice(pre)
        count = random.randrange(3, 7)
        for _ in xrange(count):
            head += random.choice(tail)
        name = head
    return str(name)
コード例 #32
0
def getShareTaskInfo(userId):
    """
    获取分享有礼信息
    """
    shareGroupIds = weakdata.getDayFishData(userId, "shareGroupIds", [])
    shareGroupTotalCount = config.getCommonValueByKey("shareGroupTotalCount")
    shareGroupCurrentCount = min(len(shareGroupIds), shareGroupTotalCount)
    groupTask = {
        "taskId": 0,
        "progress": [shareGroupCurrentCount, shareGroupTotalCount], # 分享群数/总数
        "rewards": config.getCommonValueByKey("shareGroupRewards"),
        "state": weakdata.getDayFishData(userId, "shareGroupReward", 0)
    }
    if groupTask["state"] == 0 or util.isVersionLimit(userId):
        module_tip.cancelModuleTipEvent(userId, "invite", 0)
    inviteTasks = []
    inviteList = refreshInviteData(userId)
    for _, inviteData in enumerate(inviteList):
        name = util.getNickname(inviteData["userId"])
        avatar = userdata.getAttr(inviteData["userId"], "purl")
        if inviteData.get("isAppUser", 0) == 1:
            continue
        if inviteData.get("isNewUser"):
            rewards = config.getCommonValueByKey("newUserInviteFriendRewards")
        else:
            rewards = config.getCommonValueByKey("inviteFriendRewards")
        task = {
            "taskId": inviteData["inviteId"],
            "name": name,
            "avatar": avatar,
            "vip": hallvip.userVipSystem.getUserVip(userId).vipLevel.level,
            "state": 2 if inviteData.get("receiveTime") else 1,
            "rewards": rewards
        }
        inviteTasks.append(task)
    inviteCount = weakdata.getDayFishData(userId, "inviteCount", 0)
    inviteTotalCount = config.getCommonValueByKey("inviteLimitCount", 99999)
    inviteCount = min(inviteCount, inviteTotalCount)
    friendTask = {
        "progress": [inviteCount, inviteTotalCount],
        "rewards": config.getCommonValueByKey("inviteFriendRewards"),
        "newUserRewards": config.getCommonValueByKey("newUserInviteFriendRewards"),
        "tasks": inviteTasks
    }
    message = MsgPack()
    message.setCmd("share_task_info")
    message.setResult("gameId", FISH_GAMEID)
    message.setResult("userId", userId)
    if not util.isVersionLimit(userId):
        message.setResult("groupTask", groupTask)
    message.setResult("friendTask", friendTask)
    router.sendToUser(message, userId)
コード例 #33
0
ファイル: account.py プロジェクト: isoundy000/learn_python
def modifyUserName(userId):
    """
    iOS下游客登录及苹果登录用户修改昵称为g_xxxx
    """
    clientIdNum = util.getClientIdNum(userId)
    if clientIdNum in config.getCommonValueByKey("randomNickNameClientIds",
                                                 []):
        snsId = userdata.getAttr(userId, "snsId")
        if not snsId or str(snsId).startswith("ios"):
            nickName = "g_" + ''.join(
                random.choice(string.ascii_letters + string.digits)
                for _ in range(7))
            userdata.setAttr(userId, "name", nickName)
コード例 #34
0
def logTableChat(gameId, roomId, tableId, senderUserId, chatText):
    if not chatText:
        return
    if senderUserId <= 0:
        return
    try:
        username = unicode(str(userdata.getAttr(senderUserId, 'name')))
        roomName = unicode(str(gdata.getRoomConfigure(roomId)['name']))
        ftlog.hinfo(
            'tableChatLog gameId=%s; room="%s"; table=%s; userId=%s; name="%s"; msg="%s"'
            % (gameId, roomName, tableId, senderUserId, username, chatText))
    except Exception, e:
        ftlog.exception('exception locals():', locals())
コード例 #35
0
ファイル: userchip.py プロジェクト: zhaozw/hall37
def getUserChipAll(uid):
    '''
    取得用户的所有金币, 包含被带入的金币
    '''
    uchip = userdata.getAttr(uid, daoconst.ATT_CHIP)
    gchip1 = gamedata.getGameAttrInt(uid, 1, daoconst.ATT_TABLE_CHIP)  # TODO 就代码数据兼容, 可删除
    gchip8 = gamedata.getGameAttrInt(uid, 8, daoconst.ATT_TABLE_CHIP)  # TODO 就代码数据兼容, 可删除
    tchips = daobase.executeUserCmd(uid, 'HVALS', daoconst.HKEY_TABLECHIP + str(uid))
    allchip = uchip + gchip1 + gchip8
    if tchips:
        for x in tchips:
            if isinstance(x, (int, float)):
                allchip += int(x)
    return allchip
コード例 #36
0
ファイル: dizhuusercond.py プロジェクト: luningcowboy/tuyoo
 def check(self, gameId, userId, clientId, timestamp, **kwargs):
     if not self.limitProvinces:
         return False
     province = userdata.getAttr(userId, 'province')
     if not province:
         return False
     try:
         province = province.encode('utf8') if isinstance(
             province, unicode) else province
     except:
         return False
     if province in self.limitProvinces:
         return True
     return False
コード例 #37
0
def checkRename(gameId, userId):
    #set_name_sum
    setNameSum = userdata.getAttr(userId, 'set_name_sum')
    if not setNameSum:
        # 第一次改名,直接改
        return True, stringRenameDescFirst
    else:
        # 第一次以后需要消耗1张改名卡
        timestamp = pktimestamp.getCurrentTimestamp()
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        if userAssets.balance(gameId, hallitem.ASSET_RENAME_CARD_KIND_ID,
                              timestamp) > 0:
            return True, stringRenameDesc
        return False, stringRenameCardRequired
コード例 #38
0
ファイル: xingyaoled.py プロジェクト: luningcowboy/tuyoo
 def onWinlose(cls, event):
     needSendLed = cls.needSendLed(event)
     if ftlog.is_debug():
         ftlog.debug('XingyaoLed.onWinlose gameId=', event.gameId,
                     'userId=', event.userId,
                     'roomId=', event.roomId,
                     'bigRoomId=', gdata.getBigRoomId(event.roomId),
                     'isWin=', event.winlose.isWin,
                     'deltaChip=', event.winlose.deltaChip,
                     'WINCHIP_LIMIT=', cls.WINCHIP_LIMIT,
                     'ROOM_IDS=', cls.ROOM_IDS,
                     'needSendLed=', needSendLed)
     if needSendLed:
         userName = userdata.getAttr(event.userId, 'name')
         dizhuled.sendLed('恭喜%s在经典星耀大师场赢取金币%s!' % (userName, event.winlose.deltaChip))
コード例 #39
0
def getRegisterDay(userId):
    """
    获取玩家注册的天数
    """
    registerTimeStr = userdata.getAttr(userId, 'createTime')
    nowTime = datetime.now()
    try:
        registerTime = datetime.strptime(registerTimeStr, '%Y-%m-%d %H:%M:%S.%f')
    except:
        registerTime = nowTime
    ct = nowTime.time()
    dt1 = datetime.combine(nowTime.date(), ct)
    dt2 = datetime.combine(registerTime.date(), ct)
    past = dt1 - dt2
    return int(past.days)
コード例 #40
0
ファイル: hallneituiguang.py プロジェクト: zhaozw/hall37
    def doGetPrize(cls, gameId, userId, clientId, action):
        '''
        新用户领奖接口
        '''
        conf = hallconf.getNeiTuiGuangConf(clientId)
        if not conf:
            ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=',
                        clientId, 'action=', action)
            return
        mo = MsgPack()
        bindmobile = userdata.getAttr(userId, 'bindMobile')
        userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
        if cls.bindOk(bindmobile):
            prizeGet = cls.sendBothUserPrize(gameId, userId, userstate, conf)

            if prizeGet == -1:  # 用户状态错误
                NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, "用户状态错误", mo)
            else:  # 发送奖励成功
                NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, cls.getprize(gameId, 0, conf, prizeGet), mo)
        else:  # 未绑定手机
            NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 2, conf), mo)

        return mo
コード例 #41
0
ファイル: mtt_room.py プロジェクト: zhaozw/hall37
    def __sendFinalTableInfo(self, finalTableStartTime):
        waitingUserIds = self.scheduler.users.keys()  # 防止处理过程中users变化导致数据不一致
        waitingUserN = len(waitingUserIds)
        if ftlog.is_debug():
            ftlog.debug("<< |roomId:", self.roomId,
                        "|waitingUserN:", waitingUserN)

        mpToClient = MsgPack()
        mpToClient.setCmd("final_table_info")
        mpToClient.setResult('gameId', self.gameId)
        mpToClient.setResult('roomId', self.bigRoomId)
        mpToClient.setResult('finalTableStartTime', time.mktime(finalTableStartTime.timetuple()))
        mpToClient.setResult('nowServerTime', int(time.time()))

        playerInfos = []
        for seatId, userId in enumerate(waitingUserIds):
            name = userdata.getAttr(userId, 'name')

            playerRoomInfo = PlayerRoomDao.getPlayerRoomRecord(userId, self.bigRoomId)
            if ftlog.is_debug():
                ftlog.debug("get playerRoomInfo |userId, tableId:", userId, self.roomId, playerRoomInfo, caller=self)

            item = {}
            item["userId"] = userId
            item["seatId"] = seatId
            item["tableChip"] = playerRoomInfo["tableChips"]
            item["name"] = name
            playerInfos.append(item)
        mpToClient.setResult("players", playerInfos)
        router.sendToUsers(mpToClient, waitingUserIds)

        self.matchPlugin.refreshBuyin(self)

        # Send final table information to monitor_mtt.py
        TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_MTT_FINAL_TABLE', params={
            'roomId': self.roomId}), self.gameId)
コード例 #42
0
ファイル: gm.py プロジェクト: zhaozw/hall37
    def _doTableGmGetTableDetail(self, gameId, roomId, tableId, token):
        '''获取牌桌信息'''
        room = gdata.rooms()[roomId]  # shadow roomId
        table = room.maptable[tableId]
        ftlog.info('GM._doTableGmGetTableDetail << |', 'roomId, tableId, token:', roomId, tableId, token)

        players = []
        for player in table.players:
            if player.userId > 0:
                userVip = hallvip.userVipSystem.getUserVip(player.userId)
                vipLevel = (userVip and userVip.vipLevel and userVip.vipLevel.level) or 0
                createTime, chargeTotal, ip = userdata.getAttrs(player.userId,
                                                                ['createTime', 'chargeTotal', 'sessionClientIP'])
                playerInfo = {
                    'seatId': player.seatId,
                    'purl': player.purl,
                    'name': player.name,
                    'userId': player.userId,
                    'holeCards': player.holeCards,
                    'cardtype': player.cardtype,
                    'cardOrder': player.order,
                    'bet': player.bet,
                    'userChips': player.userChips,
                    'tableChips': player.tableChips,
                    'sharkLevel': player.sharkLevel,
                    'vipLevel': vipLevel,
                    'chargeTotal': chargeTotal,
                    'createTime': createTime,
                    'ip': ip,
                    'localPic': player.localPic,
                }
                if not token:
                    del playerInfo['holeCards']
                    del playerInfo['cardtype']
                    del playerInfo['cardOrder']
                players.append(playerInfo)

        obs = []
        for userId in table.observers.keys():
            userVip = hallvip.userVipSystem.getUserVip(userId)
            vipLevel = (userVip and userVip.vipLevel and userVip.vipLevel.level) or 0
            name, chip = userdata.getAttrs(userId, ['name', 'chip'])
            ob = {
                'userId': userId,
                'name': name,
                'chip': chip,
            }
            obs.append(ob)

        tableDetail = {
            'tableId': table.tableId,
            'cards': table.gamePlay.sharedCards,
            'players': players,
            'obs': obs,
        }
        if getattr(table, 'creatorId', 0):
            tableDetail['主播'] = userdata.getAttr(table.creatorId, 'name')
            tableDetail['主播id'] = table.creatorId

        if not token:
            del tableDetail['cards']
        return tableDetail
コード例 #43
0
ファイル: userchip.py プロジェクト: zhaozw/hall37
def getCoupon(uid):
    return userdata.getAttr(uid, daoconst.ATT_COUPON)
コード例 #44
0
ファイル: userchip.py プロジェクト: zhaozw/hall37
def getChip(uid):
    return userdata.getAttr(uid, daoconst.ATT_CHIP)
コード例 #45
0
ファイル: userchip.py プロジェクト: zhaozw/hall37
def getCoin(uid):
    return userdata.getAttr(uid, daoconst.ATT_COIN)
コード例 #46
0
ファイル: userchip.py プロジェクト: zhaozw/hall37
def getDiamond(uid):
    return userdata.getAttr(uid, daoconst.ATT_DIAMOND)
コード例 #47
0
ファイル: user_remote.py プロジェクト: zhaozw/hall37
def _getFriendGameInfo(userId, gameIds, for_level_info, for_winchip, for_online_info=1):
    uid = int(userId)
    datas = {}
    gid, rid, tid, sid = 0, 0, 0, 0
    state = daoconst.OFFLINE
    if for_online_info:
        loclist = onlinedata.getOnlineLocList(uid)
        state = onlinedata.getOnlineState(uid)
        if len(loclist) > 0:
            _rid, _tid, _sid = loclist[0]
            # gid表示用户在哪个游戏中
            gid = strutil.getGameIdFromInstanceRoomId(_rid)
            # 检查是否可加入游戏
            if TYGame(gid).canJoinGame(userId, _rid, _tid, _sid):
                # rid/tid/sid表示用户所在的游戏是否可加入游戏
                # 分享出来的都是可以加入游戏的牌桌信息
                rid = _rid
                tid = _tid
                sid = _sid
            if ftlog.is_debug():
                ftlog.debug('getFriendGameInfo userId:', userId, ' gameId:', gid, ' roomId:', _rid, ' tableId:', _tid,
                            ' seatId:', _sid, ' can not join game....')
        if state == daoconst.OFFLINE:
            offline_time = gamedata.getGameAttr(uid, HALL_GAMEID, 'offlineTime')
            if not offline_time:  # 取不到离线时间,取上线时间
                offline_time = userdata.getAttr(uid, 'authorTime')
            if offline_time:
                offline_time = pktimestamp.parseTimeMs(offline_time)
                delta = datetime.now() - offline_time
                delta = delta.days * 24 * 60 + delta.seconds / 60  # 分钟数
            else:  # 异常情况
                delta = 24 * 60
            datas['offline_time'] = delta if delta > 0 else 1
        if rid > 0:
            try:
                room = gdata.roomIdDefineMap().get(rid, None)
                if room:
                    datas['room_name'] = room.configure['name']
            except:
                ftlog.error()
    # 构造回传给SDK的游戏数据
    datas.update({'uid': uid, 'gid': gid, 'rid': rid, 'tid': tid, 'sid': sid, 'state': state})

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

    if for_winchip:
        datas['winchip'] = 0
        datas['winchips'] = 0
        try:
            for gameId in gameIds:
                winchips, todaychips = gamedata.getGameAttrs(userId, gameId, ['winchips', 'todaychips'], False)
                winchips = strutil.parseInts(winchips)
                yest_winchip = 0
                todaychips = strutil.loads(todaychips, ignoreException=True)
                if todaychips and 'today' in todaychips and 'chips' in todaychips and 'last' in todaychips:
                    if pktimestamp.formatTimeDayInt() == todaychips['today']:
                        yest_winchip = todaychips['last']
                    elif pktimestamp.formatTimeYesterDayInt() == todaychips['today']:
                        yest_winchip = todaychips['chips']
                datas['winchip'] += yest_winchip
                datas['winchips'] += winchips
        except:
            ftlog.error()
    return datas
コード例 #48
0
ファイル: hallstartchip.py プロジェクト: zhaozw/hall37
def needSendStartChip(userId, gameId):
    '''是否发放启动资金
    '''
    global newuser_startchip

    return (1 == userdata.getAttr(userId, 'sendMeGift')) and (newuser_startchip > 0)