コード例 #1
0
    def decodeFromDict(self, d):
        self.startRank = d.get('startRank')
        if not isinstance(self.startRank, int):
            raise TYBizConfException(d, 'RankRewardItem.startRank must be int')

        self.endRank = d.get('endRank')
        if not isinstance(self.endRank, int):
            raise TYBizConfException(d, 'RankRewardItem.endRank must be int')

        self.rewardDesc = d.get('rewardDesc')
        if not isstring(self.rewardDesc):
            raise TYBizConfException(d,
                                     'RankRewardItem.rewardDesc must be str')

        self.rewardPic = d.get('rewardPic')
        if not isstring(self.rewardPic):
            raise TYBizConfException(d, 'RankRewardItem.rewardPic must be str')

        rewards = d.get('rewards')
        if not isinstance(rewards, list):
            raise TYBizConfException(d, 'RankRewardItem.rewards must be list')
        try:
            TYContentItem.decodeList(rewards)
        except Exception, e:
            raise TYBizConfException(
                d, 'RankRewardItem.rewards must be list err=%s' % e.message)
コード例 #2
0
ファイル: dizhu_invite.py プロジェクト: luningcowboy/tuyoo
    def doGetInviteRewardAll(cls, userId):
        status = loadStatus(userId)
        inviteeRewardList = status.inviteeRewardList
        rewardsList = []
        bigReward = None
        save = False
        for index, rewardState in enumerate(inviteeRewardList):
            if rewardState.rewardState == REWARD_STATE_IDEAL:
                rewardState.rewardState = REWARD_STATE_RECEIVED
                save = True
                r = getSimpleInviteRewardByIndex(index)
                if r:
                    rewardsList.append(r)
        if rewardsList:
            contentItems = TYContentItem.decodeList(rewardsList)
            assetList = dizhu_util.sendRewardItems(userId, contentItems, '', 'DIZHU_QIANDAO_REWARD', 0)

        if len(inviteeRewardList) >= len(getSimpleInviteRewardsConf()):
            bigReward = getSimpleInviteBigReward(userId)
            if bigReward:
                contentItems = TYContentItem.decodeList([bigReward])
                assetList = dizhu_util.sendRewardItems(userId, contentItems, '', 'DIZHU_QIANDAO_REWARD', 0)
                if bigReward.get('itemId') == 'user:coupon':
                    TGHall.getEventBus().publishEvent(UserCouponReceiveEvent(9999, userId, bigReward['count'],
                                                                         user_coupon_details.USER_COUPON_INVITE))
                status.bigRewardState = REWARD_STATE_RECEIVED
                save = True
                conf = getSimpleInviteConf()
                if conf.get('switch'):
                    gamedata.setGameAttr(userId, DIZHU_GAMEID, 'firstBigRewards', 1)
        if save:
            saveStatus(status)
        return rewardsList, bigReward
コード例 #3
0
    def decodeFromDict(self, d):
        self.unlockSeconds = d.get('unlockSeconds')
        if not isinstance(self.unlockSeconds, int) or self.unlockSeconds < 0:
            raise TYBizConfException(d, 'RewardControlFixedHelp.unlockSeconds must be int')

        self.extraReward = d.get('extraReward')
        if not isinstance(self.extraReward, dict):
            raise TYBizConfException(d, 'RewardControlFixedHelp.extraReward must be dict')
        try:
            TYContentItem.decodeList([self.extraReward])
        except Exception, e:
            raise TYBizConfException(d, 'RewardControlFixedHelp.extraReward Item error=%s' % e.message)
コード例 #4
0
def gainUserRanklistReward(userId, rankId, issueNum, clientId=None):
    # 发放周榜奖励
    userData = loadUserData(userId, rankId, issueNum)
    if not userData:
        raise TYBizException(-1, '没有找到用户数据')

    if userData.rewardState == RewardState.ST_NO_REWARD:
        raise TYBizException(-1, '本期没有奖励可领取')

    if userData.rewardState == RewardState.ST_GAIN_REWARD:
        raise TYBizException(-1, '已经领取了奖励')

    clientId = clientId or sessiondata.getClientId(userId)
    rankRewards = findRankRewardsByRank(rankId, issueNum, clientId,
                                        userData.rank)
    if not rankRewards:
        if ftlog.is_debug():
            ftlog.debug('gainUserRanklistReward rankReward is None. userId=',
                        userId, 'rankId=', rankId, 'issueNum=', issueNum,
                        'clientId=', clientId)
        # TODO warn or error
        raise TYBizException(-1, '未取到对应奖励配置')

    userData.rewardState = RewardState.ST_GAIN_REWARD
    saveUserData(userData)

    contentItems = TYContentItem.decodeList(rankRewards.get('items'))
    assetList = dizhu_util.sendRewardItems(userId, contentItems,
                                           _scoreRankConf.rewardMail,
                                           'DIZHU_SCORE_RANKLIST', int(rankId))

    ftlog.info('gainUserRanklistReward', 'userId=', userId, 'rankId=', rankId,
               'issueNum=', issueNum, 'rank=', userData.rank, 'rewards=',
               [(atp[0].kindId, atp[1]) for atp in assetList])
    return assetList
コード例 #5
0
def sendLoginReward(gameId, userId, clientId, iscreate, isdayfirst):
    if iscreate:
        newUserReward = configure.getGameJson(gameId, 'login.reward',
                                              {}).get('newUserReward')
        if newUserReward:
            if not newUserReward.get('open', 0):
                return
            rewards = newUserReward.get('rewards')
            if rewards:
                mail = newUserReward.get('mail')
                contentItems = TYContentItem.decodeList(rewards)
                dizhu_util.sendRewardItems(userId, contentItems, mail,
                                           'LOGIN_REWARD', 0)
                FTTasklet.getCurrentFTTasklet().sleepNb(1.5)
                msg = MsgPack()
                msg.setCmd('dizhu')
                msg.setResult('action', 'new_user_reward')
                msg.setResult('rewards', rewards)
                msg.setResult('cardNoteCount',
                              newUserReward.get('cardNoteCount', 0))
                router.sendToUser(msg, userId)
                ftlog.info(
                    'dizhu_login_reward.sendLoginReward newUserReward userId=',
                    userId, 'gameId=', gameId, 'clientId=', clientId,
                    'iscreate=', iscreate, 'isdayfirst=', isdayfirst,
                    'rewards=', rewards)
コード例 #6
0
    def handleRequest(self, userId, clientId, action, msg):
        if action == self.ACTION_SHARE_CHARM_RANK_LIST:
            return self.getRankRewardList(userId)
        elif action == self.ACTION_SHARE_CHARM_REWARD:
            # 更改用户领奖状态
            issue = calculateLastIssue(self.settleDayOrWeek)
            realRank = getUserRealRank(userId, self.actId, issue)
            rankRewardItem = self.getUserRankRewardItem(userId, realRank)
            userData = UserShareCharmData(userId).loadUserData(self.actId)
            issueData = userData.getIssueData(issue)

            if not issueData:
                raise ActivityWxException(-6, '您没有参与%s活动哦~' % issue)

            if issueData.state == SHARE_CHARM_REWARD_STATE_GOT:
                raise ActivityWxException(-4, '您已领取奖励哦~')
            # 发奖
            if rankRewardItem:
                userData.updateState(self.actId, issue)
                rewards = rankRewardItem.rewards
                rewardsItems = TYContentItem.decodeList(rewards)
                dizhu_util.sendRewardItems(userId, rewardsItems, '',
                                           'ACT_WX_SHARE_CHARM', self.intActId)
                for reward in rewards:
                    if reward['itemId'] == 'user:coupon':
                        from hall.game import TGHall
                        TGHall.getEventBus().publishEvent(
                            UserCouponReceiveEvent(
                                HALL_GAMEID, userId, reward['count'],
                                user_coupon_details.USER_COUPON_SHARE_CHARM))
                return rewards
            raise ActivityWxException(-5, '您没有奖励可领取哦~')
        return None
コード例 #7
0
def chooseReward(self, userId, matchId, rank):
    if ftlog.is_debug():
        ftlog.debug('MatchLottery userId=', userId, 'matchId=', matchId,
                    'rank=', rank)

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

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

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

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

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

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

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

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

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

    return lotteryReward, items
コード例 #8
0
    def decodeFromDict(self, d):
        self.active = d.get('active')
        if not isinstance(self.active, int):
            raise TYBizConfException(d, 'ActiveRewardItem.active must be int')

        self.scheduleId = d.get('scheduleId')
        if not isinstance(self.scheduleId, int):
            raise TYBizConfException(
                d, 'ActiveRewardItem.scheduleId must be int')

        self.rewardDesc = d.get('rewardDesc')
        if not isstring(self.rewardDesc):
            raise TYBizConfException(
                d, 'ActiveRewardItem.rewardDesc must be str')
        self.rewardPic = d.get('rewardPic')
        if not isstring(self.rewardPic):
            raise TYBizConfException(d,
                                     'ActiveRewardItem.rewardPic must be str')
        rewards = d.get('rewards')
        if not isinstance(rewards, list):
            raise TYBizConfException(d,
                                     'ActiveRewardItem.rewards must be list')
        try:
            r = TYContentItem.decodeList(rewards)
        except Exception, e:
            raise TYBizConfException(
                d, 'ActiveRewardItem.rewards err=%s' % e.message)
コード例 #9
0
def _changeUserBehaviourInfo(userId, ret, behaviourConf):
    try:
        reward = behaviourConf.get('reward') if behaviourConf else None
        if not reward:
            return
        ret['type'] = BEHAVIOUR_TYPE_REWARDED
        daobase.executeUserCmd(userId, 'HSET',
                               'userBehaviour:6:' + str(userId), 'info',
                               strutil.dumps(ret))

        mailStr = behaviourConf.get('mail', '幸运女神的眷顾使你获得了奖励')
        contentItems = TYContentItem.decodeList(reward)
        assetList = dizhu_util.sendRewardItems(userId, contentItems, mailStr,
                                               'USER_BEHAVIOUR_REWARD', userId)
        datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, mailStr)

        # 发奖弹窗
        rewardsList = []
        for assetItemTuple in assetList:
            assetItem = assetItemTuple[0]
            reward = {}
            reward['name'] = assetItem.displayName
            reward['pic'] = assetItem.pic
            reward['count'] = assetItemTuple[1]
            rewardsList.append(reward)

        reward_task = TodoTaskShowRewards(rewardsList)
        TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, reward_task)

        ftlog.info('userBehaviour.sendReward userId=', userId, 'reward=',
                   [(atp[0].kindId, atp[1]) for atp in assetList])

    except Exception, e:
        ftlog.warn('_changeUserBehaviourInfo userId=', userId, 'ret=', ret,
                   'err=', e)
コード例 #10
0
ファイル: wx_follow.py プロジェクト: luningcowboy/tuyoo
    def decodeFromDict(self, d):
        self.startCount = d.get('startCount')
        if not isinstance(self.startCount, int):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.startCount must be int')

        self.endCount = d.get('endCount')
        if not isinstance(self.endCount, int):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.endCount must be int')

        self.rewardDesc = d.get('rewardDesc')
        if not isstring(self.rewardDesc):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewardDesc must be str')

        self.rewardPic = d.get('rewardPic')
        if not isstring(self.rewardPic):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewardPic must be str')

        rewards = d.get('rewards')
        if not isinstance(rewards, list):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewards must be list')
        try:
            self.rewards = TYContentItem.decodeList(rewards)
            self.rewardsConf = rewards
        except Exception, e:
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewards err=%s' % e.message)
コード例 #11
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)
コード例 #12
0
ファイル: roominfo.py プロジェクト: zhaozw/hall37
 def fromDict(self, d):
     self.signinCount = d.get('signinCount', 0)
     self.startType = d.get('startType')
     self.instId = d.get('instId')
     self.startTime = d.get('startTime')
     self.signinTime = d.get('signinTime')
     fees = d.get('fees')
     if fees:
         self.fees = TYContentItem.decodeList(fees)
     return self
コード例 #13
0
 def fromDict(self, d):
     self.signinCount = d.get('signinCount', 0)
     self.startType = d.get('startType')
     self.instId = d.get('instId')
     self.startTime = d.get('startTime')
     self.signinTime = d.get('signinTime')
     fees = d.get('fees')
     if fees:
         self.fees = TYContentItem.decodeList(fees)
     return self
コード例 #14
0
    def decodeFromDict(self, d):
        productId = d.get('productId')
        if not isstring(productId):
            raise TYBizConfException(
                d, 'ChargeProductConf.productId must be str')
        product = hallstore.findProduct(None, None, productId)
        if not product:
            raise TYBizConfException(
                d, 'ChargeProductConf.productId %s doesNot exists' % productId)
        self.product = product

        rewards = d.get('rewards', [])
        if not isinstance(rewards, list):
            raise TYBizConfException(d,
                                     'ChargeProductConf.rewards must be list')
        if rewards:
            try:
                TYContentItem.decodeList(rewards)
            except Exception, e:
                raise TYBizConfException(
                    d, 'ChargeProductConf.rewards err=%s' % e.message)
コード例 #15
0
 def sendWatchAdRewards(cls, userId, adId):
     data = getUserWatchAdData(userId)
     if data.watchCount < cls.getDailyCountLimit():
         # 保存用户观看数据
         data.watchCount += 1
         saveUserWatchAdData(userId, data)
         # 发奖
         reward = cls.getAdRewardByWeight(adId, data.watchCount)
         if reward:
             contentItems = TYContentItem.decodeList([reward])
             from dizhu.entity import dizhu_util
             dizhu_util.sendRewardItems(userId, contentItems, None,
                                        'DIZHU_WATCH_AD_REWARD', 0)
             return reward, cls.getDailyCountLimit() - data.watchCount
     return None, 0
コード例 #16
0
 def processUserTableRewards(cls, userId, winlose):
     ''' 处理牌局结束用户的奖励 '''
     gameWinRewardConf = getSegmentConf().gameWinReward
     # 判断condition
     condList = gameWinRewardConf.get('conditions')
     if condList and winlose.isWin:
         for condD in condList:
             cond = UserConditionRegister.decodeFromDict(condD)
             clientId = sessiondata.getClientId(userId)
             retCheck = cond.check(DIZHU_GAMEID,
                                   userId,
                                   clientId,
                                   pktimestamp.getCurrentTimestamp(),
                                   winlose=winlose)
             if retCheck:
                 reward = gameWinRewardConf.get('reward')
                 if reward:
                     try:
                         contentItems = TYContentItem.decodeList([reward])
                         from dizhu.entity import dizhu_util
                         dizhu_util.sendRewardItems(
                             userId, contentItems, None,
                             'DIZHU_SEGMENT_TABLE_WIN', 0)
                         ret = SegmentMatchHelper.addUserSegmentTableWinRewardCount(
                             userId, reward['count'])
                         if ret:
                             retMsg = ''
                             if cond.TYPE_ID == UserConditionSegmentWinDoubles.TYPE_ID:
                                 retMsg = '满贯'
                             elif cond.TYPE_ID == UserConditionSegmentChuntian.TYPE_ID:
                                 retMsg = '春天'
                             retReward = {
                                 'itemId': reward['itemId'],
                                 'count': reward['count'],
                                 'des': retMsg
                             }
                             ftlog.info(
                                 'DizhuSegmentRewardsHelper.processUserTableRewards',
                                 'userId=', userId, 'typeId=', cond.TYPE_ID,
                                 'reward=', retReward)
                             return retReward
                         else:
                             return None
                     except Exception, e:
                         ftlog.error(
                             'DizhuSegmentRewardsHelper.processUserTableRewards',
                             'userId=', userId, 'gameWinRewardConf=',
                             gameWinRewardConf, 'errmsg=', e.message)
コード例 #17
0
ファイル: treasure_chest.py プロジェクト: luningcowboy/tuyoo
    def openTreasureChest(cls, userId, rewardId):
        ''' 开宝箱 '''
        userTreasureChest = UserTreasureChest(userId).loadTreasureChest()
        if userTreasureChest.checkOpenState(rewardId):
            ret = userTreasureChest.getTreasureChestByRewardId(rewardId)
            rewards = ret.rewards
            rewardType = ret.type
            # 给用户发奖
            if rewardType == TREASURE_CHEST_TYPE_AS_WINSTREAK:
                winSreak = ret.params.get('winStreak')
                winSreakConf = TreasureChestHelper.getWinStreakConf(winSreak)
                if winSreakConf:
                    rewards = [
                        dizhu_util.getItemByWeight(winSreakConf['rewards'])
                    ]
                    contentItems = TYContentItem.decodeList(rewards)
                    dizhu_util.sendRewardItems(
                        userId, contentItems, None,
                        'DIZHU_SEGMENT_MATCH_WINSTREAK', winSreak)
                    ftlog.info(
                        'TreasureChestHelper.openTreasureChest sendReward userId=',
                        userId, 'rewardId=', rewardId, 'rewards=', rewards)
                    # 如果是奖券则广播奖券事件
                    for reward in rewards:
                        if reward['itemId'] == 'user:coupon':
                            if rewardType == TREASURE_CHEST_TYPE_AS_WINSTREAK:
                                from hall.game import TGHall
                                TGHall.getEventBus().publishEvent(
                                    UserCouponReceiveEvent(
                                        HALL_GAMEID, userId, reward['count'],
                                        user_coupon_details.
                                        USER_COUPON_SOURCE_SEGMENT_WINSTREAK_TASK
                                    ))

            # 打开后删除宝箱
            ret = userTreasureChest.delTreasureChestByRewardId(rewardId)
            if ret:
                userTreasureChest.saveTreasureChest()
                ftlog.info(
                    'TreasureChestHelper.openTreasureChest deleteTreasureChest userId=',
                    userId, 'rewardId=', rewardId, 'rewards=', rewards)
            return True, rewards
        return False, None
コード例 #18
0
ファイル: dizhu_signin.py プロジェクト: luningcowboy/tuyoo
def _sendRewards(userId, day, typeId):
    signInData, hasReceive, expire = SignInDeskData(userId).loadData()
    if not expire and len(signInData.signInList) != day - 1:
        ftlog.warn('dizhu_signin._sendRewards error day userId=', userId,
                   'day=', day, 'typeId=', typeId)
        return 0, []
    if hasReceive:
        ftlog.warn('dizhu_signin._sendRewards has received userId=', userId,
                   'day=', day, 'typeId=', typeId)
        return 0, []
    conf = configure.getGameJson(DIZHU_GAMEID, 'signin', {})
    rewardList = conf.get('rewardList', {})
    rewards = []
    if expire:
        rewards = rewardList[0]['rewards']
    else:
        for reward in rewardList:
            if reward.get('day') == day:
                rewards = reward.get('rewards')
    if rewards:
        newRewards = rewards
        if typeId:
            newRewards = []
            for reward in rewards:
                newReward = {}
                newReward['count'] = 2 * reward['count']
                newReward['itemId'] = reward['itemId']
                newReward['pic'] = reward['pic']
                newRewards.append(newReward)
        contentItems = TYContentItem.decodeList(newRewards)
        dizhu_util.sendRewardItems(userId, contentItems, None,
                                   'SIGN_IN_DESK_REWARD', 0)
        signInData.updateSignInList()
        if ftlog.is_debug():
            ftlog.debug('dizhu_signin._sendRewards has rewards', 'userId=',
                        userId, 'typeId=', typeId, 'expire=', expire,
                        'newRewards=', newRewards, 'conf=', conf)
        return 1, newRewards
    ftlog.error('dizhu_signin._sendRewards conf error userId=', userId, 'day=',
                day, 'typeId=', typeId, 'conf=', conf)
    return 0, []
コード例 #19
0
def _onGameRoundFinish(self, event):
    bigRoomId = event.mixConfRoomId or gdata.getBigRoomId(event.roomId)
    dropRate = 0
    itemId = ''
    for roomConf in self._roomList:
        if bigRoomId in roomConf.get('roomId', []):
            dropRate = roomConf.get('dropRate', 0)
            itemId = roomConf.get('itemId')
            break

    if random.randint(0, 100) <= (dropRate * 100) and itemId:
        contentItems = TYContentItem.decodeList([{
            'itemId': itemId,
            'count': 1
        }])
        assetList = dizhu_util.sendRewardItems(event.userId, contentItems,
                                               self._mail,
                                               'DIZHU_ACT_CHRISTMAS_ITEM', 0)

        # 发奖弹窗
        from hall.entity.todotask import TodoTaskShowRewards, TodoTaskHelper
        rewardsList = []
        for assetItemTuple in assetList:
            assetItem = assetItemTuple[0]
            reward = dict()
            reward['name'] = assetItem.displayName
            reward['pic'] = assetItem.pic
            reward['count'] = assetItemTuple[1]
            rewardsList.append(reward)
        reward_task = TodoTaskShowRewards(rewardsList)
        TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, event.userId, reward_task)

        ftlog.info('gainChristmasFinalReward.todotask userId=', event.userId,
                   'items=', [(atp[0].kindId, atp[1]) for atp in assetList])

    if ftlog.is_debug():
        ftlog.debug('act.christmas._onGameRoundFinish.todotask userId=',
                    event.userId, 'bigRoomId=', bigRoomId, 'winLose=',
                    event.winlose.isWin, 'dropRate=', dropRate, 'itemId=',
                    itemId)
コード例 #20
0
    def gainUserReward(self, userId, rankId):
        # 玩家领取奖励
        rewardList = []
        rankingInfo = loadActivityScoreRankingInfo(rankId)
        if rankingInfo.itemCount > 0:
            for info in rankingInfo.items:
                hisIssue = info.issueNum
                userData = loadOrCreateUserData(userId, rankId, hisIssue)

                reward = None
                if userData.rewardStu == RewardState.ST_HAS_REWARD:
                    userData.rewardStu = RewardState.ST_GAIN_REWARD
                    reward = self.getRewardByRank(userData.rank, hisIssue)
                elif userData.dibaoStu == RewardState.ST_HAS_REWARD:
                    userData.dibaoStu = RewardState.ST_GAIN_REWARD
                    reward = self._dibaoReward

                if not reward:
                    ftlog.warn('activity_score_ranking gainUserReward',
                               'rankId=', rankId, 'userId=', userId,
                               'issueNum=', hisIssue,
                               'rank=', userData.rank, 'userData=',
                               userData.toDict(), 'reward is Null')
                    continue

                saveUserData(userData)

                contentItems = TYContentItem.decodeList(reward.get('items'))
                assetList = dizhu_util.sendRewardItems(
                    userId, contentItems, self._mail,
                    'DIZHU_ACTIVITY_SCORE_RANKLIST_REWARD', self.intActId)

                ftlog.info('activity_score_ranking gainUserReward', 'userId=',
                           userId, 'rankId=', rankId, 'rewards=',
                           [(atp[0].kindId, atp[1]) for atp in assetList])

                rewardList.append(reward)

        return rewardList
コード例 #21
0
    def decodeFromDict(self, d):
        self.score = d.get('score')
        if not isinstance(self.score, int):
            raise TYBizConfException(d, 'ScoreDiBaoConf.score must be int')

        self.playCount = d.get('playCount')
        if not isinstance(self.playCount, int):
            raise TYBizConfException(d, 'ScoreDiBaoConf.playCount must be int')

        self.rewardMail = d.get('rewardMail', '')
        if not isstring(self.rewardMail):
            raise TYBizConfException(
                d, 'ScoreDiBaoConf.rewardMail must be string')

        self.desc = d.get('desc', '')
        if not isstring(self.desc):
            raise TYBizConfException(d, 'ScoreDiBaoConf.desc must be string')

        self.img = d.get('img', '')
        if not isstring(self.img):
            raise TYBizConfException(d, 'ScoreDiBaoConf.img must be string')

        self.rewardItems = TYContentItem.decodeList(d.get('items', []))
        return self
コード例 #22
0
ファイル: reward_async.py プロジェクト: luningcowboy/tuyoo
    def buildGetRewardResponse(cls, userId, rewardId):
        ''' 返回客户端消息 mo '''
        ret = cls.getRewardByRewardId(userId, rewardId)
        if ret:
            rewards = ret['rewards']
            rewardType = ret['type']
            # 给用户发奖
            contentItems = TYContentItem.decodeList(rewards)
            if rewardType == REWARD_ASYNC_TYPE_AS_ARENA_MATCH:
                matchId = ret.get('params', {}).get('matchId', 0)
                mixId = ret.get('params', {}).get('mixId', 0)
                rank = ret.get('params', {}).get('rank', 0)
                sequence = ret.get('params', {}).get('sequence', 0)
                roomName = ret.get('params', {}).get('roomName', '红包赛')

                mail = '红包赛奖励#恭喜您在%s' % roomName + '中, 获得${rewardContent}。'
                dizhu_util.sendRewardItems(
                    userId, contentItems, mail, 'MATCH_REWARD',
                    ret.get('params', {}).get('matchId', 0))
                for reward in rewards:
                    chipType = matchutil.getBiChipType(reward['itemId'])
                    kindId = 0
                    if chipType == daoconst.CHIP_TYPE_ITEM:
                        kindId = reward['itemId'].strip('item:')
                    matchutil.report_bi_game_event(
                        'MATCH_REWARD', userId, matchId, 0, sequence, 0, 0, 0,
                        [
                            chipType, reward['count'], kindId, rank, mixId,
                            len(rewards)
                        ], 'match_reward')
            elif rewardType == REWARD_ASYNC_TYPE_AS_WINSTREAK:
                winStreak = ret.get('params', {}).get('winStreak', 0)
                dizhu_util.sendRewardItems(userId, contentItems, None,
                                           'DIZHU_SEGMENT_MATCH_WINSTREAK',
                                           winStreak)

            # 如果是奖券则广播奖券事件
            for reward in rewards:
                if reward['itemId'] == 'user:coupon':
                    if rewardType == REWARD_ASYNC_TYPE_AS_ARENA_MATCH:
                        from hall.game import TGHall
                        TGHall.getEventBus().publishEvent(
                            UserCouponReceiveEvent(
                                HALL_GAMEID, userId, reward['count'],
                                user_coupon_details.
                                USER_COUPON_SOURCE_MATCH_ARENA))

                    elif rewardType == REWARD_ASYNC_TYPE_AS_WINSTREAK:
                        from hall.game import TGHall
                        TGHall.getEventBus().publishEvent(
                            UserCouponReceiveEvent(
                                HALL_GAMEID, userId, reward['count'],
                                user_coupon_details.
                                USER_COUPON_SOURCE_SEGMENT_WINSTREAK_TASK))
        mo = MsgPack()
        mo.setCmd('dizhu')
        mo.setResult('action', 'get_reward_async')
        mo.setResult('gameId', DIZHU_GAMEID)
        mo.setResult('userId', userId)
        mo.setResult('rewardInfo', ret)
        return mo
コード例 #23
0
ファイル: match.py プロジェクト: luningcowboy/tuyoo
    def doWinLose(cls, room, table, seatId, isTimeOutKill=False): # TODO:
        if not table._match_table_info:
            ftlog.warn('GroupMatch.doWinLoseTable roomId=', room.roomId,
                       'tableId=', table.tableId,
                       'seatId=', seatId,
                       'isTimeOutKill=', isTimeOutKill,
                       'err=', 'not matchTableInfo')
            return

        if ftlog.is_debug():
            ftlog.debug('GroupMatch.doWinLose roomId=', room.roomId,
                        'tableId=', table.tableId,
                        'seatId=', seatId,
                        'isTimeOutKill=', isTimeOutKill,
                        'stageReward=', table.group.stageConf.conf.get('stageReward'))
        
        # 计算春天
        dizhuseatId = table.status.diZhu
        if seatId != dizhuseatId: 
            if table.seats[dizhuseatId - 1].outCardCount == 1:
                table.status.chuntian = 2
        else:
            s1 = table.seats[(dizhuseatId - 1 + 1) % table.maxSeatN]
            s2 = table.seats[(dizhuseatId - 1 + 2) % table.maxSeatN]
            if s1.outCardCount == 0 and s2.outCardCount == 0:
                table.status.chuntian = 2
                 
        # 翻倍计算 叫地主的倍数
        windoubles = table.status.callGrade
        # 炸弹倍数
        windoubles *= pow(2, table.status.bomb)
        # 春天倍数
        windoubles *= table.status.chuntian
        # 底牌倍数
        windoubles *= table.status.baseCardMulti
        # 明牌倍数
        windoubles *= table.status.show
         
        dizhuwin = 0
        if seatId == dizhuseatId:
            dizhuwin = 1
        if seatId == 0 : # 流局
            dizhuwin = 0
            windoubles = 1
        else:
            windoubles = abs(windoubles)
 
        userids = []
        detalChips = []
        seat_coin = []
        baseBetChip = table._match_table_info['mInfos']['basescore']
        robot_card_count = [0] * len(table.seats)  # 每个座位
        for x in xrange(len(table.seats)):
            uid = table.seats[x].userId
            userids.append(uid)
            if seatId == 0 : # 流局
                detalChip = -baseBetChip
            else:
                if dizhuwin :
                    if x + 1 == dizhuseatId :
                        detalChip = baseBetChip + baseBetChip
                    else:
                        detalChip = -baseBetChip
                else:
                    if x + 1 == dizhuseatId :
                        detalChip = -baseBetChip - baseBetChip
                    else:
                        detalChip = baseBetChip
            detalChip *= windoubles
            detalChips.append(detalChip)
            seat_coin.append(table._match_table_info['mInfos']['scores'][x] + detalChip)
            robot_card_count[x] = table.seats[x].robotCardCount
            ftlog.info('dizhu.game_win userId=', uid, 'roomId=', room.roomId, 'tableId=', table.tableId, 'delta=', detalChip)
        
        punish.Punish.doWinLosePunish(table.runConfig.punishCardCount, table.runConfig.isMatch,
                                      seat_coin, detalChips, robot_card_count)
        for x in xrange(len(table.seats)):
            uid = table.seats[x].userId
            table._match_table_info['mInfos']['scores'][x] = seat_coin[x]

        # 返回当前Table的game_win
        moWin = MsgPack()
        moWin.setCmd('table_call')
        moWin.setResult('action', 'game_win')
        moWin.setResult('isMatch', 1)
        moWin.setResult('gameId', table.gameId)
        moWin.setResult('roomId', table.roomId)
        moWin.setResult('tableId', table.tableId)
#         moWin.setResult('stat', dict(zip(tdz_stat_title, table.status)))
        moWin.setResult('stat', table.status.toInfoDictExt())
        moWin.setResult('dizhuwin', dizhuwin)
        if seatId == 0:
            moWin.setResult('nowin', 1)
        moWin.setResult('slam', 0)
        moWin.setResult('cards', [seat.cards for seat in table.seats])
        
        roundId = table.gameRound.number
        table.clear(userids)
         
        for x in xrange(len(userids)):
            uid = userids[x]
            mrank = 3
            mtableRanking = 3
            moWin.setResult('seat' + str(x + 1), [detalChips[x], seat_coin[x], 0, 0, 0, 0, mrank, mtableRanking])

            if detalChips[x] > 0:
                stageRewards = table.group.stageConf.conf.get('stageReward', None) if table.group.stageConf else None
                if stageRewards:
                    contentItems = TYContentItem.decodeList(stageRewards)
                    assetList = dizhu_util.sendRewardItems(uid, contentItems, '', 'DIZHU_STAGE_REWARD', 0)
                    moWin.setResult('stageReward', stageRewards)
                    ftlog.info('stageRewards send. userId=', uid, 'stageRewards=', stageRewards, 'assetList=', assetList)

            #增加经验
            exp = userdata.incrExp(uid, 20)
            explevel = dizhuaccount.getExpLevel(exp)
            gamedata.setGameAttr(uid, table.gameId, 'level', explevel)
            if ftlog.is_debug():
                ftlog.debug('BigMatch.doWinLoseTable',
                            'addExp=', 20,
                            'curExp=', exp,
                            'curLevel=', explevel)
             
        table.gamePlay.sender.sendToAllTableUser(moWin)
         
        # 发送给match manager
        users = []
        for x in xrange(len(userids)):
            user = {}
            user['userId'] = userids[x]
            user['deltaScore'] = int(detalChips[x])
            user['seatId'] = x + 1
            users.append(user)
         
        mnr_msg = MsgPack()
        mnr_msg.setCmd('room')
        mnr_msg.setParam('action', 'm_winlose')
        mnr_msg.setParam('gameId', table.gameId)
        mnr_msg.setParam('matchId', table.room.bigmatchId)
        mnr_msg.setParam('roomId', table.room.ctrlRoomId)
        mnr_msg.setParam('tableId', table.tableId)
        mnr_msg.setParam('users', users)
        mnr_msg.setParam('ccrc', table._match_table_info['ccrc'])
        
        if cls.WINLOSE_SLEEP > 0:
            FTTasklet.getCurrentFTTasklet().sleepNb(cls.WINLOSE_SLEEP)
        # 记录游戏winlose
        try:
            for u in users:
                table.room.reportBiGameEvent('TABLE_WIN', u['userId'], table.roomId,
                                             table.tableId, roundId, u['deltaScore'],
                                             0, 0, [], 'table_win')
        except:
            if ftlog.is_debug():
                ftlog.exception()
        router.sendRoomServer(mnr_msg, table.room.ctrlRoomId)
コード例 #24
0
    def _sendStageReward(self, result):
        # 各个阶段发阶段奖励
        rewardList = []
        stageRewards = self.room.roomConf['matchConf'].get('stageRewards', {})
        for sst in result.seatStatements:
            userId = sst.seat.userId

            stageindex = self.table.matchTableInfo.get('step', {}).get(
                'stageIndex', 0) + 1
            stageReward = stageRewards.get(str(self.table.room.bigmatchId),
                                           {}).get(str(stageindex), [])

            currStageReward = []
            try:
                sstIsDizhu = 'dizhu' if sst.isDizhu else 'nongmin'
                for rewardIndex in range(len(stageReward)):
                    currStageReward.append({
                        "count":
                        stageReward[rewardIndex].get('count',
                                                     {}).get(sstIsDizhu, 0),
                        "itemId":
                        stageReward[rewardIndex]['itemId']
                    })
            except Exception, e:
                ftlog.warn('group.stageRewards.info userId=', userId, 'err=',
                           e)

            deltaScore = sst.delta if not sst.seat.isGiveup else -9999999
            clientVer = SessionDizhuVersion.getVersionNumber(userId)

            if ftlog.is_debug():
                ftlog.debug('group.stageRewards.info userId=', userId,
                            'index=', stageindex, 'score=', deltaScore, 'ver=',
                            clientVer, 'reward=', currStageReward,
                            'stageRewardTotal=',
                            sst.seat.player.stageRewardTotal)

            if not currStageReward or deltaScore < 0 or clientVer < 3.90:
                rewardList.append(None)
                continue

            contentItems = TYContentItem.decodeList(currStageReward)
            assetList = dizhu_util.sendRewardItems(userId, contentItems, '',
                                                   'DIZHU_STAGE_REWARD', 0)
            clientAssetList = []
            for atp in assetList:
                clientAsset = {
                    "name": atp[0].displayName,
                    "itemId": atp[0].kindId,
                    "count": atp[1]
                }
                clientAssetList.append(clientAsset)
                sst.seat.player.stageRewardTotal += atp[1]
            rewardList.append(clientAssetList)

            ftlog.info('group.stageRewards.info userId=', userId,
                       'deltaScore=', deltaScore, 'stageRewardTotal=',
                       sst.seat.player.stageRewardTotal, 'index=', stageindex,
                       'assetList=', [(atp[0].kindId, atp[1])
                                      for atp in assetList], 'seatId=',
                       sst.seat.seatId)