Beispiel #1
0
    def sendBenefits(self, gameId, userId, timestamp=None):
        '''
        发放救济金
        @return: isSend(True/False), TYUserBenefits
        '''
        if timestamp is None:
            timestamp = pktimestamp.getCurrentTimestamp()
        chip = pkuserchip.getUserChipAll(userId)
        if chip < self._minChip:
            # 用户金币低于指定数目时,发放救济金
            userBenefits = self.loadUserBenefits(gameId, userId, timestamp)
            if not userBenefits.hasLeftTimes():  # 没有剩余次数,弹分享引导
                oldtime = gamedata.getGameAttr(userId, HALL_GAMEID, 'relief_share_date')
                if not oldtime or datetime.fromtimestamp(oldtime).date() < datetime.fromtimestamp(timestamp).date():
                    # 每天最多弹一次
                    gamedata.setGameAttr(userId, HALL_GAMEID, 'relief_share_date', timestamp)
                    shareId = hallshare.getShareId('Relieffund', userId, gameId)
                    share = hallshare.findShare(shareId)
                    if share:
                        task = share.buildTodotask(gameId, userId, 'Relieffund')
                        TodoTaskHelper.sendTodoTask(gameId, userId, task)
                return False, userBenefits

            # 发放救济金
            userBenefits.times += 1
            self._benefitsDao.saveUserBenefitsData(userId, TYUserBenefitsData(userBenefits.times, timestamp))
            self._sendBenefits(gameId, userBenefits)
            # 通知用户金币刷新
            datachangenotify.sendDataChangeNotify(gameId, userId, ['udata'])
            return True, userBenefits
        return False, self.loadUserBenefits(gameId, userId, timestamp)
    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
Beispiel #3
0
 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
Beispiel #4
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, 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))
Beispiel #5
0
    def exchange_user_vip_charge(cls, gameId, userId, grade):
        """
        用户兑换vip充值金币
        """
        ftlog.debug('exchange_user_vip_charge', gameId, userId, grade)
        grade = str(grade)
        vip_charge_info = cls.get_user_vip_charge(userId)
        if not vip_charge_info:
            return 1

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

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

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

        chip = cls.VIP_COIN_CONFIG[grade]
        try:
            userchip.incrChip(userId, gameId, chip, 0,
                              'H5_YOUKU_DIZHU_VIP_EXCHANGE_CHIP', 0, None)
        except:
            import traceback
            traceback.print_exc()
        datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
        return 0
Beispiel #6
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)
Beispiel #7
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])
Beispiel #8
0
def doSilverLottery(userId, gameId, clientId):
    '''
        银盘抽奖
    '''
    # 减少抽奖卡
    timestamp = pktimestamp.getCurrentTimestamp()
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    _, consumeCount, _final = userAssets.consumeAsset(
        gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, 1, timestamp,
        'ROULETTE_SILVER', 0)
    if consumeCount < 1:  # 去金盘抽奖
        result = doGetGoldUpdate(userId, gameId, clientId)
        from hall.servers.util.roulette_handler import rouletteHelper
        mo = rouletteHelper.makeRouletteQueryResponse(gameId, userId, clientId,
                                                      'roulette_goldUpdate',
                                                      result)
        from poker.protocol import router
        router.sendToUser(mo, userId)
        return
    datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
    # 抽奖
    result = {}
    result['items'] = doRouletteSilverLottery(userId, gameId, clientId)
    # 判断下次的抽奖为金盘还是银盘
    result['rouletteType'] = 'silver'
    result['cardNumber'] = userAssets.balance(
        gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, timestamp)
    # 返回信息,判断是否有抽奖卡,没有的话,改为金盘抽奖
    ftlog.hinfo('doSilverLottery.userId=', userId,
                'gameId=', gameId, 'clientId=', clientId, 'items=',
                result.get('items', []), 'rouletteType=', 1, 'number=', 1)
    sendGiftsToUser(userId, gameId, clientId, [result['items']])
    return result
Beispiel #9
0
    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)
Beispiel #10
0
def _onOrderDelivery(event):
    if hasattr(event, 'assetItems') and event.assetItems:
        for assetKind, count, final in event.assetItems:
            # 从无到有或者从有到无需要发送推广位变化
            if (assetKind.kindId in (hallitem.ASSET_ITEM_MEMBER_KIND_ID, hallitem.ASSET_ITEM_MEMBER_NEW_KIND_ID)
                and (count == final)):
                datachangenotify.sendDataChangeNotify(HALL_GAMEID, event.userId, 'promotion_loc')
    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))
Beispiel #12
0
def doSilverLottery(userId, gameId, clientId):
    '''
        银盘抽奖
    '''
    # 减少抽奖卡
    timestamp = pktimestamp.getCurrentTimestamp()
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    _, consumeCount, _final = userAssets.consumeAsset(gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, 1,
                                                      timestamp, 'ROULETTE_SILVER', 0)
    if consumeCount < 1:  # 去金盘抽奖
        result = doGetGoldUpdate(userId, gameId, clientId)
        from hall.servers.util.roulette_handler import rouletteHelper
        mo = rouletteHelper.makeRouletteQueryResponse(gameId, userId, clientId, 'roulette_goldUpdate', result)
        from poker.protocol import router
        router.sendToUser(mo, userId)
        return
    datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
    # 抽奖
    result = {}
    result['items'] = doRouletteSilverLottery(userId, gameId, clientId)
    # 判断下次的抽奖为金盘还是银盘
    result['rouletteType'] = 'silver'
    result['cardNumber'] = userAssets.balance(gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, timestamp)
    # 返回信息,判断是否有抽奖卡,没有的话,改为金盘抽奖
    ftlog.hinfo('doSilverLottery.userId=', userId,
                'gameId=', gameId,
                'clientId=', clientId,
                'items=', result.get('items', []),
                'rouletteType=', 1,
                'number=', 1)
    sendGiftsToUser(userId, gameId, clientId, [result['items']])
    return result
Beispiel #13
0
    def sendAssetsToUser(cls,
                         gameId,
                         userId,
                         assets,
                         eventId,
                         mail=None,
                         intEventParam=0):
        '''
        :param gameId 统计用途,地主就写6
        :param assets 要发送的资产, 格式必须是:{itemId:'item:0011', count:1}
        :param eventId 事件ID,要在config/poker/map.bieventid.json中注册
        :param mail(optional) 给用户邮箱发送信息,默认不发送
        '''
        timestamp = pktimestamp.getCurrentTimestamp()
        contentitem = TYContentItem.decodeFromDict(assets)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetKind, consumecount, finalcount = userAssets.addAsset(
            gameId, contentitem.assetKindId, contentitem.count, timestamp,
            eventId, intEventParam)
        # 通知用户道具和消息存在改变
        if assetKind.keyForChangeNotify:
            datachangenotify.sendDataChangeNotify(
                gameId, userId, [assetKind.keyForChangeNotify, 'message'])

        # 发送邮箱信息
        if mail and len(mail) > 0:
            pkmessage.sendPrivate(9999, userId, 0, mail)

        return (assetKind, consumecount, finalcount)
Beispiel #14
0
    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)
Beispiel #15
0
 def doQiPaiNotify(self, appId, userId, buttonId, rmbs, diamonds):
     userdata.clearUserCache(userId)
     if appId > 0 and userId > 0:
         datachangenotify.sendDataChangeNotify(appId, userId, ['chip', 'diamonds'])
     msg = MsgPack()
     msg.setResult('ec', 0)
     return msg
Beispiel #16
0
def setUpTableChipOnSitDown(userId, roomId, tableId, seatId, clientId,
                            isSupportBuyin, continuityBuyin, roomBuyInChip,
                            roomMinCoin):
    ftlog.debug('setUpTableChipOnSitDown ', userId, roomId, tableId, seatId,
                clientId, isSupportBuyin, continuityBuyin, roomBuyInChip)
    if continuityBuyin == 1:
        # 连续带入判断
        last_table_chip = _getLastTableChip(userId, isSupportBuyin)
        ftlog.debug('setUpTableChipOnSitDown last_table_chip=',
                    last_table_chip)
        if last_table_chip >= roomBuyInChip:
            buyin_chip = _moveChipToTablechipBuyUser(userId, roomId, tableId,
                                                     seatId, isSupportBuyin,
                                                     last_table_chip,
                                                     roomMinCoin, clientId)
        else:
            buyin_chip = _moveChipToTablechipBuyUser(userId, roomId, tableId,
                                                     seatId, isSupportBuyin,
                                                     roomBuyInChip,
                                                     roomMinCoin, clientId)
    else:
        buyin_chip = _moveChipToTablechipBuyUser(userId, roomId, tableId,
                                                 seatId, isSupportBuyin,
                                                 roomBuyInChip, roomMinCoin,
                                                 clientId)
    _resetLastTableChip(userId, isSupportBuyin)
    datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, 'udata')
    return buyin_chip
Beispiel #17
0
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
Beispiel #18
0
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
Beispiel #19
0
 def addUserItemByKindId(cls, userId, gameId, clientId, kindId, count):
     timestamp = pktimestamp.getCurrentTimestamp()
     userAssets = hallitem.itemSystem.loadUserAssets(userId)
     calcGameId = strutil.getGameIdFromHallClientId(clientId)
     userAssets.addAsset(calcGameId, kindId, count, timestamp, 'MAJIANG_FANGKA_INVITE_REWARD', pokerconf.clientIdToNumber(clientId))
     datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
     ftlog.debug('addUserItemByKindId userId:', userId, ' gameId:', gameId, 'kindId', kindId, 'count', count)
Beispiel #20
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
Beispiel #21
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)
Beispiel #22
0
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
Beispiel #23
0
def sendLoginReward(userId, gameId, clientId):
    global _loginRewards
    if ftlog.is_debug():
        ftlog.debug('hall_login_reward.sendLoginReward userId:', userId,
                    ' gameId:', gameId, ' clientId:', clientId)

    conf = hallconf.getLoginRewardConf()
    supplement = conf.get('supplement', None)
    if supplement != None:
        from hall.entity import hallitem
        changed = []
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        items = supplement["items"]
        for item in items:
            maxCount = item["count"]
            itemId = item["itemId"]
            balance = userAssets.balance(gameId, itemId,
                                         pktimestamp.getCurrentTimestamp())
            if (maxCount - balance) > 0:

                assetKind, _addCount, _final = userAssets.addAsset(
                    gameId, itemId, maxCount - balance,
                    pktimestamp.getCurrentTimestamp(), 'LOGIN_REWARD', 0)

                if assetKind.keyForChangeNotify:
                    changed.append(assetKind.keyForChangeNotify)

        datachangenotify.sendDataChangeNotify(gameId, userId, changed)

    for reward in _loginRewards:
        reward.sendRewards(userId, gameId, clientId)
Beispiel #24
0
def _moveHall51DataBack(userId, gameId, clientId):
    try:
        gameId = HALL_ID
        flag = gamedata.getGameAttrInt(userId, gameId, 'userChipMoveGame')
        ftlog.info('_moveHall51DataBack', userId, gameId, flag)
        if flag > 0:
            # 当前用户登录过HALL51
            chip, exp, charm, coupon = gamedata.getGameAttrs(
                userId, gameId, ['chip', 'exp', 'charm', 'coupon'])
            chip, exp, charm, coupon = strutil.parseInts(
                chip, exp, charm, coupon)
            ftlog.info('_moveHall51DataBack data->', userId, gameId, chip, exp,
                       charm, coupon)
            if charm > 0:
                userdata.incrCharm(userId, charm)
            if exp > 0:
                userdata.incrExp(userId, exp)
            if coupon > 0:
                trueDelta, finalCount = userchip.incrCoupon(
                    userId, gameId, coupon, userchip.ChipNotEnoughOpMode.NOOP,
                    userchip.EVENT_NAME_SYSTEM_REPAIR, 0, clientId)
                ftlog.info('_moveHall51DataBack data coupon->', userId, gameId,
                           coupon, trueDelta, finalCount)
            if chip > 0:
                trueDelta, finalCount = userchip.incrChip(
                    userId, gameId, chip, userchip.ChipNotEnoughOpMode.NOOP,
                    userchip.EVENT_NAME_SYSTEM_REPAIR, 0, clientId)
                ftlog.info('_moveHall51DataBack data chip->', userId, gameId,
                           chip, trueDelta, finalCount)
            gamedata.delGameAttrs(
                userId, gameId,
                ['chip', 'exp', 'charm', 'coupon', 'userChipMoveGame'])
            datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
    except:
        ftlog.error()
Beispiel #25
0
    def doGetPrize(self, gameId, userId, clientId):
        try:
            timestamp = pktimestamp.getCurrentTimestamp()
            status = neituiguang.loadStatus(userId, timestamp)
            if not status.isBindMobile:
                conf = neituiguang.getConf()
                TodoTaskHelper.sendTodoTask(
                    gameId, userId, TodoTaskBindPhone(conf.pleaseBindPhone,
                                                      ''))
                return
            count, assetList = neituiguang.getAllReward(status)
            if count > 0:
                conf = neituiguang.getConf()
                prizeRewardTips = strutil.replaceParams(
                    conf.prizeRewardTips, {
                        'rewardContent':
                        TYAssetUtils.buildContentsString(assetList)
                    })
                TodoTaskHelper.sendTodoTask(gameId, userId,
                                            TodoTaskGoldRain(prizeRewardTips))

                mo = self.buildQueryPrizeResponse(gameId, userId, clientId)
                router.sendToUser(mo, userId)
            else:
                TodoTaskHelper.sendTodoTask(gameId, userId,
                                            TodoTaskShowInfo('奖励已经领取', True))
            datachangenotify.sendDataChangeNotify(gameId, userId,
                                                  ['free', 'promotion_loc'])
        except TYBizException, e:
            TodoTaskHelper.sendTodoTask(gameId, userId,
                                        TodoTaskShowInfo(e.message, True))
Beispiel #26
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
Beispiel #27
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
Beispiel #28
0
def handleShippingResultCoupon(userId, record, result):
    timestamp = pktimestamp.getCurrentTimestamp()
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    if result == RESULT_OK:
        record.state = TYExchangeRecord.STATE_SHIPPING_SUCC
    elif result == RESULT_SHIPPINGFAIL_RETURN:
        record.state = TYExchangeRecord.STATE_SHIPPING_FAIL_RETURN
        count = record.params.get('count', 0)
        userAssets.addAsset(HALL_GAMEID, hallitem.ASSET_COUPON_KIND_ID, count,
                            timestamp, 'WX_GET_CASH_BACK', count)
        # 历史提现记录对应减掉这个数额
        userdata.incrAttr(userId, 'exchangedCoupon', -abs(count))
    elif result == RESULT_SHIPPINGFAIL:
        record.state = TYExchangeRecord.STATE_SHIPPING_FAIL
    else:
        assert (0)

    amount = record.params.get('amount', 0)
    if result != RESULT_OK:
        mail = '您申请提现%.2f元,审核未通过,抱歉。' % (amount)
    else:
        mail = '您已成功提现%.2f元,请查收。' % (amount)
    pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail)
    datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message')

    return record
Beispiel #29
0
def handleAuditResultCoupon(userId, record, result):
    timestamp = pktimestamp.getCurrentTimestamp()
    userAssets = hallitem.itemSystem.loadUserAssets(userId)

    if result == RESULT_AUDITSUCC:
        record.state = TYExchangeRecord.STATE_ACCEPT
    elif result == RESULT_REJECT:
        record.state = TYExchangeRecord.STATE_REJECT
    elif result == RESULT_REJECT_RETURN:
        record.state = TYExchangeRecord.STATE_REJECT_RETURN
        count = record.params.get('count', 0)
        userAssets.addAsset(HALL_GAMEID, hallitem.ASSET_COUPON_KIND_ID, count,
                            timestamp, 'WX_GET_CASH_BACK', count)
        # 历史提现记录对应减掉这个数额
        userdata.incrAttr(userId, 'exchangedCoupon', -abs(count))
    else:
        assert (0)

    if result in (RESULT_REJECT, RESULT_REJECT_RETURN):
        mail = '您申请提现%.2f元,审核未通过,抱歉。' % (record.params.get('amount', 0))
        pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId,
                       mail)
        datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message')

    return record
Beispiel #30
0
 def sendReward(self, gameId, userId, clientId, contentItem, eventId,
                intEventParam):
     try:
         timestamp = pktimestamp.getCurrentTimestamp()
         userAssets = hallitem.itemSystem.loadUserAssets(userId)
         assetKind, count, final = userAssets.addAsset(
             gameId, contentItem.assetKindId, contentItem.count, timestamp,
             eventId, intEventParam)
         if assetKind.keyForChangeNotify:
             datachangenotify.sendDataChangeNotify(
                 gameId, userId, [assetKind.keyForChangeNotify])
         contentStr = TYAssetUtils.buildContent((assetKind, count, final))
         ftlog.info(
             'ActivityPCHandler.sendReward gameId=', gameId, 'userId=',
             userId, 'clientId=', clientId, 'reward=',
             '(%s,%s)' % (contentItem.assetKindId, contentItem.count),
             'eventId=', eventId, 'intEventParam=', intEventParam)
         return '恭喜您获得%s!' % (contentStr)
     except TYBizException, e:
         ftlog.warn(
             'ActivityPCHandler.sendReward gameId=', gameId, 'userId=',
             userId, 'clientId=', clientId, 'reward=',
             '(%s,%s)' % (contentItem.assetKindId, contentItem.count),
             'eventId=', eventId, 'intEventParam=', intEventParam, 'err=',
             str(e))
         return '领取失败'
Beispiel #31
0
 def addUserItemByKindId(cls, userId, gameId, clientId, kindId, count):
     timestamp = pktimestamp.getCurrentTimestamp()
     userAssets = hallitem.itemSystem.loadUserAssets(userId)
     calcGameId = strutil.getGameIdFromHallClientId(clientId)
     userAssets.addAsset(calcGameId, kindId, count, timestamp, 'MAJIANG_FANGKA_INVITE_REWARD', 0)
     datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
     ftlog.debug('addUserItemByKindId userId:', userId, ' gameId:', gameId, 'kindId', kindId, 'count', count)
Beispiel #32
0
    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
Beispiel #33
0
def subscribeMember(gameId,
                    userId,
                    timestamp,
                    eventId,
                    intEventParam,
                    roomId=0,
                    tableId=0,
                    roundId=0,
                    param01=0,
                    param02=0):
    status = loadSubMemberStatus(userId)
    deliveryDays = _checkSubMember(gameId,
                                   userId,
                                   timestamp,
                                   status,
                                   eventId,
                                   intEventParam,
                                   roomId=roomId,
                                   tableId=tableId,
                                   roundId=roundId,
                                   param01=param01,
                                   param02=param02)
    if deliveryDays > 0:
        datachangenotify.sendDataChangeNotify(gameId, userId,
                                              ['promotion_loc'])
    return status
Beispiel #34
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
Beispiel #35
0
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
Beispiel #36
0
def incrUserChip(userId, gameId, chip, eventId, intEventParam, clientId):
    trueDelta, final = userchip.incrChip(userId, gameId, chip,
                                         daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                         eventId, intEventParam, clientId)
    if trueDelta != 0:
        datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
    return trueDelta, final
Beispiel #37
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
Beispiel #38
0
def _sendReward(userId, invitee, count):
    userchip.incrCoupon(userId, HALL_GAMEID, count, ChipNotEnoughOpMode.NOOP,
                        'HALL_INVITEE_TASK_REWARD', invitee, None)
    datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'coupon')

    ftlog.info('SendInviteeTaskReward', 'userId=', userId, 'invitee=', invitee,
               'count=', count)
    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
Beispiel #40
0
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
Beispiel #41
0
    def on_praise_friend(cls, gameId, uid, clientId, mo):
        code = mo.getResult('code', 0)
        # vip = mo.getResult('vip')
        if code == 0:
            friend_uid = int(mo.getResult('friend_uid'))
            nick_name = mo.getResult('nick_name')
            friend_nick_name = mo.getResult('friend_nick_name')
            my_add_charm = mo.getResult('my_add_charm')
            friend_add_charm = mo.getResult('friend_add_charm')
            my_charm = mo.getResult('my_charm')
            friend_charm = mo.getResult('friend_charm')

            msg1 = '给"' + friend_nick_name + '"点赞获得' + str(my_add_charm) + '个魅力值'
            msg2 = '"' + nick_name + '"给您点赞获得' + str(friend_add_charm) + '个魅力值'
            from poker.entity.biz.message import message
            message.send(gameId, message.MESSAGE_TYPE_SYSTEM, int(uid), msg1)
            message.send(gameId, message.MESSAGE_TYPE_SYSTEM, int(friend_uid), msg2)
            ftlog.debug('on praise friend.... ' + msg1)
            ftlog.debug('on praise friend.... ' + msg2)

            datachangenotify.sendDataChangeNotify(gameId, uid, 'charm')

            from hall.entity.hallranking import rankingSystem, TYRankingInputTypes
            timestamp = pktimestamp.getCurrentTimestamp()
            rankingSystem.setUserByInputType(gameId, TYRankingInputTypes.CHARM,
                                             uid, my_charm, timestamp)
            rankingSystem.setUserByInputType(gameId, TYRankingInputTypes.CHARM,
                                             friend_uid, friend_charm, timestamp)
            # 历史获赞次数
            history_praised_num = gamedata.incrGameAttr(friend_uid, gameId, 'history_praised_num', 1)
            mo.setResult('friend_history_praised_num', history_praised_num)

        if code != 2:
            return

        from hall.entity.todotask import TodoTaskPayOrder, TodoTaskShowInfo
        from hall.entity.todotask import TodoTaskHelper
        from hall.entity import hallvip, hallitem

        user_vip = hallvip.userVipSystem.getUserVip(uid)
        delta_exp = user_vip.deltaExpToNextLevel()

        product, _ = hallstore.findProductByContains(gameId, uid, clientId,
                                                     ['coin'], None,
                                                     hallitem.ASSET_CHIP_KIND_ID,
                                                     delta_exp * 1000)

        pay_order = TodoTaskPayOrder(product)
        if user_vip == 0:
            msg = '点赞次数已达今日上限,开通VIP可提高点赞次数上限获得更多福利哦~'
            btnTxt = '开通VIP'
        else:
            msg = '点赞次数已达今日上限,升级VIP等级可提高点赞次数上限获得更多福利哦~'
            btnTxt = '升级VIP'
        dialog_task = TodoTaskShowInfo(msg, True)
        dialog_task.setSubCmd(pay_order)
        dialog_task.setSubText(btnTxt)
        TodoTaskHelper.sendTodoTask(gameId, uid, [dialog_task])
Beispiel #42
0
def flipCard(gameId, userId, clientId, roomId, paddingsCount):
    '''
    翻牌
    @return: flippedCard, paddingsCardList
    '''
    timestamp = pktimestamp.getCurrentTimestamp()
    ctx = FlipCardContext(gameId, userId, clientId, roomId)

    flipableCard = _flipCardPolicyTable.selectPolicy(ctx).randomCard()
    if ftlog.is_debug():
        ftlog.debug('FlipCardService.flipCard gameId=', gameId,
                    'userId=', userId,
                    'roomId=', roomId,
                    'roomMinChip=', ctx.roomMinChip,
                    'userAllChip=', ctx.userAllChip,
                    'userVipLevel=', ctx.userVip.vipLevel.level,
                    'minBuyChip=', ctx.minBuyChip,
                    'flipableCard=', flipableCard)

    flippedCard = flipableCard.flip(ctx)
    if not flippedCard:
        ftlog.debug('FlipCardService.flipCard gameId=', gameId,
                    'userId=', userId,
                    'roomId=', roomId,
                    'roomMinChip=', ctx.roomMinChip,
                    'userAllChip=', ctx.userAllChip,
                    'userVipLevel=', ctx.userVip.vipLevel.level,
                    'minBuyChip=', ctx.minBuyChip,
                    'flipableCard=', flipableCard,
                    'err=', 'NoFlippedCard')
        raise FlipCardException(-1, 'System error')

    if isinstance(flippedCard, FlippedCardAsset):
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        userAssets.addAsset(gameId, flippedCard.assetKind.assetKindId,
                            timestamp, 'ACTIVITY_FAN_PAI', 0)
        if flippedCard.assetKind.keyForChangeNotify:
            datachangenotify.sendDataChangeNotify(gameId, userId, flippedCard.assetKind.keyForChangeNotify)
    paddingsCardList = _paddingCard(ctx, paddingsCount)

    if ftlog.is_debug():
        paddingsCardsStrs = []
        for paddingsCard in paddingsCardList:
            paddingsCardsStrs.append(str(paddingsCard))
        ftlog.debug('FlipCardService.flipCard gameId=', gameId,
                    'userId=', userId,
                    'roomId=', roomId,
                    'roomMinChip=', ctx.roomMinChip,
                    'userAllChip=', ctx.userAllChip,
                    'userVipLevel=', ctx.userVip.vipLevel.level,
                    'minBuyChip=', ctx.minBuyChip,
                    'flipableCard=', flipableCard,
                    'paddingsCards', paddingsCardsStrs)

    while len(paddingsCardList) < paddingsCount:
        paddingsCardList.append(flippedCard)

    return flippedCard, paddingsCardList
Beispiel #43
0
def supplementCheckin(userId, gameId, clientId, supplementDate=None, nowDate=None):
    '''
    用户补签
    @param userId: 用户ID
    @param supDate: 补签日期,如果为None则表示补签最近一天
    @param nowDate: 当前日期
    @return: MonthCheckinStatus
    '''
    from hall.game import TGHall

    nowDate = nowDate or datetime.now().date()
    status = loadStatus(userId, nowDate)
    if isScriptDoGetReward(userId):
        raise AlreadyCheckinException('亲,签到奖励准备中,请玩几把再来领取吧!')
    # 检查最大补签数
    if status.supplementCheckinCount >= getConf().get("maxSupplementCheckinCount"):
        raise SupplementOverException()

    if supplementDate:
        if not pktimestamp.isSameMonth(supplementDate, status.curDate):
            raise InvalidSupplementDateException()
    else:
        holeDateList = status._getHoleDateList()
        if not holeDateList:
            raise AlreadyCheckinException()
        supplementDate = holeDateList[0]

    if not status.addSupplementCheckinDate(supplementDate):
        raise AlreadyCheckinException()

    # 减少抽奖卡,消耗成功之后,发放奖励。
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    timestamp = pktimestamp.getCurrentTimestamp()

    _, consumeCount, _final = userAssets.consumeAsset(gameId, 'item:4168', 1,
                                                      timestamp, 'HALL_CHECKIN', 0)
    if consumeCount < 1:
        result = {}
        result["lessCard"] = "您的补签卡不足"
        return 1, result
    datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
    _saveStatus(status)

    userToGetGift(userId, gameId, state=0)
    # 领取累计奖励
    _, clientVer, _ = strutil.parseClientId(clientId)
    if clientVer <= 3.76:
        # 自动领奖
        days = status.allCheckinCount
        getDaysReward(userId, days, gameId, nowDate)

    TGHall.getEventBus().publishEvent(MonthSupCheckinOkEvent(userId, gameId, status, nowDate))

    ftlog.debug('supplementCheckin userId =', userId
                , 'gameId =', gameId
                , 'clientId =', clientId
                , 'noeDate =', nowDate)
    return 0, status
Beispiel #44
0
 def doAssistanceGet(self, gameId, userId):
     try:
         _consumeCount, finalCount, sendChip = hallvip.userVipSystem.gainAssistance(gameId, userId)
         if sendChip > 0:
             datachangenotify.sendDataChangeNotify(gameId, userId, 'udata')
         todotask = TodoTaskGoldRain(VipHelper.buildGotAssistanceDesc(finalCount, sendChip))
         TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
     except TYAssistanceChipTooMuchException, e:
         ftlog.warn('ERROR, doAssistanceGet', gameId, userId, e.chip, e.upperChipLimit, e.errorCode, e.message)
Beispiel #45
0
    def exchangeCouponItem(self, userId, couponId, **kwargs):
        couponItem = self.findCouponItem(couponId)
        if not couponItem:
            if ftlog.is_debug():
                ftlog.debug('CouponService.exchangeCouponItem userId=', userId,
                            'couponId=', couponId,
                            'kwargs=', kwargs,
                            'gameId=', self.gameId,
                            'coupons=', self._couponItemMap.keys())
            raise TYBizException(-1, 'Not found couponId %s' % (couponId))

        if (couponItem.itemType == CouponItem.TYPE_PHONE_CARD
            and not kwargs.get('phone')):
            # 检查chargePhone参数
            raise TYBizException(-1, 'Please input phone number')

        # 减奖券
        trueDelta, final = pkuserchip.incrCoupon(userId, self.gameId, -couponItem.couponCount,
                                                 pkdaoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                                 0, 0, 0)
        if -trueDelta < couponItem.couponCount:
            raise TYBizException(-1, 'Coupon not enough')

        if couponItem.itemType == CouponItem.TYPE_PHONE_CARD:
            phone = kwargs.get('phone')
            isCtyOk = sdkclient.couponCharge(self.gameId, userId, phone, '', '',
                                             couponItem.couponCount, couponItem.itemCount)
            if isCtyOk:
                mail = couponItem.mailOk
            else:
                mail = couponItem.mailFail
            if mail:
                mail = strutil.replaceParams(mail, {
                    'couponCount': str(couponItem.couponCount),
                    'itemCount': str(couponItem.itemCount),
                    'itemName': couponItem.itemName,
                    'phone': phone,
                    'qqGroup': self._qqGroup
                })
                pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail)
                datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message')
        elif couponItem.itemType == CouponItem.TYPE_ID_CHIP:
            pkuserchip.incrChip(userId, self.gameId, couponItem.itemCount,
                                pkdaoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                0, 0, 0)
            mail = couponItem.mailOk
            if mail:
                mail = strutil.replaceParams(mail, {
                    'couponCount': str(couponItem.couponCount),
                    'itemCount': str(couponItem.itemCount),
                    'itemName': couponItem.itemName,
                    'qqGroup': self._qqGroup
                })
                pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail)
                datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message')
        return trueDelta, final
Beispiel #46
0
 def doGameGetMemberReward(self, userId, gameId, clientId):
     userAssets = hallitem.itemSystem.loadUserAssets(userId)
     userBag = userAssets.getUserBag()
     memberCardItem = userBag.getItemByKindId(hallitem.ITEM_MEMBER_NEW_KIND_ID)
     timestamp = pktimestamp.getCurrentTimestamp()
     if memberCardItem and memberCardItem.canCheckin(timestamp):
         checkinAction = memberCardItem.itemKind.findActionByName('checkin')
         checkinAction.doAction(gameId, userAssets, memberCardItem, timestamp, {})
         datachangenotify.sendDataChangeNotify(gameId, userId, 'free')
         TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain('恭喜您领取了今天的会员福利'))
Beispiel #47
0
def sendSoldierRewardToUser(userId, gameId, reward):
    '''
        将本期的奖品进行下发
    '''
    changed = []
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    assetKind, _addCount, _final = userAssets.addAsset(gameId, reward.get('itemId'), reward.get('count'),
                                                       int(time.time()), 'ROULETTE_BIGREWARD', 0)
    if assetKind.keyForChangeNotify:
        changed.append(assetKind.keyForChangeNotify)
    datachangenotify.sendDataChangeNotify(gameId, userId, changed)
Beispiel #48
0
def sendToUserALotteryCard(userId, gameId, clientId):
    '''
        用户第一次使用轮盘功能,赠送一张抽奖卡
    '''
    changed = []
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    assetKind, _addCount, _final = userAssets.addAsset(gameId, hallitem.ASSET_ITEM_LOTTERY_CARD_ID, 1, int(time.time()),
                                                       'ROULETTE_SILVER', 0)
    if assetKind.keyForChangeNotify:
        changed.append(assetKind.keyForChangeNotify)
    datachangenotify.sendDataChangeNotify(gameId, userId, changed)
Beispiel #49
0
def _onChargeNotify(event):
    ftlog.info('hallstore._onChargeNotify gameId=', event.gameId,
               'userId=', event.userId,
               'diamonds=', event.diamonds,
               'rmbs=', event.rmbs,
               'firstRechargeThreshold=', storeSystem.firstRechargeThreshold)
    if event.diamonds >= storeSystem.firstRechargeThreshold:
        count = pkgamedata.incrGameAttr(event.userId, HALL_GAMEID, 'first_recharge', 1)
        if count == 1:
            TGHall.getEventBus().publishEvent(UserFirstRecharedEvent(HALL_GAMEID, event.userId))
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, event.userId, 'promotion_loc')
Beispiel #50
0
def presentItemByUnitsCount(gameId, userId, fromUserId, kindId, count, receiveMail):
    itemKind = hallitem.itemSystem.findItemKind(kindId)
    if not itemKind:
        return False
    userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
    userBag.addItemUnitsByKind(gameId, itemKind, count,
                               pktimestamp.getCurrentTimestamp(), fromUserId,
                               'ACCEPT_PRESENT_ITEM', fromUserId)
    if receiveMail:
        pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, receiveMail)
    datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
    return True
Beispiel #51
0
    def doSupCheckinMonth(self, gameId, userId, clientId):
        try:
            mo = MsgPack()
            typeData, status = monthcheckin.supplementCheckin(userId, gameId, clientId)

            mo.setCmd('month_checkin')
            if not status:
                mo.setResult('userId', userId)
                mo.setResult('tip', 'maybe is script')
                ftlog.info('maybe is script userId =', userId)
                router.sendToUser(mo, userId)
                return
            if typeData == 1:
                mo.setResult('action', 'supCheckin')
                mo.setResult('lessCard', status['lessCard'])
                router.sendToUser(mo, userId)
            else:
                mo.setResult('action', 'supCheckin')
                mo.setResult('supCheckinCount', monthcheckin.getSupplementCheckinCardCount(userId, gameId))
                mo.setResult('checkinDateList', [d.strftime('%Y%m%d') for d in status.checkinDateList])
                mo.setResult('supplementCheckinDateList',
                             [d.strftime('%Y%m%d') for d in status.supplementCheckinDateList])
                mo.setResult('rewardDaysList', status.rewardDaysList)
                daysRewards = []
                for _days, rewardContent in enumerate(monthcheckin.getConf().get('daysRewards', [])):
                    reward = rewardContent.get('reward')
                    monthRange = monthcheckin.getMonthRange()
                    if rewardContent.get('days') < monthRange:
                        monthRange = rewardContent.get('days')
                    daysRewards.append({
                        'days': monthRange,
                        'desc': reward.get('desc'),
                        'picUrl': reward.get('picUrl'),
                        'state': self.calcDaysRewardState(status, monthRange)
                    })
                    ftlog.debug('doSupCheckinMonth daysRewards monthRange =', monthRange)
                mo.setResult('daysRewards', daysRewards)
                mo.setResult('descSucess', '恭喜你获得500金币+1幸运卡')
                ftlog.debug('doSupCheckinMonth usereId =', userId
                            , 'gameId =', gameId
                            , 'clientId =', clientId
                            , 'checkinDateList =', [d.strftime('%Y%m%d') for d in status.checkinDateList]
                            , 'supplementCheckinDateList =',
                            [d.strftime('%Y%m%d') for d in status.supplementCheckinDateList])
                router.sendToUser(mo, userId)
                datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc'])
        except MonthCheckinException, e:
            mo = MsgPack()
            mo.setCmd('month_checkin')
            mo.setResult('action', 'supCheckin')
            mo.setError(e.errorCode, e.message)
            router.sendToUser(mo, userId)
            ftlog.debug('dosupCheckin ' + str(e))
Beispiel #52
0
def sendGiftToUser(item, userId, gameId):
    ftlog.debug('dayToGift userId =', userId
                , 'item =', item
                , 'gameId =', gameId
                , 'userId =', userId)
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    for _k, v in enumerate(item):
        changed = []
        assetKind, _addCount, _final = userAssets.addAsset(9999, v.get("itemId"), v.get("count"), int(time.time()),
                                                           'HALL_CHECKIN', 0)
        if assetKind.keyForChangeNotify:
            changed.append(assetKind.keyForChangeNotify)
        datachangenotify.sendDataChangeNotify(gameId, userId, changed)
Beispiel #53
0
def unsubscribeMember(gameId, userId, isTempVipUser, timestamp, eventId, intEventParam):
    from hall.entity import hallitem
    status = loadSubMemberStatus(userId)
    _checkSubMember(gameId, userId, timestamp, status, eventId, intEventParam)
    if status.subDT:
        subDT = status.subDT
        nowDT = datetime.fromtimestamp(timestamp)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        balance = userAssets.balance(gameId, hallitem.ASSET_ITEM_MEMBER_NEW_KIND_ID, timestamp)
        removeDays = 0
        if isTempVipUser:
            # 用户首次购买72小时之内如果退订则扣除剩余会员天数
            removeDays = max(0, (status.expiresDT.date() - nowDT.date()).days)
            status.deliveryDT = None
            status.subDT = None
            status.expiresDT = None
        # # 退订会员权益不消失
        #         else:
        #             # 根据平台中心建议新增:用户退订后会员有效期最长维持到当月最后一天
        #             limitDT = datetime.fromtimestamp(pktimestamp.getDeltaMonthStartTimestamp(timestamp, 1))
        #             # 最多剩余多少天
        #             maxKeep = max(0, (limitDT.date() - nowDT.date()).days)
        #             status.subDT = None
        #             status.deliveryDT = None
        #             status.expiresDT = (nowDT + timedelta(days=maxKeep)).replace(hour=0, minute=0, second=0, microsecond=0)
        #             removeDays = max(0, balance - maxKeep)

        _saveSubMemberStatus(userId, status)
        removeDays = min(balance, removeDays)

        if removeDays > 0:
            changed = []
            _assetKind, _consumeCount, final = userAssets.consumeAsset(gameId, hallitem.ASSET_ITEM_MEMBER_NEW_KIND_ID,
                                                                       removeDays, timestamp, eventId, intEventParam)
            if final <= 0:
                changed.append('promotion_loc')
            changed.append('item')
            datachangenotify.sendDataChangeNotify(gameId, userId, changed)
        ftlog.info('hallsubmember.unsubscribeMember gameId=', gameId,
                   'userId=', userId,
                   'isTempVipUser='******'isSub=', status.isSub,
                   'unsubDesc=', status.unsubDesc,
                   'expiresDT=', status.expiresDT.strftime('%Y-%m-%d %H:%M:%S') if status.expiresDT else None,
                   'eventId=', eventId,
                   'intEventParam=', intEventParam,
                   'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'),
                   'subTime=', subDT.strftime('%Y-%m-%d %H:%M:%S') if subDT else None,
                   'balance=', balance,
                   'removeDays=', removeDays)
Beispiel #54
0
 def _loadTaskModel(self, userTaskUnit, timestamp):
     ftlog.debug('NewUserTaskSystem._loadTaskModel userId=', userTaskUnit.userId,
                 'taskIds=', [task.kindId for task in userTaskUnit.taskList])
     taskModel = NewUserTaskModel(self, userTaskUnit)
     if not taskModel.userTaskUnit.taskList:
         status = neituiguang.loadStatus(userTaskUnit.userId, timestamp)
         # 根据用户状态初始化任务
         if status.inviter and status.isNewUser:
             ftlog.info('NewUserTaskSystem._loadTaskModel userId=', userTaskUnit.userId,
                        'inviter=', status.inviter.userId)
             poolIndex = 0 if status.inviter.userId == 0 else 1
             init = taskModel.initTasksIfNeed(poolIndex, timestamp)
             if init:
                 datachangenotify.sendDataChangeNotify(HALL_GAMEID, userTaskUnit.userId, ['free', 'promotion_loc'])
     return taskModel
Beispiel #55
0
    def consumeItemByKindId(cls, userId, gameId, kindId, count, eventId, roomId=0):
        """道具消费
        """
        itemKind = hallitem.itemSystem.findItemKind(kindId)
        if not itemKind:
            return False
        userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
        timestamp = pktimestamp.getCurrentTimestamp()
        consumeCount = userBag.consumeUnitsCountByKind(gameId,
                                                       itemKind, count, timestamp, eventId, roomId)
        datachangenotify.sendDataChangeNotify(gameId, userId, 'item')
        if consumeCount < count:
            return False

        return True
Beispiel #56
0
 def onUserLogin(self, event):
     if not self._mailWhenCanExchange:
         return
     _, clientVer, _ = strutil.parseClientId(event.clientId)
     if clientVer < 3.0:
         return
     if not event.dayFirst or event.gameId != HALL_GAMEID:
         return
     couponItem = self.findMinCouponItem([CouponItem.TYPE_PHONE_CARD])
     if not couponItem:
         return
     userCouponCount = pkuserchip.getCoupon(event.userId)
     if userCouponCount >= couponItem.couponCount:
         pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, event.userId, self._mailWhenCanExchange)
         datachangenotify.sendDataChangeNotify(self.gameId, event.userId, 'message')
Beispiel #57
0
def doGoldLottery(userId, gameId, clientId, number):
    '''
        金盘抽奖
    '''
    if number <= 0 or number > 50:
        ftlog.error('doGoldLottery number best be > 0 or <= 50, the msg is fake')
        return

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

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

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

    # 统计需求
    ftlog.hinfo('doGoldLottery.userId=', userId,
                'gameId=', gameId,
                'clientId=', clientId,
                'number=', number,
                'rouletteType=', 2,
                'rewardItem=', items)
    TGHall.getEventBus().publishEvent(TYEventRouletteDiamond(userId, gameId, number))
    return result
Beispiel #58
0
def handleExchangeAuditResult(userId, exchangeId, result):
    '''
    处理审核结果
    '''
    record = loadRecord(userId, exchangeId)
    if not record:
        raise TYUnknownExchangeOrder()

    if record.state != TYExchangeRecord.STATE_AUDIT:
        raise TYBadStateExchangeOrder()

    userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
    item = userBag.findItem(record.itemId)

    if not isinstance(item, TYExchangeItem):
        raise TYBizException(-1, '系统错误')

    if item.state != TYExchangeItem.STATE_AUDIT:
        raise TYBizException(-1, '道具状态错误')

    ftlog.debug('hallexchange.handleExchangeAuditResult userId=', userId,
                'exchangeId=', exchangeId,
                'result=', result)

    timestamp = pktimestamp.getCurrentTimestamp()
    if result == RESULT_OK:
        record.state = TYExchangeRecord.STATE_ACCEPT
        userBag.removeItem(HALL_GAMEID, item, timestamp, 'EXCHANGE', item.kindId)
    else:
        record.state = TYExchangeRecord.STATE_REJECT
        if result == RESULT_REJECT_RETURN:
            item.state = TYExchangeItem.STATE_NORMAL
            userBag.updateItem(HALL_GAMEID, item, timestamp)
        else:
            userBag.removeItem(HALL_GAMEID, item, timestamp, 'EXCHANGE', item.kindId)
    itemDisPlayName = item.itemKind.displayName
    exchangeDesc = record.params.get("desc", '')
    if result == RESULT_OK:
        mail = "您申请用%s兑换(领取)%s,已成功为您办理,请查收。" % (itemDisPlayName, exchangeDesc)
    else:
        mail = "您申请用%s兑换(领取)%s,审核未通过,抱歉。" % (itemDisPlayName, exchangeDesc)
    ftlog.debug("handleExchangeAuditResult,mail:", mail)
    pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail)
    datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message')

    jstr = json.dumps(record.toDict())
    _saveRecordData(userId, exchangeId, jstr)
    return record
Beispiel #59
0
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