コード例 #1
0
ファイル: hallactivitygetgift.py プロジェクト: zhaozw/hall37
def get_gift_for_user(conf, gifttype, userId, gameId, clientId):
    ftlog.debug("get_gift_for_user begin:")
    design = conf.get('design', {})
    if gifttype in design:
        ftlog.debug("get_gift_for_user begin:1")
        from hall.entity.hallitem import itemSystem
        userAssets = itemSystem.loadUserAssets(userId)
        changed = []
        if design[gifttype]["type"] == "user:coupon":
            x = random.uniform(1, design[gifttype]["limits"])
            coinAdd = int(design[gifttype]["count"] * x)
            asset = userAssets.addAsset(gameId, design[gifttype]["type"], coinAdd, int(time.time()), 'HALL_FLIPCARD', 0)
            changed.append(asset)
            changeNames = TYAssetUtils.getChangeDataNames(changed)
            datachangenotify.sendDataChangeNotify(gameId, userId, changeNames)
            result = "恭喜你获得了%d" % coinAdd + "奖劵"
            return result
        elif design[gifttype]["type"] == "item:1007":
            x = random.uniform(1, design[gifttype]["limits"])
            coinAdd = int(design[gifttype]["count"] * x)
            asset = userAssets.addAsset(gameId, design[gifttype]["type"], coinAdd, int(time.time()), 'HALL_FLIPCARD', 0)
            changed.append(asset)
            changeNames = TYAssetUtils.getChangeDataNames(changed)
            datachangenotify.sendDataChangeNotify(gameId, userId, changeNames)
            result = "恭喜你获得了%d" % coinAdd + "张参赛劵"
            return result
        if design[gifttype]["type"] == "item:4118":
            x = random.uniform(1, design[gifttype]["limits"])
            coinAdd = int(design[gifttype]["count"] * x)
            asset = userAssets.addAsset(gameId, design[gifttype]["type"], coinAdd, int(time.time()), 'HALL_FLIPCARD', 0)
            changed.append(asset)
            changeNames = TYAssetUtils.getChangeDataNames(changed)
            datachangenotify.sendDataChangeNotify(gameId, userId, changeNames)
            result = "恭喜你获得了%d" % coinAdd + "天左轮手枪"
            return result
        elif design[gifttype]["type"] == "item:2003":
            x = random.uniform(1, design[gifttype]["limits"])
            coinAdd = int(design[gifttype]["count"] * x)
            asset = userAssets.addAsset(gameId, design[gifttype]["type"], coinAdd, int(time.time()), 'HALL_FLIPCARD', 0)
            changed.append(asset)
            changeNames = TYAssetUtils.getChangeDataNames(changed)
            datachangenotify.sendDataChangeNotify(gameId, userId, changeNames)
            result = "恭喜你获得了%d" % coinAdd + "天记牌器"
            return result
        elif design[gifttype]["type"] == "coin":
            ftlog.debug("get_gift_for_user begin:2")
            x = random.uniform(1, design[gifttype]["limits"])
            coinAdd = int(design[gifttype]["count"] * x)
            userchip.incrChip(userId, gameId, coinAdd, daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO, 'HALL_FLIPCARD', 0,
                              clientId)
            datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
            result = "恭喜你获得了%d" % coinAdd + "金币"
            return result
        else:
            result = "红包被领完了..."
            return result
    else:
        result = "红包领完了,我很抱歉"
        return result
コード例 #2
0
ファイル: vip_handler.py プロジェクト: zhaozw/hall37
    def _doNewVipGift(cls, gameId, userId, level):
        try:
            userVip, _giftStates, gotVipGiftResult = hallvip.userVipSystem.gainUserVipGift(gameId, userId, level)
            ftlog.debug('VipTcpHandler._doNewVipGift userId=', userId,
                        'gameId=', gameId,
                        'giftVipLevel=', gotVipGiftResult.vipGiftState.vipLevel.level)
            giftInfo = VipHelper.buildGiftInfo(userVip, gotVipGiftResult.vipGiftState)
            getGiftTodoTask = TodoTaskVipGotGift(gotVipGiftResult.vipGiftState.vipLevel.level,
                                                 gotVipGiftResult.vipGiftState.vipLevel.vipExp,
                                                 gotVipGiftResult.vipGiftState.vipLevel.name,
                                                 gotVipGiftResult.vipGiftState.vipLevel.desc,
                                                 giftInfo)

            todotasks = [getGiftTodoTask]
            needGoldRain = TYAssetUtils.getAssetCount(gotVipGiftResult.giftItemList, hallitem.ASSET_CHIP_KIND_ID) > 0
            if needGoldRain:
                todotasks.append(TodoTaskGoldRain(VipHelper.buildGotGiftDesc(gotVipGiftResult)))
            else:
                todotasks.append(TodoTaskPopTip(VipHelper.buildGotGiftDesc(gotVipGiftResult)))

            mo = TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
            # 通知客户端变化
            if gotVipGiftResult.giftItemList:
                datachangenotify.sendDataChangeNotify(gameId, userId,
                                                      TYAssetUtils.getChangeDataNames(gotVipGiftResult.giftItemList))
            return mo
        except TYBizException, e:
            return cls.sendErrorResponse(userId, 'newvip', e.errorCode, e.message)
コード例 #3
0
ファイル: skillscore.py プロジェクト: luningcowboy/tuyoo
 def sendLevelReward(self, userId, oldLevel, newLevel):
     if not newLevel.rewardContent:
         return None
     items = newLevel.rewardContent.getItems()
     ftlog.info('GameSkillScore.sendLevelReward', 'userId=', userId,
                'oldLevel=', oldLevel.level, 'new_level=', newLevel.level,
                'items=', [(ci.assetKindId, ci.count) for ci in items])
     ua = hallitem.itemSystem.loadUserAssets(userId)
     aslist = ua.sendContentItemList(self.gameId, items, 1, True,
                                     pktimestamp.getCurrentTimestamp(),
                                     'TASK_MASTER_SCORE_UP_LEVEL_REWARD',
                                     newLevel.level)
     items = []
     for x in aslist:
         kindId = hallconf.translateAssetKindIdToOld(x[0].kindId)
         akind = hallitem.itemSystem.findAssetKind(x[0].kindId)
         items.append({
             'id': kindId,
             'count': x[1],
             'name': akind.displayName,
             'pic': akind.pic,
         })
     datachangenotify.sendDataChangeNotify(
         self.gameId, userId, TYAssetUtils.getChangeDataNames(aslist))
     return items
コード例 #4
0
ファイル: dizhu_util.py プロジェクト: luningcowboy/tuyoo
def sendReward(userId, rewardConf, mailstr, eventId, eventParam):
    """
    通用发货
    param: rewardConf 奖励配置
    格式:
    {
        'typeId': 'FixedContent',
        'items': [{'itemId': 'user:chip', 'count': 100}]
    }
    param: mailstr 邮件内容文本字符串,其中包含子串\\${rewardContent}
    eventId: 哪个事件触发的
    eventParam: 事件参数 
    return: list<(TYAssetKind, consumeCount, final)>
    """
    rewardContent = TYContentRegister.decodeFromDict(rewardConf)
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    assetList = userAssets.sendContent(DIZHU_GAMEID, rewardContent, 1, True,
                                       pktimestamp.getCurrentTimestamp(),
                                       eventId, eventParam)
    changeNames = TYAssetUtils.getChangeDataNames(assetList)
    contents = TYAssetUtils.buildContentsString(assetList)
    if mailstr:
        mailstr = strutil.replaceParams(mailstr, {'rewardContent': contents})
        message.send(DIZHU_GAMEID, message.MESSAGE_TYPE_SYSTEM, userId,
                     mailstr)
        changeNames.add('message')
    datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, changeNames)
    return assetList
コード例 #5
0
ファイル: hallroulette.py プロジェクト: zhaozw/hall37
def sendGiftsToUser(userId, gameId, clientId, items):
    '''
        多个奖品时的发奖,或者一个奖品的发奖,items为数组
    '''
    contentItemList = []
    rouletteMap = getRouletteMap()

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

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

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    results = userAssets.sendContentItemList(gameId, contentItemList, 1, True,
                                             int(time.time()), 'ROULETTE_GOLD',
                                             0)
    datachangenotify.sendDataChangeNotify(
        gameId, userId, TYAssetUtils.getChangeDataNames(results))
コード例 #6
0
def getAllReward(status):
    from hall.entity import hallitem
    count = 0
    for invitation in status.inviteeMap.values():
        if invitation.state == Invitation.STATE_ACCEPT:
            invitation.state = Invitation.STATE_REWARD
            count += 1
    assetTupleList = []
    if count > 0:
        _saveStatus(status)

        timestamp = pktimestamp.getCurrentTimestamp()
        if _conf.prizeRewardItem:
            ftlog.info('neituiguang.getAllReward userId=', status.userId,
                       'assetKindId=', _conf.prizeRewardItem.assetKindId,
                       'assetCount=', _conf.prizeRewardItem.count,
                       'invitationCount=', count)
            assetTuple = hallitem.itemSystem.loadUserAssets(
                status.userId).addAsset(HALL_GAMEID,
                                        _conf.prizeRewardItem.assetKindId,
                                        _conf.prizeRewardItem.count, timestamp,
                                        'PROMOTE_REWARD', 0)
            assetTupleList.append(assetTuple)
            datachangenotify.sendDataChangeNotify(
                HALL_GAMEID, status.userId,
                TYAssetUtils.getChangeDataNames(assetTupleList))
    return count, assetTupleList
コード例 #7
0
ファイル: hallvip.py プロジェクト: zhaozw/hall37
    def gainUserVipGift(self, gameId, userId, level):
        '''
        领取level级别vip的礼品
        @param userId: 要领取礼品的用户ID
        @param level: 要领取的礼品的vip级别
        @return: userVip, list<TYVipGiftState>, TYUserVipGotGiftResult
        '''
        userVip = self.getUserVip(userId)
        if level > userVip.vipLevel.level:
            raise TYVipLevelNotGotException(level, userVip.vipLevel.level)

        vipLevel = self._vipSystem.findVipLevelByLevel(level)
        if not vipLevel:
            raise TYVipLevelNotFoundException(level)

        if not vipLevel.giftContent:
            raise TYVipLevelNoGiftException(level)

        vipGiftStatus = self._loadUserVipGiftStatus(userId)
        giftState = vipGiftStatus.getGiftStateByLevel(level)
        if giftState and giftState.state == TYVipGiftState.STATE_GOT:
            raise TYVipLevelGiftAlreadyGotException(level)

        giftState = TYVipGiftState(vipLevel, TYVipGiftState.STATE_GOT)
        vipGiftStatus.setGiftState(giftState.level, giftState)
        self._saveVipGiftStates(userId, vipGiftStatus)

        # 发奖
        assetList = self._sendGiftContent(gameId, userVip, vipLevel)
        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
        gotGiftResult = TYUserVipGotGiftResult(userVip, giftState, assetList)
        TGHall.getEventBus().publishEvent(TYUserVipGotGiftEvent(gameId, userId, gotGiftResult))
        return userVip, self._fillAndToList(userVip, vipGiftStatus), gotGiftResult
コード例 #8
0
    def _exchange(self, gameid, userid, actkey, exchangeid):
        info = self._exchanges.get(exchangeid)
        if not info:
            return {'result': 'fail', 'tip': "unknown productId"}

        buynum = self.get_exchange_buynum(userid, actkey, info)
        if buynum >= info['limitTimes']:
            return {'result': 'fail', 'tip': '兑换次数已满'}

        if not self.alter_user_credit(userid, actkey, -info['price']):
            return {'result': 'fail', 'tip': '您的积分不足'}
        daobase.executeUserCmd(userid, 'HINCRBY', actkey, self.FIELD_EXCHANGE_NUM.format(exchangeid), 1)

        userAssets = hallitem.itemSystem.loadUserAssets(userid)
        assetList = userAssets.sendContent(gameid, info['content'], 1, True,
                                           timestamp.getCurrentTimestamp(), "ACTIVITY_CREDIT_EXCHANGE", exchangeid)
        response = self._query(userid, actkey)
        ftlog.debug('TYActCreditExchange._exchange gameId=', gameid,
                    'userId=', userid,
                    'activityId=', self.getid(),
                    'reward=', TYAssetUtils.buildContents(assetList),
                    'buynum=', buynum + 1,
                    'credit=', response['credit'])
        changeNames = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(gameid, userid, changeNames)
        response['result'] = 'ok'
        response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(assetList)
        return response
コード例 #9
0
    def _sendRewards(self, status, task, timestamp):
        from hall.game import TGHall

        userAssets = hallitem.itemSystem.loadUserAssets(status.userId)
        assetList = userAssets.sendContent(self.gameId,
                                           task.taskKind.rewardContent, 1,
                                           True, timestamp,
                                           'HALL_RP_TASK_REWARD', task.kindId)
        ftlog.info('RPTaskSystem._sendRewards', 'gameId=', self.gameId,
                   'userId=', status.userId, 'kindId=', task.kindId, 'assets=',
                   [(atup[0].kindId, atup[1]) for atup in assetList])
        changed = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(self.gameId, status.userId,
                                              changed)

        if task.taskKind.rewardMail:
            contents = TYAssetUtils.buildContentsString(assetList)
            mail = strutil.replaceParams(task.taskKind.rewardMail,
                                         {'rewardContent': contents})
            pkmessage.sendPrivate(HALL_GAMEID, status.userId, 0, mail)

        TGHall.getEventBus().publishEvent(
            UserRedPacketTaskRewardEvent(status.userId, HALL_GAMEID,
                                         task.taskKind, assetList))

        couponCount = TYAssetUtils.getAssetCount(assetList,
                                                 hallitem.ASSET_COUPON_KIND_ID)
        if couponCount > 0:
            TGHall.getEventBus().publishEvent(
                UserReceivedCouponEvent(
                    HALL_GAMEID, status.userId, couponCount,
                    hall_red_packet_const.RP_SOURCE_RP_TASK))
コード例 #10
0
ファイル: toolbox.py プロジェクト: luningcowboy/tuyoo
    def sendAssetsListToUser(cls,
                             gameId,
                             userId,
                             assetList,
                             eventId,
                             mail=None,
                             intEventParam=0):
        '''
        :param gameId 统计用途,地主就写6
        :param assetList 要发送的资产, 格式必须是:[{itemId:'item:0011', count:1}, ...]
        :param eventId 事件ID,要在config/poker/map.bieventid.json中注册
        :param mail(optional) 给用户邮箱发送信息,默认不发送
        '''
        timestamp = pktimestamp.getCurrentTimestamp()
        itemList = []
        for i in xrange(0, len(assetList)):
            itemList.insert(i, TYContentItem.decodeFromDict(assetList[i]))
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContentItemList(gameId, itemList, 1, True,
                                                   timestamp, eventId,
                                                   intEventParam)

        # 通知用户道具和消息存在改变
        if assetList:
            datachangenotify.sendDataChangeNotify(
                gameId, userId, TYAssetUtils.getChangeDataNames(assetList))

        # 发送邮箱信息
        if mail and len(mail) > 0:
            pkmessage.sendPrivate(9999, userId, 0, mail)
コード例 #11
0
def _onOrderDelivery(event):
    if event.orderDeliveryResult.assetItems:
        changedNames = TYAssetUtils.getChangeDataNames(event.orderDeliveryResult.assetItems)
        datachangenotify.sendDataChangeNotify(event.gameId, event.userId, changedNames)
        ftlog.info('hallstore._onOrderDelivery gameId=', event.gameId,
                   'userId=', event.userId,
                   'orderDeliveryResult=', event.orderDeliveryResult)
コード例 #12
0
    def _exchange(self, gameid, userid, actkey, exchangeid):
        info = self._exchanges.get(exchangeid)
        if not info:
            return {'result': 'fail', 'tip': "unknown productId"}

        buynum = self.get_exchange_buynum(userid, actkey, info)
        if buynum >= info['limitTimes']:
            return {'result': 'fail', 'tip': '兑换次数已满'}

        if not self.alter_user_credit(userid, actkey, -info['price']):
            return {'result': 'fail', 'tip': '您的积分不足'}
        daobase.executeUserCmd(userid, 'HINCRBY', actkey,
                               self.FIELD_EXCHANGE_NUM.format(exchangeid), 1)

        userAssets = hallitem.itemSystem.loadUserAssets(userid)
        assetList = userAssets.sendContent(gameid, info['content'], 1, True,
                                           timestamp.getCurrentTimestamp(),
                                           "ACTIVITY_CREDIT_EXCHANGE",
                                           exchangeid)
        response = self._query(userid, actkey)
        ftlog.debug('TYActCreditExchange._exchange gameId=', gameid, 'userId=',
                    userid, 'activityId=', self.getid(), 'reward=',
                    TYAssetUtils.buildContents(assetList), 'buynum=',
                    buynum + 1, 'credit=', response['credit'])
        changeNames = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(gameid, userid, changeNames)
        response['result'] = 'ok'
        response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(
            assetList)
        return response
コード例 #13
0
 def do_message_receive(self, userId, gameId, clientId, typeid, msgid):
     ret = message.attachment_receive(userId, typeid, msgid,
                                      hallitem.itemSystem)
     if ret:
         changed = TYAssetUtils.getChangeDataNames(ret[1])
         changed.add('message')
         datachangenotify.sendDataChangeNotify(ret[0], userId, changed)
コード例 #14
0
ファイル: neituiguang.py プロジェクト: zhaozw/hall37
def getAllReward(status):
    from hall.entity import hallitem
    count = 0
    for invitation in status.inviteeMap.values():
        if invitation.state == Invitation.STATE_ACCEPT:
            invitation.state = Invitation.STATE_REWARD
            count += 1
    assetTupleList = []
    if count > 0:
        _saveStatus(status)

        timestamp = pktimestamp.getCurrentTimestamp()
        if _conf.prizeRewardItem:
            ftlog.info('neituiguang.getAllReward userId=', status.userId,
                       'assetKindId=', _conf.prizeRewardItem.assetKindId,
                       'assetCount=', _conf.prizeRewardItem.count,
                       'invitationCount=', count)
            assetTuple = hallitem.itemSystem.loadUserAssets(status.userId).addAsset(HALL_GAMEID,
                                                                                    _conf.prizeRewardItem.assetKindId,
                                                                                    _conf.prizeRewardItem.count,
                                                                                    timestamp, 'PROMOTE_REWARD', 0)
            assetTupleList.append(assetTuple)
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, status.userId,
                                                  TYAssetUtils.getChangeDataNames(assetTupleList))
    return count, assetTupleList
コード例 #15
0
    def _exchange(self, gameid, userid, actkey, exchangeid):
        info = self._exchanges.get(exchangeid)
        if not info:
            return {'result': 'fail', 'tip': "unknown productId"}

        buynum = self.get_exchange_buynum(userid, actkey, info)
        if buynum >= info['limitTimes']:
            return {'result': 'fail', 'tip': '兑换次数已满'}

        curtime = timestamp.getCurrentTimestamp()
        userAssets = hallitem.itemSystem.loadUserAssets(userid)
        try:
            userAssets.consumeContentItemList(gameid, info['costs'], False, curtime,
                                              "ACT_ITEM_EXCHANGE_COST", exchangeid)
        except:
            return {'result': 'fail', 'tip': '您的道具不足,快去获取道具吧'}

        daobase.executeUserCmd(userid, 'HINCRBY', actkey, self.FIELD_EXCHANGE_NUM.format(exchangeid), 1)
        assetList = userAssets.sendContent(gameid, info['content'], 1, True,
                                           timestamp.getCurrentTimestamp(), "ACT_ITEM_EXCHANGE_GAIN", exchangeid)
        response = self._query(userid, actkey)
        ftlog.info('TYActItemExchange._exchange gameId=', gameid,
                   'userId=', userid,
                   'activityId=', self.getid(),
                   'reward=', TYAssetUtils.buildContents(assetList),
                   'buynum=', buynum + 1,
                   'credit=', response['credit'])
        changeNames = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(gameid, userid, changeNames)
        response['result'] = 'ok'
        response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(assetList)
        return response
コード例 #16
0
ファイル: hall_share3.py プロジェクト: luningcowboy/tuyoo
def sendReward(gameId, userId, sharePoint):
    from hall.entity import hallitem
    if not sharePoint.reward or not sharePoint.reward.content:
        return None

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    assetList = userAssets.sendContent(gameId, sharePoint.reward.content, 1, True,
                                       pktimestamp.getCurrentTimestamp(),
                                       'SHARE3_REWARD', sharePoint.pointId)
    ftlog.info('hall_share3.sendReward',
               'gameId=', gameId,
               'userId=', userId,
               'pointId=', sharePoint.pointId,
               'groupId=', sharePoint.groupId,
               'rewards=', [(atup[0].kindId, atup[1]) for atup in assetList])
    changedDataNames = TYAssetUtils.getChangeDataNames(assetList)
    datachangenotify.sendDataChangeNotify(gameId, userId, changedDataNames)
    for atup in assetList:
        if atup[0].kindId == 'user:coupon':
            # 广播事件
            from hall.game import TGHall
            TGHall.getEventBus().publishEvent(
                UserCouponReceiveEvent(HALL_GAMEID, userId, atup[1], user_coupon_details.USER_COUPON_SHARE3))

    return assetList
コード例 #17
0
    def sendRewards(self, userId, timestamp):
        if ftlog.is_debug():
            ftlog.debug('FTTableFinishRecorder.sendRewards', 'userId=', userId,
                        'rewardContent=', self.rewardContent)

        if not self.rewardContent:
            return

        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContent(DIZHU_GAMEID, self.rewardContent, 1,
                                           True, timestamp, 'ACTIVITY_REWARD',
                                           self.intActId)

        changed = None
        if assetList:
            changed = TYAssetUtils.getChangeDataNames(assetList)
        if self.mail:
            mail = strutil.replaceParams(
                self.mail,
                {'rewardContent': TYAssetUtils.buildContentsString(assetList)})
            pkmessage.sendPrivate(HALL_GAMEID, userId, 0, mail)
            if not changed:
                changed = set(['message'])
        if changed:
            datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId,
                                                  changed)

        ftlog.info('FTTableFinishRecorder.sendRewards', 'userId=', userId,
                   'rewards=', [(at[0].kindId, at[1]) for at in assetList])
コード例 #18
0
ファイル: skillscore.py プロジェクト: luningcowboy/tuyoo
def get_skill_level_reward(userId, old_level, new_level):
    rewards = dizhuconf.getSkillScoreReward().get(str(new_level),
                                                  {}).get('rewards', None)
    if not rewards:
        return None
    ftlog.debug('get_skill_level_reward->', userId, old_level, new_level,
                rewards)
    sitems = TYContentRegister.decodeFromDict(rewards).getItems()
    ua = hallitem.itemSystem.loadUserAssets(userId)
    aslist = ua.sendContentItemList(DIZHU_GAMEID, sitems, 1, True,
                                    timestamp.getCurrentTimestamp(),
                                    'TASK_MASTER_SCORE_UP_LEVEL_REWARD', 0)
    items = []
    for x in aslist:
        kindId = hallconf.translateAssetKindIdToOld(x[0].kindId)
        akind = hallitem.itemSystem.findAssetKind(x[0].kindId)
        items.append({
            'id': kindId,
            'count': x[1],
            'name': akind.displayName,
            'pic': akind.pic,
        })
    datachangenotify.sendDataChangeNotify(
        HALL_GAMEID, userId, TYAssetUtils.getChangeDataNames(aslist))
    return items
コード例 #19
0
def sendReward(userId, clientId, timestamp):
    from hall.game import TGHall
    
    for cond, rewardContent in _conf.rewards:
        if cond and not cond.check(HALL_GAMEID, userId, clientId, timestamp):
            continue
        
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContent(HALL_GAMEID,
                                           rewardContent,
                                           1,
                                           True,
                                           timestamp,
                                           'HALL_RP_REWARD',
                                           0)
        ftlog.info('hall_red_packet_main.sendReward',
                   'userId=', userId,
                   'assets=', [(atup[0].kindId, atup[1]) for atup in assetList])
        changed = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, changed)
        count = TYAssetUtils.getAssetCount(assetList, hallitem.ASSET_COUPON_KIND_ID)
        if count > 0:
            TGHall.getEventBus().publishEvent(UserReceivedCouponEvent(HALL_GAMEID,
                                                                      userId,
                                                                      count,
                                                                      hall_red_packet_const.RP_SOURCE_RP_MAIN))
        return assetList
    return None
コード例 #20
0
ファイル: util_user.py プロジェクト: huazhengyang/tuyoo
def consumeAssetNotify(gameId, userId, assetKindId, count, eventId,
                       intEventParam):
    '''
    减少用户资产并通知
    一般一次减少一种时用此接口,一次减少多种时用consumeAssets
    :param gameId:         
    :param userId:         
    :param assetKindId:    资产种类id,形如  user:chip   item:6001  等,详见 findAssetKind 方法
    :param count:          资产数量
    :param eventId:        哪个事件触发的,配置见 poker/map.bieventid.json
    :param intEventParam:  eventId相关的参数
    '''
    try:
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assertKind, consumeCount, final = userAssets.consumeAsset(
            gameId, assetKindId, count, pktimestamp.getCurrentTimestamp(),
            eventId, intEventParam)
        changeNames = TYAssetUtils.getChangeDataNames([(assertKind,
                                                        consumeCount, final)])
        datachangenotify.sendDataChangeNotify(gameId, userId, changeNames)
        return consumeCount, final
    except:
        ftlog.error('user_remote.consumeAsset gameId=', gameId, 'userId=',
                    userId, 'assetKindId=', assetKindId, 'count=', count,
                    'eventId=', eventId, 'intEventParam=', intEventParam)
        return 0, 0
コード例 #21
0
def signoutMatch(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug("match_remote.signoutMatch gameId=", gameId, "userId=",
                    userId, "contentItem=", contentItem, "bigRoomId=",
                    bigRoomId, "instId=", instId, "ctrlRoomId=", ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if not userMatchInfo:
        return 0, None

    if userMatchInfo.instId != instId:
        ftlog.debug("match_remote.signoutMatch diffInstId gameId=", gameId,
                    "userId=", userId, "contentItem=", contentItem,
                    "bigRoomId=", bigRoomId, "instId=", instId, "ctrlRoomId=",
                    ctrlRoomId, "recordInstId=", userMatchInfo.instId)
        return 0, None

    if userMatchInfo.state != UserMatchInfo.ST_SIGNIN:
        return ERR_ALREADY_IN_MATCH, None

    removeUserMatchInfo(userMatchInfo)
    daobase.executeTableCmd(ctrlRoomId, 0, "srem", "signs:" + str(ctrlRoomId),
                            userId)
    ftlog.debug("match_remote.signoutMatch gameId=", gameId, "userId=", userId,
                "contentItem=", contentItem, "bigRoomId=", bigRoomId,
                "instId=", instId, "ctrlRoomId=", ctrlRoomId)
    if userId > 10000 and contentItem:
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        item = TYContentItem.decodeFromDict(contentItem)
        assetList = userAssets.sendContentItemList(
            gameId, [item], 1, True, pktimestamp.getCurrentTimestamp(),
            "MATCH_RETURN_FEE", bigRoomId)
        datachangenotify.sendDataChangeNotify(
            gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
    return 0, None
コード例 #22
0
ファイル: util_user.py プロジェクト: huazhengyang/tuyoo
def addAssets(gameId, userId, contentItems, eventId, intEventParam):
    '''
    增加多种用户资产
    :param gameId:
    :param userId:
    :param contentItems:
    :param eventId:
    :param intEventParam:
    '''
    if ftlog.is_debug():
        ftlog.debug('addAssets gameId=', gameId, 'userId=', userId,
                    'contentItems=', contentItems, 'eventId=', eventId,
                    'intEventParam=', intEventParam)
    try:
        contentItems = _decodeContentItems(contentItems)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContentItemList(
            gameId, contentItems, 1, True, pktimestamp.getCurrentTimestamp(),
            eventId, intEventParam)
        datachangenotify.sendDataChangeNotify(
            gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
        return True
    except:
        ftlog.error()
        return False
コード例 #23
0
ファイル: duobao.py プロジェクト: luningcowboy/tuyoo
def add_content_item_list(uid, content):
    timestamp = pktimestamp.getCurrentTimestamp()
    userAssets = hallitem.itemSystem.loadUserAssets(uid)
    assetList = userAssets.sendContent(DIZHU_GAMEID, content, 1, True,
                                       timestamp, 'HALL_DUOBAO_COST', 0)
    ftlog.debug('duobao._send_rewards', 'userId=', uid, 'assets=',
                [(atup[0].kindId, atup[1]) for atup in assetList])
    changed = TYAssetUtils.getChangeDataNames(assetList)
    datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, uid, changed)
コード例 #24
0
ファイル: hall_login_reward.py プロジェクト: zhaozw/hall37
    def sendRewards(self, userId, gameId, clientId):
        bSend = True

        for cond in self.conditions:
            if not cond.check(gameId, userId, clientId,
                              pktimestamp.getCurrentTimestamp()):
                bSend = False

        if bSend:
            from hall.entity import hallitem
            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            assetList = userAssets.sendContent(
                gameId, self.items, 1, True, pktimestamp.getCurrentTimestamp(),
                'LOGIN_REWARD', 0)

            if assetList:
                if ftlog.is_debug():
                    ftlog.debug('hall_login_reward.sendReward gameId=', gameId,
                                'userId=', userId, 'rewards=',
                                [(atup[0].kindId, atup[1])
                                 for atup in assetList])
                # 记录登录奖励获取时间
                gamedata.setGameAttr(userId, HALL_GAMEID, 'login_reward',
                                     pktimestamp.getCurrentTimestamp())
                # 通知更新
                changedDataNames = TYAssetUtils.getChangeDataNames(assetList)
                datachangenotify.sendDataChangeNotify(gameId, userId,
                                                      changedDataNames)
                pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId,
                               self.mail)
                from poker.util import strutil
                _, cVer, _ = strutil.parseClientId(clientId)
                if cVer < 3.90:
                    TodoTaskHelper.sendTodoTask(
                        gameId, userId, TodoTaskShowInfo(self.mail, True))
                else:
                    rewardsList = []
                    for assetItemTuple in assetList:
                        '''
                        0 - assetItem
                        1 - count
                        2 - final
                        '''
                        assetItem = assetItemTuple[0]
                        reward = {}
                        reward['name'] = assetItem.displayName
                        reward['pic'] = assetItem.pic
                        reward['count'] = assetItemTuple[1]
                        rewardsList.append(reward)

                    if ftlog.is_debug():
                        ftlog.debug(
                            'hall_login_reward.TodoTaskShowRewards rewardsList: ',
                            rewardsList)

                    TodoTaskHelper.sendTodoTask(
                        gameId, userId, TodoTaskShowRewards(rewardsList))
コード例 #25
0
def sendGiftsToUser(userId, gameId, clientId, items):
    '''
        多个奖品时的发奖,或者一个奖品的发奖,items为数组
    '''
    contentItemList = []
    rouletteMap = getRouletteMap()

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

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

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

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

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    results = userAssets.sendContentItemList(gameId, contentItemList, 1, True,
                                             int(time.time()), 'ROULETTE_GOLD',
                                             0)
    datachangenotify.sendDataChangeNotify(
        gameId, userId, TYAssetUtils.getChangeDataNames(results))
コード例 #26
0
def deliveryContentForExchange(userAssets, exchangeItem, timestamp=None):
    timestamp = timestamp or pktimestamp.getCurrentTimestamp()
    assetList = userAssets.sendContent(HALL_GAMEID, exchangeItem.content, 1,
                                       True, timestamp,
                                       'HALL_RP_EXCHANGE_DELIVERY',
                                       exchangeItem.exchangeId)
    changed = TYAssetUtils.getChangeDataNames(assetList)
    if changed:
        datachangenotify.sendDataChangeNotify(HALL_GAMEID, userAssets.userId,
                                              changed)

    return assetList
コード例 #27
0
def onFiveStarRated(userId, clientId, timestamp):
    ver, channelName = _parseClientId(clientId)
    channel = _channels.get(channelName)
    if channel:
        fsRate = _loadFiveStarRate(userId, channel)
        if ver <= fsRate.rateVersion:
            ftlog.warn('fivestarrate.onFiveStarRated not allow !!', userId,
                       clientId, 'clientVersion=', ver, 'rateVersion=',
                       fsRate.rateVersion)
            # 不允许降低版本进行评价,同时也限定每个版本只能评价一次
            return False
        fsRate.rateTime = timestamp
        fsRate.rateVersion = ver
        _saveFiveStarRate(userId, fsRate)
        count = _incrRateCount(fsRate, timestamp)

        # 添加好评奖励
        if 'appendItems' in channel and _canSendPrize(channel):
            items = channel.get('appendItems', [])
            ftlog.debug('fivestarrate.onFiveStarRated appendItems=', items)
            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            bSendCoin = False
            changed = []
            for item in items:
                assetKind = userAssets.addAsset(9999,
                                                item["itemId"], item["count"],
                                                int(time.time()),
                                                'FIVE_STAR_SEND', 0)
                changed.append(assetKind)
                if item['itemId'] == 'user:chip':
                    bSendCoin = True

            changeNames = TYAssetUtils.getChangeDataNames(changed)
            changeNames.add('free')
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId,
                                                  changeNames)

            #金币雨
            if bSendCoin == True:
                TodoTaskHelper.sendTodoTask(
                    HALL_GAMEID, userId,
                    TodoTaskGoldRain(channel.get('feedback', '感谢您的五星好评')))

        ftlog.debug('fivestarrate.onFiveStarRated userId=', userId,
                    'clientId=', clientId, 'timestamp=', timestamp, 'count=',
                    count)
        return True
    return False
コード例 #28
0
ファイル: user_remote.py プロジェクト: zhaozw/hall37
def consumeAssets(gameId, userId, contentItems, eventId, intEventParam):
    if ftlog.is_debug():
        ftlog.debug('consumeAssets gameId=', gameId,
                    'userId=', userId,
                    'contentItems=', contentItems,
                    'eventId=', eventId,
                    'intEventParam=', intEventParam)
    try:
        contentItems = decodeContentItems(contentItems)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.consumeContentItemList(gameId, contentItems, True,
                                                      pktimestamp.getCurrentTimestamp(), eventId, intEventParam)
        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
        return None, 0
    except TYAssetNotEnoughException, e:
        return e.assetKind.kindId, e.required - e.actually
コード例 #29
0
ファイル: test_base.py プロジェクト: zhaozw/hall37
 def consumeAssets(self, gameId, userId, contentItems, eventId, params):
     if ftlog.is_debug():
         ftlog.debug('user_remote.consumeAssets gameId=', gameId,
                    'userId=', userId,
                    'contentItems=', contentItems,
                    'eventId=', eventId,
                    'params=', params)
     try:
         contentItems = self.decodeContentItems(contentItems)
         userAssets = hallitem.itemSystem.loadUserAssets(userId)
         assetList = userAssets.consumeContentItemList(gameId, contentItems, True, pktimestamp.getCurrentTimestamp(), eventId, 0)
         datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
         return None, 0
     except TYAssetNotEnoughException, e:
         ftlog.error()
         return e.assetKind.kindId, e.required - e.actually
コード例 #30
0
def sendBindInviterReward(status):
    if _bindInviterReward:
        userAssets = hallitem.itemSystem.loadUserAssets(status.userId)
        assetList = userAssets.sendContent(HALL_GAMEID, _bindInviterReward, 1,
                                           True,
                                           pktimestamp.getCurrentTimestamp(),
                                           'HALL_BIND_INVITER_REWARD',
                                           status.inviter)
        changedDataNames = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(HALL_GAMEID, status.userId,
                                              changedDataNames)
        ftlog.info('hall_invite.sendBindInviterReward', 'userId=',
                   status.userId, 'rewards=',
                   [(atup[0].kindId, atup[1]) for atup in assetList])
        return assetList
    return None
コード例 #31
0
ファイル: dizhu_util.py プロジェクト: luningcowboy/tuyoo
def sendRewardItems(userId, items, mail, eventId, eventParam, **kwargs):
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    assetList = userAssets.sendContentItemList(
        DIZHU_GAMEID, items, 1, True, pktimestamp.getCurrentTimestamp(),
        eventId, eventParam)
    changeNames = TYAssetUtils.getChangeDataNames(assetList)
    contents = TYAssetUtils.buildContentsString(assetList)
    if mail:
        replaceDict = {'rewardContent': contents}
        replaceDict.update(kwargs)
        mailstr = strutil.replaceParams(mail, replaceDict)
        mailstr = mailstr.replace('红包券', '元红包')
        message.send(DIZHU_GAMEID, message.MESSAGE_TYPE_SYSTEM, userId,
                     mailstr)
        changeNames.add('message')
    datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, changeNames)
    return assetList
コード例 #32
0
ファイル: account_handler.py プロジェクト: luningcowboy/tuyoo
 def doGainNSLoginReward(self, userId, gameId, clientId):
     checkinOk, rewardAssetList, _checkinDays = \
         halldailycheckin.dailyCheckin.gainCheckinReward(gameId, userId)
     rewardChipCount = 0
     if checkinOk:
         datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(rewardAssetList))
         rewardChipCount = TYAssetUtils.getAssetCount(rewardAssetList, hallitem.ASSET_CHIP_KIND_ID)
     states = halldailycheckin.dailyCheckin.getStates(gameId, userId, pktimestamp.getCurrentTimestamp())
     mo = MsgPack()
     mo.setCmd('gain_nslogin_reward')
     mo.setResult('gameId', gameId)
     mo.setResult('userId', userId)
     mo.setResult('rewardstate', TodoTaskHelper.translateDailyCheckinStates(states))
     mo.setResult('success', True)
     mo.setResult('chip', userchip.getChip(userId))
     mo.setResult('rewardchip', rewardChipCount)
     router.sendToUser(mo, userId)
コード例 #33
0
ファイル: account_handler.py プロジェクト: zhaozw/hall37
 def doGainNSLoginReward(self, userId, gameId, clientId):
     checkinOk, rewardAssetList, _checkinDays = \
         halldailycheckin.dailyCheckin.gainCheckinReward(gameId, userId)
     rewardChipCount = 0
     if checkinOk:
         datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(rewardAssetList))
         rewardChipCount = TYAssetUtils.getAssetCount(rewardAssetList, hallitem.ASSET_CHIP_KIND_ID)
     states = halldailycheckin.dailyCheckin.getStates(gameId, userId, pktimestamp.getCurrentTimestamp())
     mo = MsgPack()
     mo.setCmd('gain_nslogin_reward')
     mo.setResult('gameId', gameId)
     mo.setResult('userId', userId)
     mo.setResult('rewardstate', TodoTaskHelper.translateDailyCheckinStates(states))
     mo.setResult('success', True)
     mo.setResult('chip', userchip.getChip(userId))
     mo.setResult('rewardchip', rewardChipCount)
     router.sendToUser(mo, userId)
コード例 #34
0
def unlockUserForMatch(gameId, userId, bigRoomId, instId, ctrlRoomId, tableId,
                       seatId, contentItem):
    if ftlog.is_debug():
        ftlog.debug("match_remote.unlockUserForMatch gameId=", gameId,
                    "userId=", userId, "bigRoomId=", bigRoomId, "instId=",
                    instId, "ctrlRoomId=", ctrlRoomId, "tableId=", tableId,
                    "seatId=", seatId, "contentItem=", contentItem)

    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if userMatchInfo:
        # 此处有异常,正常要有userMatchInfo
        removeUserMatchInfo(userMatchInfo)

        if contentItem:
            try:
                contentItemObj = TYContentItem.decodeFromDict(contentItem)
                userAssets = hallitem.itemSystem.loadUserAssets(userId)
                assetList = userAssets.sendContentItemList(
                    gameId, [contentItemObj], 1, True,
                    pktimestamp.getCurrentTimestamp(), "MATCH_RETURN_FEE",
                    bigRoomId)
                datachangenotify.sendDataChangeNotify(
                    gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
                ftlog.info(
                    "match_remote.unlockUserForMatch returnFees ok gameId=",
                    gameId, "userId=", userId, "bigRoomId=", bigRoomId,
                    "instId=", instId, "ctrlRoomId=", ctrlRoomId, "tableId=",
                    tableId, "seatId=", seatId, "contentItem=", contentItem)
            except:
                ftlog.error("match_remote.unlockUserForMatch gameId=", gameId,
                            "userId=", userId, "bigRoomId=", bigRoomId,
                            "instId=", instId, "ctrlRoomId=", ctrlRoomId,
                            "tableId=", tableId, "seatId=", seatId,
                            "contentItem=", contentItem)
        try:
            onlinedata.removeOnlineLoc(userId, ctrlRoomId, tableId)
        except:
            ftlog.error("match_remote.unlockUserForMatch gameId=", gameId,
                        "userId=", userId, "bigRoomId=", bigRoomId, "instId=",
                        instId, "ctrlRoomId=", ctrlRoomId, "tableId=", tableId,
                        "seatId=", seatId, "contentItem=", contentItem)

        ftlog.info("match_remote.unlockUserForMatch ok gameId=", gameId,
                   "userId=", userId, "bigRoomId=", bigRoomId, "instId=",
                   instId, "ctrlRoomId=", ctrlRoomId, "tableId=", tableId,
                   "seatId=", seatId, "contentItem=", contentItem)
コード例 #35
0
ファイル: user_remote.py プロジェクト: zhaozw/hall37
def addAssets(gameId, userId, contentItems, eventId, intEventParam):
    if ftlog.is_debug():
        ftlog.debug('addAssets gameId=', gameId,
                    'userId=', userId,
                    'contentItems=', contentItems,
                    'eventId=', eventId,
                    'intEventParam=', intEventParam)
    try:
        contentItems = decodeContentItems(contentItems)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContentItemList(gameId, contentItems, 1, True,
                                                   pktimestamp.getCurrentTimestamp(), eventId, intEventParam)
        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
        return True
    except:
        ftlog.error()
        return False
コード例 #36
0
ファイル: match_remote.py プロジェクト: luningcowboy/tuyoo
def signinMatch(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.signinMatch gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    try:
        userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
        if userMatchInfo:
            if userMatchInfo.instId == instId:
                if userMatchInfo.state == UserMatchInfo.ST_SIGNIN:
                    return ERR_ALREADY_SIGNIN, None
                return ERR_ALREADY_IN_MATCH, None
            else:
                ftlog.warn('match_remote.signinMatch gameId=', gameId,
                           'userId=', userId,
                           'contentItem=', contentItem,
                           'bigRoomId=', bigRoomId,
                           'instId=', instId,
                           'ctrlRoomId=', ctrlRoomId,
                           'recordInstId=', userMatchInfo.instId)
                
        userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId)
        userMatchInfo.ctrlRoomId = ctrlRoomId
        userMatchInfo.instId = instId
        if contentItem:
            userMatchInfo.feeItem = TYContentItem.decodeFromDict(contentItem)
        if userId > 10000 and contentItem:
            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            assetTuple = userAssets.consumeAsset(gameId,
                                                 contentItem['itemId'],
                                                 contentItem['count'],
                                                 pktimestamp.getCurrentTimestamp(),
                                                 'MATCH_SIGNIN_FEE', bigRoomId)
            if assetTuple[1] < contentItem['count']:
                raise TYAssetNotEnoughException(assetTuple[0], contentItem['count'], assetTuple[2])
            # 记录用户
            datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames([assetTuple]))
        saveUserMatchInfo(userMatchInfo)
        daobase.executeTableCmd(ctrlRoomId, 0, 'sadd', 'signs:' + str(ctrlRoomId), userId)
        return 0, None
    except TYAssetNotEnoughException, e:
        return ERR_FEE_NOT_ENOUGH, (e.assetKind.kindId, e.required - e.actually)
コード例 #37
0
ファイル: match_remote.py プロジェクト: zhaozw/hall37
def signinMatch(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.signinMatch gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    try:
        userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
        if userMatchInfo:
            if userMatchInfo.instId == instId:
                if userMatchInfo.state == UserMatchInfo.ST_SIGNIN:
                    return ERR_ALREADY_SIGNIN, None
                return ERR_ALREADY_IN_MATCH, None
            else:
                ftlog.warn('match_remote.signinMatch gameId=', gameId,
                           'userId=', userId,
                           'contentItem=', contentItem,
                           'bigRoomId=', bigRoomId,
                           'instId=', instId,
                           'ctrlRoomId=', ctrlRoomId,
                           'recordInstId=', userMatchInfo.instId)

        userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId)
        userMatchInfo.ctrlRoomId = ctrlRoomId
        userMatchInfo.instId = instId
        if contentItem:
            userMatchInfo.feeItem = TYContentItem.decodeFromDict(contentItem)
        if userId > 10000 and contentItem:
            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            assetTuple = userAssets.consumeAsset(gameId,
                                                 contentItem['itemId'],
                                                 contentItem['count'],
                                                 pktimestamp.getCurrentTimestamp(),
                                                 'MATCH_SIGNIN_FEE', bigRoomId)
            if assetTuple[1] < contentItem['count']:
                raise TYAssetNotEnoughException(assetTuple[0], contentItem['count'], assetTuple[2])
            # 记录用户
            datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames([assetTuple]))
        saveUserMatchInfo(userMatchInfo)
        daobase.executeTableCmd(ctrlRoomId, 0, 'sadd', 'signs:' + str(ctrlRoomId), userId)
        return 0, None
    except TYAssetNotEnoughException, e:
        return ERR_FEE_NOT_ENOUGH, (e.assetKind.kindId, e.required - e.actually)
コード例 #38
0
ファイル: test_base.py プロジェクト: zhaozw/hall37
 def addAssets(self, gameId, userId, contentItems, eventId, params):
     if ftlog.is_debug():
         ftlog.debug('user_remote.addAssets gameId=', gameId,
                    'userId=', userId,
                    'contentItems=', contentItems,
                    'eventId=', eventId,
                    'params=', params)
     try:
         contentItems = self.decodeContentItems(contentItems)
         userAssets = hallitem.itemSystem.loadUserAssets(userId)
         #def sendContentItemList(self, gameId, contentItemList, count, ignoreUnknown, timestamp, eventId, **kwargs):
         # TODO set eventId
         assetList = userAssets.sendContentItemList(gameId, contentItems, 1, True, pktimestamp.getCurrentTimestamp(), 0)
         datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
         return True
     except:
         ftlog.error()
         return False
コード例 #39
0
    def _sendRewards(self, status, task, timestamp):
        userAssets = hallitem.itemSystem.loadUserAssets(status.userId)
        assetList = userAssets.sendContent(self.gameId,
                                           task.taskKind.rewardContent, 1,
                                           True, timestamp, 'ACTIVITY_REWARD',
                                           self.intActId)
        ftlog.debug('QuweiTaskActivity._sendRewards', 'gameId=', self.gameId,
                    'actId=', self.actId, 'userId=', status.userId, 'assets=',
                    [(atup[0].kindId, atup[1]) for atup in assetList])
        changed = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(self.gameId, status.userId,
                                              changed)

        if task.taskKind.rewardMail:
            contents = TYAssetUtils.buildContentsString(assetList)
            mail = strutil.replaceParams(task.taskKind.rewardMail,
                                         {'rewardContent': contents})
            pkmessage.sendPrivate(HALL_GAMEID, status.userId, 0, mail)
コード例 #40
0
ファイル: hallshare.py プロジェクト: zhaozw/hall37
def sendReward(gameId, userId, share, shareLoc):
    from hall.entity import hallitem
    if not share.rewardContent:
        return None

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    assetList = userAssets.sendContent(gameId, share.rewardContent, 1, True,
                                       pktimestamp.getCurrentTimestamp(),
                                       'SHARE_REWARD', share.shareId)
    ftlog.info('hallshare.sendReward gameId=', gameId,
               'userId=', userId,
               'shareId=', share.shareId,
               'shareLoc=', shareLoc,
               'rewards=', [(atup[0].kindId, atup[1]) for atup in assetList])
    changedDataNames = TYAssetUtils.getChangeDataNames(assetList)
    datachangenotify.sendDataChangeNotify(gameId, userId, changedDataNames)
    TGHall.getEventBus().publishEvent(HallShareGetRewardEvent(gameId, userId, assetList))

    return assetList
コード例 #41
0
ファイル: match_remote.py プロジェクト: zhaozw/hall37
def signoutMatch(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.signoutMatch gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if not userMatchInfo:
        return 0, None

    if userMatchInfo.instId != instId:
        ftlog.debug('match_remote.signoutMatch diffInstId gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId,
                    'recordInstId=', userMatchInfo.instId)
        return 0, None

    if userMatchInfo.state != UserMatchInfo.ST_SIGNIN:
        return ERR_ALREADY_IN_MATCH, None

    removeUserMatchInfo(userMatchInfo)
    daobase.executeTableCmd(ctrlRoomId, 0, 'srem', 'signs:' + str(ctrlRoomId), userId)
    ftlog.debug('match_remote.signoutMatch gameId=', gameId,
                'userId=', userId,
                'contentItem=', contentItem,
                'bigRoomId=', bigRoomId,
                'instId=', instId,
                'ctrlRoomId=', ctrlRoomId)
    if userId > 10000 and contentItem:
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        item = TYContentItem.decodeFromDict(contentItem)
        assetList = userAssets.sendContentItemList(gameId, [item], 1, True,
                                                   pktimestamp.getCurrentTimestamp(),
                                                   'MATCH_RETURN_FEE', bigRoomId)
        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
    return 0, None
コード例 #42
0
ファイル: fivestarrate.py プロジェクト: zhaozw/hall37
def onFiveStarRated(userId, clientId, timestamp):
    ver, channelName = _parseClientId(clientId)
    channel = _channels.get(channelName)
    if channel:
        fsRate = _loadFiveStarRate(userId, channel)
        fsRate.rateTime = timestamp
        if ver > fsRate.rateVersion:
            fsRate.rateVersion = ver
        _saveFiveStarRate(userId, fsRate)
        count = _incrRateCount(fsRate, timestamp)

        # 添加好评奖励
        if 'appendItems' in channel and _canSendPrize(channel):
            items = channel.get('appendItems', [])
            ftlog.debug('fivestarrate.onFiveStarRated appendItems=', items)
            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            bSendCoin = False
            changed = []
            for item in items:
                assetKind = userAssets.addAsset(9999, item["itemId"], item["count"], int(time.time()), 'FIVE_STAR_SEND',
                                                0)
                changed.append(assetKind)
                if item['itemId'] == 'user:chip':
                    bSendCoin = True

            changeNames = TYAssetUtils.getChangeDataNames(changed)
            changeNames.add('free')
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, changeNames)

            # 金币雨
            if bSendCoin == True:
                TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskGoldRain(channel.get('feedback', '感谢您的五星好评')))

        ftlog.debug('fivestarrate.onFiveStarRated userId=', userId,
                    'clientId=', clientId,
                    'timestamp=', timestamp,
                    'count=', count)
        return True
    return False
コード例 #43
0
ファイル: hallvip.py プロジェクト: zhaozw/hall37
    def addUserVipExp(self, gameId, userId, toAddExp, eventId, intEventParam):
        '''
        增加vip经验值
        @param gameId: 在那个gameId中增加的经验值,用于统计 
        @param toAddExp: 要增加的经验值
        @param eventId: 导致经验值增加的事件ID
        @param intEventParam: eventId相关参数
        @return: TYUserVip
        '''
        assert (toAddExp >= 0)
        vipExp = self._vipDao.incrVipExp(userId, toAddExp)
        oldVipExp = vipExp - toAddExp
        oldVipLevel = self._vipSystem.findVipLevelByVipExp(oldVipExp)
        newVipLevel = self._vipSystem.findVipLevelByVipExp(vipExp)

        ftlog.debug('TYUserVipSystemImpl.addUserVipExp gameId=', gameId, 'userId=', userId,
                    'oldExp=', oldVipExp, 'newExp=', vipExp,
                    'oldLevel=', oldVipLevel.level, 'newLevel=', newVipLevel.level)

        userVip = TYUserVip(userId, vipExp, newVipLevel)
        if oldVipLevel.level != newVipLevel.level:
            nextVipLevel = oldVipLevel.nextVipLevel
            assetList = []
            while (nextVipLevel and nextVipLevel.level <= newVipLevel.level):
                subContentList = self._sendRewardContent(gameId, userVip, nextVipLevel)
                if subContentList:
                    assetList.extend(subContentList)
                nextVipLevel = nextVipLevel.nextVipLevel
            changeDataNames = TYAssetUtils.getChangeDataNames(assetList)
            changeDataNames.add('vip')
            changeDataNames.add('decoration')
            datachangenotify.sendDataChangeNotify(gameId, userId, changeDataNames)
            TGHall.getEventBus().publishEvent(TYUserVipLevelUpEvent(gameId, userId, oldVipLevel,
                                                                    userVip, assetList,
                                                                    eventId, intEventParam))
        else:
            datachangenotify.sendDataChangeNotify(gameId, userId, 'vip')
            TGHall.getEventBus().publishEvent(TYUserVipExpChangedEvent(gameId, userId, userVip, oldVipExp))
        return userVip
コード例 #44
0
    def __getReward(self, rdskey, userId, gameId, actId, excode):
        config_ = daobase.executeMixCmd('HGET', 'excodeinfo:' + rdskey, 'rewards')

        try:
            config_ = json.loads(config_)
        except:
            return {}

        if not isinstance(config_, list):
            return {}

        rewards = {}
        items_ = config_
        ftlog.debug('ExchangeCode.__getReward', 'items=', items_)
        from hall.entity.hallitem import itemSystem
        userAssets = itemSystem.loadUserAssets(userId)
        assetTupleList = []
        for itemDict in items_:
            for assetKindId, count in itemDict.iteritems():
                count = int(count)
                if assetKindId in self._rewardMap:
                    assetKindId = self._rewardMap[assetKindId]['itemId']
                assetTuple = userAssets.addAsset(gameId, assetKindId, count,
                                                 int(time.time()),
                                                 'ACTIVITY_EXCHANGE', 0)

                rewards[assetKindId] = count
                assetTupleList.append(assetTuple)
        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetTupleList))
        ftlog.info('ExchangeCode->__statistics userid=', userId,
                   'excode=', excode,
                   'rewards=', rewards)
        msg = '兑换码兑换礼品成功,已自动加入到您的背包中,请查收。'
        message.send(9999, message.MESSAGE_TYPE_SYSTEM, userId, msg)
        result = TYAssetUtils.buildContentsString(assetTupleList)
        ftlog.debug('the last msg is result', result)
        return result
コード例 #45
0
ファイル: hallroulette.py プロジェクト: zhaozw/hall37
def sendGiftsToUser(userId, gameId, clientId, items):
    '''
        多个奖品时的发奖,或者一个奖品的发奖,items为数组
    '''
    contentItemList = []
    rouletteMap = getRouletteMap()

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

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

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    results = userAssets.sendContentItemList(gameId, contentItemList, 1, True, int(time.time()), 'ROULETTE_GOLD', 0)
    datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(results))
コード例 #46
0
ファイル: hall_red_envelope.py プロジェクト: zhaozw/hall37
    def openRedEnvelope(self, userId, itemId=''):
        '''
        打开红包
        '''
        global _redEnvelopeConfig

        # 是否领取过
        receivers = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.RECEIVER, 0, -1)
        if receivers:
            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope receivers:', receivers)

            for receiverJson in receivers:
                receiver = json.loads(receiverJson)
                if ftlog.is_debug():
                    ftlog.debug('TYRedEnvelope.openRedEnvelope receiver:', receiver)
                if userId == receiver['userId']:
                    return False, _redEnvelopeConfig['tips']['opened']

        # 构造添加给获取红包用户的奖励清单        
        contentItemList = []
        prizesJson = self._getPrize(itemId)
        # prizesJson = daobase.executeMixCmd('LPOP', self.dbPrefix + self.id + self.PACKAGES)
        daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.PACKAGES, self.expiredTime)

        if prizesJson:
            prizes = json.loads(prizesJson)
            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope prizes:', prizes)
            for prize in prizes:
                if ftlog.is_debug():
                    ftlog.debug('TYRedEnvelope.openRedEnvelope prize:', prize)

                result, _itemId = self.getAssetID(prize)
                if result == False:
                    ftlog.debug('TYRedEnvelope.openRedEnvelope prize err1: ', prize, ' left: ', self.contents);
                    continue

                result, value = self.getItemValue(prize)
                if result == False:
                    ftlog.debug('TYRedEnvelope.openRedEnvelope prize err2: ', prize, ' left: ', self.contents);
                    continue

                if ftlog.is_debug():
                    ftlog.debug('TYRedEnvelope.openRedEnvelope itemId:', _itemId)
                    ftlog.debug('TYRedEnvelope.openRedEnvelope count:', prizes[prize] * value)

                contentItemList.append(
                    TYContentItem.decodeFromDict({'itemId': _itemId, 'count': prizes[prize] * value}))

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

            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            # 添加奖励
            results = userAssets.sendContentItemList(HALL_GAMEID, contentItemList, 1, True,
                                                     pktimestamp.getCurrentTimestamp(), self.EVENTID, 0)
            # notify
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, TYAssetUtils.getChangeDataNames(results))
            # 构造奖励字符串
            prizeString = TYAssetUtils.buildContentsString(results)

            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope prizeString:', prizeString)

            # add receiver
            re = {}
            re['userId'] = userId
            re['prize'] = prizes
            re['prizeStr'] = prizeString
            re['time'] = pktimestamp.formatTimeMs()

            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope add receiver re: ', re)
            daobase.executeMixCmd('LPUSH', self.dbPrefix + self.id + self.RECEIVER, json.dumps(re))
            daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.RECEIVER, self.expiredTime)

            # make response
            response = {}
            response['envelopeId'] = self.id
            response['prizes'] = prizes
            response['prizeStr'] = prizeString

            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope response: ', response)

            return True, response
        else:
            if self.state != self.STATE_FINISH:
                self.state = self.STATE_FINISH
                self.save2DB()

            return False, _redEnvelopeConfig['tips']['finished']
コード例 #47
0
ファイル: buy_send_gift.py プロジェクト: zhaozw/hall37
def _onOrderDelivery(event):
    from hall.entity import hallitem
    nowDT = datetime.now()
    order = event.orderDeliveryResult.order

    if ((_conf.startDT and nowDT < _conf.startDT)
        or (_conf.endDT and nowDT >= _conf.endDT)):
        if ftlog.is_debug():
            ftlog.debug('buy_send_gift._onOrderDelivery outofTime userId=', event.userId,
                        'orderId=', order.orderId,
                        'productId=', order.productId,
                        'nowDT=', nowDT.strftime('%Y-%m-%d %H:%M:%S'),
                        'startDT=', _conf.startDT.strftime('%Y-%m-%d %H:%M:%S'),
                        'endDT=', _conf.endDT.strftime('%Y-%m-%d %H:%M:%S'))
        return

    giftConf = _conf.findGiftConf(order.productId)
    if not giftConf:
        if ftlog.is_debug():
            ftlog.debug('buy_send_gift._onOrderDelivery noGiftConf userId=', event.userId,
                        'orderId=', order.orderId,
                        'productId=', order.productId,
                        'orderClientId=', order.clientId)
        return

    hallGameId = strutil.getGameIdFromHallClientId(order.clientId)
    if hallGameId not in giftConf.gameIds:
        if ftlog.is_debug():
            ftlog.debug('buy_send_gift._onOrderDelivery notInGameIds userId=', event.userId,
                        'orderId=', order.orderId,
                        'productId=', order.productId,
                        'giftConf=', giftConf.conf,
                        'orderClientId=', order.clientId,
                        'hallGameId=', hallGameId,
                        'gameIds=', giftConf.gameIds)
        return

    count = 0
    if giftConf.maxCount >= 0:
        limitD = gamedata.getGameAttrJson(order.userId, hallGameId, 'act.buy_send_gift', {})
        count = limitD.get(order.productId, 0)
        if count + 1 > giftConf.maxCount:
            ftlog.info('buy_send_gift._onOrderDelivery overLimit userId=', event.userId,
                       'orderId=', order.orderId,
                       'productId=', order.productId,
                       'giftConf=', giftConf.conf if giftConf else None,
                       'orderClientId=', order.clientId,
                       'count=', count,
                       'maxCount=', giftConf.maxCount)
            return
        count += 1
        limitD[order.productId] = count
        gamedata.setGameAttr(order.userId, hallGameId, 'act.buy_send_gift', strutil.dumps(limitD))

    assetList = None
    if giftConf.giftContent:
        userAssets = hallitem.itemSystem.loadUserAssets(order.userId)
        # def sendContent(self, gameId, content, count, ignoreUnknown, timestamp, eventId, intEventParam):
        assetList = userAssets.sendContent(hallGameId, giftConf.giftContent, 1,
                                           True, pktimestamp.getCurrentTimestamp(),
                                           'ACTIVITY_REWARD',
                                           10043)
    changedDataNames = TYAssetUtils.getChangeDataNames(assetList) if assetList else set()

    contentStr = TYAssetUtils.buildContentsString(assetList) if assetList else ''
    if giftConf.mail:
        mail = strutil.replaceParams(giftConf.mail, {'gotContent': contentStr, 'price': order.product.price})
        message.send(hallGameId, message.MESSAGE_TYPE_SYSTEM, order.userId, mail)
        changedDataNames.add('message')
    if changedDataNames:
        datachangenotify.sendDataChangeNotify(HALL_GAMEID, order.userId, changedDataNames)
    ftlog.info('buy_send_gift._onOrderDelivery sendGift userId=', event.userId,
               'orderId=', order.orderId,
               'productId=', order.productId,
               'giftConf=', giftConf.conf if giftConf else None,
               'orderClientId=', order.clientId,
               'count=', count,
               'maxCount=', giftConf.maxCount,
               'assetList=', [(a[0].kindId, a[1]) for a in assetList] if assetList else None)
コード例 #48
0
ファイル: match_remote.py プロジェクト: zhaozw/hall37
def unlockUserForMatch(gameId, userId, bigRoomId, instId, ctrlRoomId, tableId, seatId, contentItem):
    if ftlog.is_debug():
        ftlog.debug('match_remote.unlockUserForMatch gameId=', gameId,
                    'userId=', userId,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId,
                    'tableId=', tableId,
                    'seatId=', seatId,
                    'contentItem=', contentItem)

    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if userMatchInfo:
        # 此处有异常,正常要有userMatchInfo
        removeUserMatchInfo(userMatchInfo)

        if contentItem:
            try:
                contentItemObj = TYContentItem.decodeFromDict(contentItem)
                userAssets = hallitem.itemSystem.loadUserAssets(userId)
                assetList = userAssets.sendContentItemList(gameId, [contentItemObj],
                                                           1, True,
                                                           pktimestamp.getCurrentTimestamp(),
                                                           'MATCH_RETURN_FEE', bigRoomId)
                datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
                ftlog.info('match_remote.unlockUserForMatch returnFees ok gameId=', gameId,
                           'userId=', userId,
                           'bigRoomId=', bigRoomId,
                           'instId=', instId,
                           'ctrlRoomId=', ctrlRoomId,
                           'tableId=', tableId,
                           'seatId=', seatId,
                           'contentItem=', contentItem)
            except:
                ftlog.error('match_remote.unlockUserForMatch gameId=', gameId,
                            'userId=', userId,
                            'bigRoomId=', bigRoomId,
                            'instId=', instId,
                            'ctrlRoomId=', ctrlRoomId,
                            'tableId=', tableId,
                            'seatId=', seatId,
                            'contentItem=', contentItem)
        try:
            onlinedata.removeOnlineLoc(userId, ctrlRoomId, tableId)
        except:
            ftlog.error('match_remote.unlockUserForMatch gameId=', gameId,
                        'userId=', userId,
                        'bigRoomId=', bigRoomId,
                        'instId=', instId,
                        'ctrlRoomId=', ctrlRoomId,
                        'tableId=', tableId,
                        'seatId=', seatId,
                        'contentItem=', contentItem)

        ftlog.info('match_remote.unlockUserForMatch ok gameId=', gameId,
                   'userId=', userId,
                   'bigRoomId=', bigRoomId,
                   'instId=', instId,
                   'ctrlRoomId=', ctrlRoomId,
                   'tableId=', tableId,
                   'seatId=', seatId,
                   'contentItem=', contentItem)
コード例 #49
0
 def _exchange(self, userId, gameId, clientId, activityId, exchangeId):
     key = "TYActivity:%d:%d:%s" % (gameId, userId, activityId)
     ftlog.debug("getGifts key:", key)
     ftlog.debug("getGifts key!!!exchangeId:", exchangeId)
     num = daobase.executeUserCmd(userId, 'hget', key, 'giftNum')
     if not num:
         num = 0
     giftsNum = num
     exConfig = self._getExchangeConfig(exchangeId)
     if not exConfig:
         return {"errorInfo": "config not exist", "errorCode": 2}
     needCount = exConfig["consumeCount"]
     limit = exConfig["limitTimes"]
     nowDateStr = time.strftime("%Y-%m-%d", time.localtime(time.time()))
     exTimesField = "exTimes:%d:%s" % (exchangeId, nowDateStr)
     key = "TYActivity:%d:%d:%s" % (gameId, userId, activityId)
     ftlog.debug("_exchange key:", key)
     exchangeResult = daobase.executeUserLua(userId, self.EXCHANGE_SCRIPT,
                                             4, key, needCount, limit, exTimesField)
     if exchangeResult == 1:
         ftlog.info("exceed limit,", "userId", userId, "gameId", gameId, "activityId", activityId,
                    "exchangeId", exchangeId, clientId)
         return {"exchangeResult": [], "reason": u"今日兑换次数已满!", "list": [], "giftsNum": giftsNum}
     if exchangeResult == 2:
         ftlog.info("no enough gifts,", "userId", userId, "gameId", gameId, "activityId", activityId,
                    "exchangeId", exchangeId, clientId)
         ftlog.debug("self._clientConf:", self._clientConf)
         giftName = self._clientConf["config"]["gift"]["name"]
         info = u"您的%s不足!" % giftName
         ftlog.debug("_exchange key123:", key)
         ftlog.debug("_exchange key123:", giftsNum)
         return {"exchangeResult": [], "reason": info, "list": [], "giftsNum": giftsNum}
     result = {}
     result["exchangeResult"] = []
     info = u"兑换成功,您获得"
     itemNum = len(exConfig["items"])
     changed = []
     from hall.entity.hallitem import itemSystem
     userAssets = itemSystem.loadUserAssets(userId)
     for item in exConfig["items"]:
         itemNum -= 1
         asset = userAssets.addAsset(gameId, item['productId'], item['count'], int(time.time()),
                                     'ACTIVITY_GETSCORE', 0)
         changed.append(asset)
         result["exchangeResult"].append({"name": item["name"], "count": item["count"],
                                          "productId": item["productId"], "unit": item["unit"]})
         if itemNum == 0:
             info = info + "%d%s%s。" % (item["count"], item["unit"], item["name"])
         else:
             info = info + "%d%s%s," % (item["count"], item["unit"], item["name"])
         ftlog.info('exchangeCode userId = ', userId,
                    'gameId = ', gameId,
                    'clientId = ', clientId,
                    'activityId = ', activityId,
                    'info = ', info)
     changeNames = TYAssetUtils.getChangeDataNames(changed)
     datachangenotify.sendDataChangeNotify(gameId, userId, changeNames)
     result["reason"] = info
     result["list"] = []
     '''
         拿到当前剩余的积分,并返回
     '''
     ftlog.debug("_exchange key123:", key)
     result["giftsNum"] = giftsNum
     ftlog.debug("_exchange key123456:", giftsNum)
     ftlog.info("exchangeResult,", "userId", userId, "gameId", gameId, "activityId", activityId,
                "exchangeId", exchangeId, clientId, result)
     return result
コード例 #50
0
ファイル: hallstore.py プロジェクト: zhaozw/hall37
def exchangeProduct(gameId, userId, clientId, orderId, productId, count):
    product = storeSystem.findProduct(productId)
    if not product:
        raise TYBuyProductUnknownException(productId)

    if product.buyType != 'exchange':
        raise TYProductNotSupportExchangeException(productId)

    timestamp = pktimestamp.getCurrentTimestamp()

    # 限购系统锁定
    periodId = hallstocklimit.productBuyLimitSystem.lockProduct(gameId, userId, productId, count, timestamp)

    # 创建订单
    try:
        storeSystem.buyProduct(gameId, userId, clientId, orderId, productId, count)
    except:
        if periodId:
            hallstocklimit.productBuyLimitSystem.unlockProduct(gameId, userId, periodId, productId,
                                                               count, 1, timestamp)
        raise

    # 
    ftlog.info('hallstore.exchangeProduct gameId=', gameId,
               'userId=', userId,
               'clientId=', clientId,
               'orderId=', orderId,
               'productId=', productId,
               'count=', count)

    try:
        # 消耗兑换的东西
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetTuple = userAssets.consumeAsset(gameId, product.exchangeFeeContentItem.assetKindId,
                                             product.exchangeFeeContentItem.count * count,
                                             timestamp,
                                             'BUY_PRODUCT', pokerconf.productIdToNumber(productId))
        if assetTuple[1] < product.exchangeFeeContentItem.count * count:
            ftlog.warn('hallstore.exchangeProduct gameId=', gameId,
                       'userId=', userId,
                       'clientId=', clientId,
                       'orderId=', orderId,
                       'productId=', productId,
                       'count=', count,
                       'consumedCount=', assetTuple[1],
                       'needConsumeCount=', product.exchangeFeeContentItem.count * count,
                       'err=', 'ConsumeNotEnough')
            msg = strutil.replaceParams(product.exchangeFeeNotEnoughText, {'feeName': assetTuple[0].displayName})
            raise TYProductExchangeNotEnoughException(productId, msg)

        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames([assetTuple]))
        consumeMap = {assetTuple[0].kindId: assetTuple[1]}
        ret = storeSystem.deliveryOrder(userId, orderId, productId, TYChargeInfo('', {}, consumeMap))

        # 分享提示
        shareId = hallshare.getShareId('exchangeShare', userId, gameId)
        if ftlog.is_debug():
            ftlog.debug('handleExchangeAuditResult shareId: ', shareId)

        share = hallshare.findShare(shareId)
        if share:
            desc = share.getDesc(gameId, userId, True)
            newDesc = strutil.replaceParams(desc, {'exchangeDesc': product.displayName})
            share.setDesc(newDesc)
            task = share.buildTodotask(HALL_GAMEID, userId, 'exchange')
            TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, task)

        if periodId:
            hallstocklimit.productBuyLimitSystem.deliveryProduct(gameId, userId, periodId, productId, count, timestamp)
        return ret
    except:
        if periodId:
            hallstocklimit.productBuyLimitSystem.unlockProduct(gameId, userId, periodId, productId, count, 2, timestamp)
        raise
コード例 #51
0
ファイル: message_handler.py プロジェクト: zhaozw/hall37
 def do_message_receive(self, userId, gameId, clientId, typeid, msgid):
     ret = message.attachment_receive(userId, typeid, msgid, hallitem.itemSystem)
     if ret:
         changed = TYAssetUtils.getChangeDataNames(ret[1])
         changed.add('message')
         datachangenotify.sendDataChangeNotify(ret[0], userId, changed)
コード例 #52
0
ファイル: hallstore.py プロジェクト: zhaozw/hall37
def _onOrderDelivery(event):
    if event.orderDeliveryResult.assetItems:
        changedNames = TYAssetUtils.getChangeDataNames(event.orderDeliveryResult.assetItems)
        datachangenotify.sendDataChangeNotify(event.gameId, event.userId, changedNames)