示例#1
0
 def _sendTaskReward(self, player, dropType, dropItem, broadcastUserIds):
     """
     发送任务奖励
     """
     dropItems = None
     if dropType == 1:  # 宝箱
         chestRewards = chest_system.getChestRewards(
             player.userId, dropItem)
         util.addRewards(player.userId,
                         chestRewards,
                         "BI_NFISH_NCMPTT_TASK_REWARDS",
                         roomId=self.table.roomId,
                         tableId=self.table.tableId)
         dropItems = {
             "chest": dropItem,
             "chestRewards": chestRewards,
             "chip": 0,
             "type": 0
         }
         from newfish.game import TGFish
         from newfish.entity.event import GainChestEvent
         from newfish.entity.chest.chest_system import ChestFromType
         event = GainChestEvent(player.userId, FISH_GAMEID, dropItem,
                                ChestFromType.Cmptt_Ncmptt_Bonus_Task)
         TGFish.getEventBus().publishEvent(event)
         # chest_system.newChestItem(player.userId, dropItem["name"], "BI_NFISH_NCMPTT_TASK_REWARDS", self.table.roomId)
     elif dropType == 2:  # 金币
         dropItems = {"chest": 0, "chip": dropItem["count"], "type": 1}
         rewards = [{"name": "tableChip", "count": dropItem["count"]}]
         util.addRewards(player.userId, rewards,
                         "BI_NFISH_NCMPTT_TASK_REWARDS", self.table.roomId)
     return dropItems
def getReturnerReward(userId, clientId, taskId):
    """
    领取回归豪礼
    """
    rewards = None
    returnerMission = getReturnerMissionData(userId)
    if returnerMission:
        for taskConf in config.getReturnerMissionConf("tasks"):
            if taskConf["taskId"] == taskId and taskId in returnerMission["tasks"]:
                if returnerMission["tasks"][taskId]["state"] == 2:
                    rewards = buildTaskRewards(taskConf["rewards"], returnerMission["userLevel"], returnerMission["vipExp"])
                    returnerMission["tasks"][taskId]["state"] = 3
                    break
    mo = MsgPack()
    mo.setCmd("returner_reward")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("taskId", taskId)
    mo.setResult("code", 0 if rewards else 1)
    if rewards:
        util.addRewards(userId, rewards, "BI_NFISH_RETURNER_REWARDS", int(taskId))
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.returnerMission, json.dumps(returnerMission))
        module_tip.cancelModuleTipEvent(userId, "returnerMission", taskId)
        mo.setResult("rewards", rewards)
    router.sendToUser(mo, userId)
示例#3
0
def sendGrandPrizeReward(roomId, tableId, userId, fId, coinCount, level,
                         seatId, fpMultiple):
    """
    发放巨奖奖励
    """
    try:
        rewards = [{"name": config.CHIP_KINDID, "count": coinCount}]
        room = gdata.rooms()[roomId]
        table = room.maptable[tableId]
        player = table.getPlayer(userId)

        msg = MsgPack()
        msg.setCmd("getGrandPrizeRewards")
        msg.setResult("gameId", FISH_GAMEID)
        msg.setResult("userId", userId)
        msg.setResult("fId", fId)
        msg.setResult("rewards", rewards)
        msg.setResult("level", level)
        msg.setResult("seatId", seatId)
        msg.setResult("fpMultiple", fpMultiple)
        GameMsg.sendMsg(msg, table.getBroadcastUids())

        if player:
            for bigRoomId in config.getGrandPrizeConf().get("roomIds", []):
                player.fireCost[str(bigRoomId)] = 0
            name = player.name
            player.addTableChip(coinCount, "BI_NFISH_GRAND_PRIZE")
            player.totalGainChip += coinCount
            # 深海巨奖触发幸运降临
            table.checkBigPrize(player,
                                coinCount // fpMultiple,
                                coinCount,
                                fpMultiple,
                                isGrandPriz=True)
        else:
            from poker.entity.dao import gamedata
            from newfish.entity.redis_keys import GameData
            fireCost = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                                GameData.fireCost, {})
            for bigRoomId in config.getGrandPrizeConf().get("roomIds", []):
                fireCost[str(bigRoomId)] = 0
            gamedata.setGameAttr(userId, FISH_GAMEID, GameData.fireCost,
                                 json.dumps(fireCost))
            name = util.getNickname(userId)
            util.addRewards(userId, rewards, "BI_NFISH_GRAND_PRIZE", roomId)

        leds = [
            "ID_LED_GRAND_PRIZE_1", "ID_LED_GRAND_PRIZE_2",
            "ID_LED_GRAND_PRIZE_3"
        ]
        if len(leds) > level >= 0:
            lang = util.getLanguage(userId)
            msg = config.getMultiLangTextConf(leds[level], lang=lang) % \
                  (name, config.getMultiLangTextConf(table.runConfig.title, lang=lang), util.formatScore(coinCount, lang=lang))
            user_rpc.sendLed(FISH_GAMEID, msg, id=leds[level], lang=lang)
    except Exception as e:
        ftlog.error("sendGrandPrizeReward", roomId, tableId, userId, fId,
                    coinCount, traceback.format_exc())
    return 0
示例#4
0
def v2DataTov3Data(userId, clientId):
    """
    v2版本用户属性继承到v3版本
    """
    # 金币数量调整
    totalChip = userchip.getUserChipAll(userId)
    incrChip = totalChip * 10 - totalChip
    userchip.incrChip(userId, FISH_GAMEID, incrChip, 0,
                      "BI_NFISH_NEW_USER_REWARDS", 0, clientId)

    # 处理宝藏相关数据
    from newfish.entity import treasure_system
    treasureList = config.getV2ToV3Conf("treasure")
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    for _, treasureConf in enumerate(treasureList):
        old_kindId = treasureConf["old_kindId"]
        new_kindId = treasureConf.get("new_kindId")
        ratio = treasureConf.get("ratio", 0)
        convert_kindId = treasureConf.get("convert_kindId")
        convert_num = treasureConf.get("convert_num", 999999)
        surplusCount = util.balanceItem(userId, old_kindId, userAssets)
        if surplusCount > 0:
            if new_kindId:
                treasureData = treasure_system.getTreasure(userId, new_kindId)
                if treasureData[treasure_system.INDEX_LEVEL] == 0:
                    treasureData[treasure_system.INDEX_LEVEL] = 1
                    treasure_system.setTreasure(userId, new_kindId,
                                                treasureData)
            if convert_kindId:
                convertNum = min(surplusCount, convert_num)
                convertNum = int(math.ceil(convertNum * ratio))
                rewards = [{"name": convert_kindId, "count": convertNum}]
                util.addRewards(userId, rewards, "BI_NFISH_NEW_USER_REWARDS",
                                old_kindId, surplusCount)
            consumeItems = [{"name": old_kindId, "count": surplusCount}]
            util.consumeItems(userId, consumeItems,
                              "BI_NFISH_NEW_USER_REWARDS")

    # 处理技能相关数据
    skillList = config.getV2ToV3Conf("skill")
    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    for _, skillConf in enumerate(skillList):
        old_kindId = skillConf["old_kindId"]
        ratio = skillConf.get("ratio", 0)
        convert_kindId = skillConf.get("convert_kindId")
        surplusCount = util.balanceItem(userId, old_kindId, userAssets)
        if surplusCount > 0:
            if convert_kindId:
                convertNum = int(math.ceil(surplusCount * ratio))
                rewards = [{"name": convert_kindId, "count": convertNum}]
                util.addRewards(userId, rewards, "BI_NFISH_NEW_USER_REWARDS",
                                old_kindId, surplusCount)
            consumeItems = [{"name": old_kindId, "count": surplusCount}]
            util.consumeItems(userId, consumeItems,
                              "BI_NFISH_NEW_USER_REWARDS")
示例#5
0
def getQuestRewards(userId, clientId, taskId):
    """
    领取单个主线任务奖励
    """
    mo = MsgPack()
    mo.setCmd("task")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("taskId", taskId)
    mo.setResult("action", "mainReward")
    code = 3
    taskConf = config.getMainQuestTaskConf(clientId, taskId)
    if taskConf:
        state = getTask(userId, taskId)[QuestIndex.State]
        if state == QuestState.Default:
            code = 2
        elif state == QuestState.Received:
            code = 1
        else:
            code = 0
            chestInfo = {}
            rewards = []
            rewards.extend(taskConf["normalRewards"])
            chestRewards = taskConf["chestRewards"]
            if chestRewards:
                chestId = chestRewards[0]["name"]
                chestInfo = chest_system.getChestInfo(chestId)
                _rewards = chest_system.getChestRewards(userId, chestId)
                rewards.extend(_rewards)
            setTask(
                userId, clientId, taskId,
                [QuestState.Received, int(time.time())])  # 领取任务奖励
            util.addRewards(userId, rewards, "BI_NFISH_MAIN_QUEST_REWARDS",
                            int(taskId))
            module_tip.cancelModuleTipEvent(userId, "mainquest", taskId)
            # 检查主线任务增加的星级能否解锁对应星级奖励.
            sectionId = getSectionId(taskId)
            sectionData = getSection(userId, sectionId)
            sectionConf = config.getMainQuestSectionConf(clientId, sectionId)
            totalStar = _getSectionStar(userId, clientId, sectionId)
            for val in sectionConf["starRewards"]:
                if totalStar >= val["star"] and val["star"] not in sectionData[
                        SectionIndex.TakenStars]:
                    module_tip.addModuleTipEvent(userId, "mainquest",
                                                 "star_%d" % val["star"])
            mo.setResult("chestInfo", chestInfo)  # 宝箱奖励
            mo.setResult("rewards", rewards)
            bireport.reportGameEvent("BI_NFISH_GE_MAIN_QUEST_TASKID", userId,
                                     FISH_GAMEID, 0, 0, 0, 0, 0, 0, [taskId],
                                     clientId)
    mo.setResult("code", code)
    router.sendToUser(mo, userId)
    pushCurrTask(userId)
示例#6
0
 def _sendTaskReward(self, player, dropType, dropItem):
     """
     发送任务奖励
     """
     if dropType == 1:  # 金币
         dropItems = {"chip": dropItem["count"]}
         rewards = [{"name": "tableChip", "count": dropItem["count"]}]
         util.addRewards(player.userId, rewards,
                         "BI_NFISH_TIDE_TASK_REWARDS", self.table.roomId)
     else:
         util.addRewards(player.userId, [dropItem],
                         "BI_NFISH_TIDE_TASK_REWARDS", self.table.roomId)
         dropItems = dropItem
     return dropItems
示例#7
0
def getShareTaskRewards(userId, taskId):
    """
    领取分享好礼奖励
    """
    code = 1
    chestId = 0
    rewards = []
    eventId = "BI_NFISH_INVITE_TASK_REWARDS"
    if taskId == 0:
        isReceiveReward = weakdata.getDayFishData(userId, "shareGroupReward", 0)
        shareGroupIds = weakdata.getDayFishData(userId, "shareGroupIds", [])
        shareGroupTotalCount = config.getCommonValueByKey("shareGroupTotalCount")
        if isReceiveReward == 1 and len(shareGroupIds) >= shareGroupTotalCount:
            rewards = config.getCommonValueByKey("shareGroupRewards")
            from newfish.entity.chest import chest_system
            for reward in rewards:
                kindId = reward["name"]
                if util.isChestRewardId(kindId):
                    chestId = kindId
                    rewards = chest_system.getChestRewards(userId, kindId)
                    code = chest_system.deliveryChestRewards(userId, kindId, rewards, eventId)
                else:
                    code = util.addRewards(userId, [reward], eventId)
            weakdata.setDayFishData(userId, WeakData.shareGroupReward, 2)
    else:
        inviteList = refreshInviteData(userId)
        for _, inviteData in enumerate(inviteList):
            if inviteData["inviteId"] == taskId and not inviteData.get("receiveTime"):
                if inviteData.get("isAppUser", 0) == 1:
                    continue
                if inviteData.get("isNewUser"):
                    rewards = config.getCommonValueByKey("newUserInviteFriendRewards")
                else:
                    rewards = config.getCommonValueByKey("inviteFriendRewards")
                code = util.addRewards(userId, rewards, eventId)
                inviteData["receiveTime"] = int(time.time())
                break
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.inviteList, json.dumps(inviteList))
    message = MsgPack()
    message.setCmd("share_task_receive")
    message.setResult("gameId", FISH_GAMEID)
    message.setResult("userId", userId)
    message.setResult("taskId", taskId)
    message.setResult("code", code)
    if code == 0:
        module_tip.cancelModuleTipEvent(userId, "invite", taskId)
        message.setResult("chestId", chestId)
        message.setResult("rewards", rewards)
    router.sendToUser(message, userId)
示例#8
0
def executeChestAction(userId, order, actionType):
    """
    对背包中的宝箱执行行为
    """
    rewards = []
    userBag, chestItem, openingChestItem, nextOpeningChestItem = getChestItemDetail(userId, order)
    if actionType in [ChestAction.NormalOpen, ChestAction.AtOnceOpen]:  # [普通开启, 立即开启]
        if not chestItem:
            ftlog.info("openChest->not chestItem", userId)
            return 1, rewards
        if actionType == ChestAction.NormalOpen and chestItem.state != ChestState.Opened:
            ftlog.error("openChest->state error", userId)
            return 2, rewards
        if actionType == ChestAction.AtOnceOpen:    # 立即开启宝箱,执行扣金币操作
            chestTimeLeft = chestItem.beginTime + chestItem.totalTime - pktimestamp.getCurrentTimestamp()
            if chestTimeLeft > 0:
                needCoin = _needCoinAsOpenChest(chestItem.chestId, chestTimeLeft)
                chip = userchip.getChip(userId)
                if chip < needCoin:
                    ftlog.debug("openChest->chip not enough")
                    return 3, rewards
                util.addRewards(userId, [{"name": config.CHIP_KINDID, "count": -abs(needCoin)}], "BI_NFISH_ATONCE_OPEN_CHEST")
                # 修改下个宝箱的状态及时间
                if chestItem == openingChestItem and nextOpeningChestItem:
                    nextOpeningChestItem.state = ChestState.Opening
                    nextOpeningChestItem.beginTime = pktimestamp.getCurrentTimestamp()
                    userBag.updateItem(FISH_GAMEID, nextOpeningChestItem, pktimestamp.getCurrentTimestamp())
        # 发放宝箱奖励
        rewards = getChestRewards(userId, chestItem.chestId)
        deliveryChestRewards(userId, chestItem.chestId, rewards)
        # 删除已开启宝箱
        userBag.removeItem(FISH_GAMEID, chestItem, pktimestamp.getCurrentTimestamp(), "ITEM_USE", actionType)
        # 打开宝箱事件
        from newfish.game import TGFish
        from newfish.entity.event import OpenChestEvent
        event = OpenChestEvent(userId, FISH_GAMEID, chestItem.chestId, actionType)
        TGFish.getEventBus().publishEvent(event)
    elif actionType == ChestAction.Discard: # 丢弃宝箱
        # 获得宝箱开启倒计时
        chestTimeLeft = chestItem.beginTime + chestItem.totalTime - pktimestamp.getCurrentTimestamp()
        if chestTimeLeft > 0:
            # 修改下个宝箱的状态及时间
            if chestItem == openingChestItem and nextOpeningChestItem:
                nextOpeningChestItem.state = ChestState.Opening
                nextOpeningChestItem.beginTime = pktimestamp.getCurrentTimestamp()
                userBag.updateItem(FISH_GAMEID, nextOpeningChestItem, pktimestamp.getCurrentTimestamp())
        # 删除已丢弃宝箱
        userBag.removeItem(FISH_GAMEID, chestItem, pktimestamp.getCurrentTimestamp(), "ITEM_USE", actionType)
    return 0, rewards
示例#9
0
def sendFishCheckinRewardInfo(userId, day):
    """
    领取签到奖励
    """
    mo = MsgPack()
    mo.setCmd("fishCheckinReward")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    ts = int(time.time())
    code = 1
    if util.isFinishAllNewbieTask(userId):
        # kindId, rewards, checkinDay = getTodayCheckinRewards(userId)
        # if kindId and rewards :
        #     code = util.addRewards(userId, rewards, "BI_NFISH_CHECKIN_REWARDS")
        #     if code == 0:
        #         finishCheckin(userId, rewards, checkinDay)
        #         mo.setResult("kindId", kindId)
        #         mo.setResult("rewards", rewards)
        checkinDay, totalRewards, rd = getTodayCheckinRewards(userId)
        if totalRewards:
            code = util.addRewards(userId, totalRewards,
                                   "BI_NFISH_CHECKIN_REWARDS")
            finishCheckin(userId, totalRewards, checkinDay, ts=ts)
            for k, v in rd.iteritems():
                mo.setResult(k, v)
            mo.setResult("totalRewards", totalRewards)
            if code != 0:
                ftlog.error("checkin, userId =", userId, "day =", day,
                            "checkinday =", checkinDay, "rd =", rd)
    mo.setResult("day", day)
    mo.setResult("code", code)
    router.sendToUser(mo, userId)
def getExchangeReward(userId, idx):
    """
    获取兑换奖励
    """
    rewards = []
    code = 1
    rewardListConf = getAllRewardList()
    rewardConf = {}
    targetVal = 0
    for _val in rewardListConf:
        if idx == _val.get("id", 0):
            rewardConf = _val.get("reward", {})
            targetVal = _val.get("targetVal", 0)
            break
    luckyTreeData = getLuckyTreeData(userId)
    if luckyTreeData.get("copperCount", 0) < targetVal:
        return rewards, code
    if rewardConf:
        itemId = rewardConf.get("name", 0)
        if util.isChestRewardId(itemId):
            rewards = chest_system.getChestRewards(userId, itemId)
        else:
            rewards = [rewardConf]
        code = util.addRewards(userId, rewards, "BI_NFISH_LUCKY_TREE_REWARDS",
                               int(idx))
        if code != 0:
            ftlog.error("lucky_tree, userId =", userId, "idx =", idx,
                        "rewards =", rewards, "code =", code)
        luckyTreeData["copperCount"] = max(
            0, luckyTreeData["copperCount"] - targetVal)
        saveLuckyTreeData(userId, luckyTreeData)
    return rewards, code
示例#11
0
def sendIdentifyReward(userId):
    """
    实名认证领奖
    """
    mo = MsgPack()
    mo.setCmd("id_card_identify_reward")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    identifyReward = []
    if ftlog.is_debug():
        ftlog.debug("user_system.sendIdentifyReward IN",
                    "userId=", userId)
    try:
        rewarded = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.idCardRewarded)
        if rewarded:
            code = 1
        else:
            idCardReward = config.getCommonValueByKey("idCardReward", [])
            if ftlog.is_debug():
                ftlog.debug("user_system.sendIdentifyReward send reward",
                            "userId=", userId,
                            "idCardReward=", idCardReward)
            code = util.addRewards(userId, idCardReward, "BI_NFISH_NEW_USER_REWARDS")
            if code == 0:
                identifyReward = idCardReward
                gamedata.setGameAttr(userId, FISH_GAMEID, GameData.idCardRewarded, 1)
    except Exception as e:
        ftlog.error("user_system.sendIdentifyReward error", e,
                    "userId=", userId)
        code = 3
    mo.setResult("code", code)
    mo.setResult("reward", identifyReward)
    router.sendToUser(mo, userId)
示例#12
0
 def addGiftData(self, giftId):
     """
     使礼包变为可领取状态并添加礼包数据
     """
     extraRwards = []
     giftConf = config.getGiftConf(self.clientId, giftId)
     itemId = giftConf["monthCard"]["name"]
     count = giftConf["monthCard"]["count"]
     userBag = hallitem.itemSystem.loadUserAssets(self.userId).getUserBag()
     itemPermanent = userBag.getItemByKindId(
         config.PERMANENT_MONTH_CARD_KINDID)
     # 已购买永久月卡后不可以再次购买任何月卡.
     if itemPermanent:
         return 1, extraRwards
     item = userBag.getItemByKindId(itemId)
     # 当前没有月卡时购买月卡天数减1(普通月卡需特殊处理).
     if itemId == config.MONTH_CARD_KINDID and (item is None or item.isDied(
             int(time.time()))) and count > 1:
         count -= 1
     rewards = [{"name": itemId, "count": count}]
     # 首次购买奖励
     if gamedata.getGameAttrInt(self.userId, FISH_GAMEID,
                                GameData.hasBoughtMonthCard) == 0:
         for reward in giftConf.get("firstBuyRewards", []):
             if reward["type"] == 3:  # 资产/道具
                 extraRwards.append({
                     "name": reward["itemId"],
                     "count": reward["count"]
                 })
     # 购买立得
     for reward in giftConf.get("getAfterBuy", []):
         if reward["type"] == 3:  # 资产/道具
             extraRwards.append({
                 "name": reward["itemId"],
                 "count": reward["count"]
             })
     rewards.extend(extraRwards)
     util.addRewards(self.userId,
                     rewards,
                     "BI_NFISH_BUY_ITEM_GAIN",
                     int(giftId),
                     param01=int(giftId))
     gamedata.setGameAttr(self.userId, FISH_GAMEID,
                          GameData.hasBoughtMonthCard, json.dumps(1))
     honor_system.checkMonthCardHonor(self.userId)
     return 0, extraRwards
 def getPointReward(self, userId):
     """
     是否获取积分阶段奖励
     """
     rewards = []
     for info in config.getGrandPrixConf("stageInfo"):
         point = info["point"]
         reward = info["rewards"]
         if self.grandPrixFishPoint >= point and point not in self.grandPrixGetPointsInfo:
             rewards.extend(reward)
             self.grandPrixGetPointsInfo.append(point)
     if rewards:
         util.addRewards(userId, rewards,
                         "BI_GRAND_PRIX_POINT_REWARD")  # 添加奖励
         weakdata.setDayFishData(userId, WeakData.grandPrix_getPointsInfo,
                                 json.dumps(self.grandPrixGetPointsInfo))
     return rewards
示例#14
0
def addRewardsToTable(roomId, tableId, userId, rewards, eventId,
                      intEventParam):
    """
    在渔场内发放奖励
    """
    try:
        room = gdata.rooms()[roomId]
        table = room.maptable[tableId]
        player = table.getPlayer(userId)
        if player and rewards[0]["name"] == config.CHIP_KINDID:
            player.addTableChip(rewards[0]["count"], eventId, intEventParam)
        else:
            util.addRewards(userId, rewards, eventId, intEventParam)
    except Exception as e:
        ftlog.error("addRewardsToTable", roomId, tableId, userId, rewards,
                    eventId, intEventParam, traceback.format_exc())
    return 0
示例#15
0
def getDailyQuestReward(userId, star, type="day"):
    """
    领取每日任务星级奖励
    """
    from newfish.entity.chest.chest_system import ChestFromType
    fromType = ChestFromType.Daily_Quest_Week_Chest if type == "week" else \
               ChestFromType.Daily_Quest_Daily_Chest
    reason = 0
    rewards = []
    finishedStar = 0
    key = _getUserDailyQuestWeeklyRewardKey(userId)
    ret = json.loads(weakdata.getWeekFishData(userId, key, "{}"))
    finishedWeekStar = ret.get("star", 0)
    gotRewardStars = _getUserQuestRewardData(userId, type)
    questInfo = getUserQuestInfoData(userId)
    all = len(questInfo) == len(config.getDailyQuestGroupOrder())
    if star in gotRewardStars:
        reason = 1  # 已经领取过奖励
    else:
        todayQuest, activeLv = getTodayQuest(userId)
        for k, v in todayQuest.iteritems():
            progress, state = questInfo.get(str(k), [0, QuestTaskState.Normal])
            if state == QuestTaskState.Received:
                finishedStar += v["taskLevel"]
        starConfig = config.getDailyQuestRewardConf(activeLv, all).get(str(star), {})
        if not starConfig or (type == "day" and finishedStar < star) or (type == "week" and finishedWeekStar < star):
            reason = 2  # 未达到领取条件
        else:
            rewards = starConfig.get("rewards")
            code = 0
            _insertQuestRewarded(userId, star, type)
            for reward in starConfig.get("rewards"):
                kindId = reward["itemId"]
                if util.isChestRewardId(kindId):
                    rewards = chest_system.getChestRewards(userId, kindId)
                    code = chest_system.deliveryChestRewards(userId, kindId, rewards, "DTASK_REWARD", fromType=fromType)
                else:
                    code = util.addRewards(userId, [reward], "DTASK_REWARD")
            if code != 0:
                ftlog.error("newfish->getDailyQuestReward =", userId, "rewards =", rewards)
    mo = MsgPack()
    mo.setCmd("task")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("action", "dailyReward")
    mo.setResult("star", star)
    mo.setResult("type", type)
    mo.setResult("gotReward", gotRewardStars)
    mo.setResult("reason", reason)
    if reason == 0:
        gotRewardStars.append(star)
        mo.setResult("gotReward", gotRewardStars)
        mo.setResult("rewards", rewards)
        # _insertQuestRewarded(userId, star, type)
        module_tip.cancelModuleTipEvent(userId, "task", star)
    router.sendToUser(mo, userId)
    if ftlog.is_debug():
        ftlog.debug("daily_quest, userId =", userId, "star =", star, "type =", type, "mo =", mo)
示例#16
0
 def _sendTaskReward(self, player, chestId, broadcastUserIds):
     """
     发送任务奖励
     """
     chestRewards = chest_system.getChestRewards(player.userId, chestId)
     util.addRewards(player.userId,
                     chestRewards,
                     "BI_NFISH_CMPTT_TASK_REWARDS",
                     roomId=self.table.roomId,
                     tableId=self.table.tableId)
     from newfish.game import TGFish
     from newfish.entity.event import GainChestEvent
     from newfish.entity.chest.chest_system import ChestFromType
     event = GainChestEvent(player.userId, FISH_GAMEID, chestId,
                            ChestFromType.Cmptt_Ncmptt_Bonus_Task)
     TGFish.getEventBus().publishEvent(event)
     dropItems = {"chest": chestId, "chestRewards": chestRewards, "type": 0}
     return dropItems
示例#17
0
def getQuestReward(userId, taskId, rewardflyPos):
    """
    领取每日任务奖励
    """
    code = 1
    reason = 2
    rewards = []
    questInfo = getUserQuestInfoData(userId)
    progress, state = questInfo.get(str(taskId), [0, QuestTaskState.Normal])
    # 未达到领取条件
    if state == QuestTaskState.Normal:
        reason = 2
    # 已经领取过奖励
    elif state == QuestTaskState.Received:
        reason = 1
    elif state == QuestTaskState.Complete:
        reason = 0
        questInfo[str(taskId)] = [progress, QuestTaskState.Received]
        setUserQuestInfoData(userId, questInfo)
        module_tip.cancelModuleTipEvent(userId, "task", taskId)     # -1
        todayQuest, activeLv = getTodayQuest(userId)
        quest = todayQuest.get(taskId, {})
        rewards = _processQuestReward(userId, quest)                # quest.get("rewards", [])
        code = util.addRewards(userId, rewards, "DTASK_REWARD")
        taskLevel = quest.get("taskLevel", 0)
        # 更新周奖励的星级
        finishedWeekStar = _incrDailyQuestWeekStar(userId, taskLevel)
        questData = getDailyQuestData(userId)
        finishedStar = questData.get("finishedStar", 0)
        all = len(questInfo) == len(config.getDailyQuestGroupOrder())
        dailyQuestRewardFinishedStars = config.getDailyQuestRewardFinishedStars("day", all)
        for star in dailyQuestRewardFinishedStars:
            if finishedStar >= star > finishedStar - taskLevel:
                module_tip.addModuleTipEvent(userId, "task", star)
                break
        dailyQuestRewardFinishedWeekStars = config.getDailyQuestRewardFinishedStars("week", all)
        for star in dailyQuestRewardFinishedWeekStars:
            if finishedWeekStar >= star > finishedWeekStar - taskLevel:
                module_tip.addModuleTipEvent(userId, "task", star)
                break
        from newfish.entity.event import DailyTaskRewardEvent
        from newfish.game import TGFish
        event = DailyTaskRewardEvent(userId, FISH_GAMEID, taskId, taskLevel)
        TGFish.getEventBus().publishEvent(event)
    mo = MsgPack()
    mo.setCmd("task")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("action", "questReward")
    mo.setResult("taskId", taskId)
    mo.setResult("rewardflyPos", rewardflyPos)
    mo.setResult("reason", reason)
    if reason == 0:
        mo.setResult("code", code)
        mo.setResult("rewards", rewards)
    router.sendToUser(mo, userId)
示例#18
0
def _dealMail(userId, mailIds, mailSenderType):
    """
    领取邮件奖励
    :param mailType: 1为表示系统邮件,为2表示其他邮件
    """
    code = 0
    rewards = []
    curTime = int(time.time())
    _key = GameData.mailInfos if mailSenderType == MailSenderType.MT_SYS else GameData.userMailInfos
    mailInfos = gamedata.getGameAttrJson(userId, FISH_GAMEID, _key, [])
    commonRewards = []
    chestRewards = []
    try:
        for _mailInfo in mailInfos:
            expireTime = _mailInfo.get("expireTime")
            # 过期邮件不可领取.
            if expireTime and expireTime + 10 < curTime:
                continue
            if (not mailIds or _mailInfo["id"] in mailIds) and _mailInfo["state"] == MailState.Default:
                eventId = "BI_NFISH_MAIL_REWARDS"
                intEventParam = int(_mailInfo["type"])
                param0 = None
                if _mailInfo["type"] == MailRewardType.Present:
                    eventId = "ACCEPT_PRESENT_ITEM"
                    intEventParam = _mailInfo["userId"]
                elif _mailInfo["type"] in [MailRewardType.StarRank, MailRewardType.RobberyRank, MailRewardType.PoseidonRank]:
                    eventId = "BI_NFISH_RANKING_REWARDS"
                elif _mailInfo["type"] == MailRewardType.InviteReward:
                    param0 = _mailInfo["userId"]
                elif _mailInfo["type"] == MailRewardType.MatchReward:
                    eventId = "MATCH_REWARD"
                elif _mailInfo["type"] == MailRewardType.TreasureReward:
                    eventId = "BI_NFISH_TREASURE_REWARDS"
                elif _mailInfo["type"] == MailRewardType.FishCanReturn:
                    eventId = "BI_NFISH_FISH_CAN_RETURN"

                commonReward = []
                chestReward = []
                if _mailInfo["reward"]:
                    commonReward, chestReward, totalRewards = _getAllRewardInfo(userId, _mailInfo["reward"])
                    code = util.addRewards(userId, totalRewards, eventId, intEventParam, param01=param0)
                if code == 0:
                    _mailInfo["state"] = MailState.Received
                    commonRewards.extend(commonReward)
                    chestRewards.extend(chestReward)
                    # rewards.append({"commonReward": commonRewards, "chestRewards": chestRewards})
                elif code == 4:  # 没有奖励
                    code = 0
                    _mailInfo["state"] = MailState.Received
        rewards.append({"commonReward": commonRewards, "chestRewards": chestRewards})
    except Exception as e:
        ftlog.error("_dealMail error", userId, mailIds, mailSenderType, e)
    if ftlog.is_debug():
        ftlog.debug("_dealMail=====>userId =", userId, "rewards =", rewards, "mailSenderType =", mailSenderType)
    gamedata.setGameAttr(userId, FISH_GAMEID, _key, json.dumps(mailInfos))
    return code, rewards
 def setRewards(self, fpMultiple, bet, betType=None):
     """
     确定转盘奖励结果
     """
     rewards = []
     fishPool = str(self.fishPool)
     pwData = self._getData(fishPool, fpMultiple)
     prizeConf = self.getPrizeConf(fishPool, fpMultiple)
     weightList = []
     if self._enable(fishPool, fpMultiple):
         for idx, item in enumerate(prizeConf.get("wheel", [])):
             enable = 1 if idx not in pwData[PWValueSlot.TAKEN] else 0
             weightList.append(item["rate"] if enable else 0)
     code = 1
     if pwData[PWValueSlot.STATE] in [
             PWState.NOT_TAKE_REWARD, PWState.FAIL_SPIN
     ] and len(pwData[PWValueSlot.RET]) > 0:
         if pwData[PWValueSlot.
                   STATE] == PWState.NOT_TAKE_REWARD and betType == "bet":
             for item in pwData[PWValueSlot.RET]:
                 if item["ratio"] == bet:
                     try:
                         rewards = [item["rewards"][item["ret"]]]
                         if rewards and rewards[0].get("count",
                                                       0) > 0:  # 抽奖成功,获得奖励
                             code = util.addRewards(
                                 self.userId, rewards,
                                 "BI_NFISH_PRIZE_WHEEL_REWARDS",
                                 int(fishPool), self.roomId, fpMultiple)
                             self.addRoomLotteryProfitCoin(rewards)
                         else:
                             if ftlog.is_debug():
                                 ftlog.debug("prize_wheel, userId =",
                                             self.userId, "fishPool =",
                                             fishPool, "bet =", bet, code,
                                             "data =",
                                             pwData[PWValueSlot.RET])
                         self._resetPrizeWheelState(fishPool, fpMultiple)
                     except:
                         ftlog.error("prize_wheel, userId =", self.userId,
                                     "fishPool =", fishPool, "bet =", bet,
                                     code, "data =",
                                     pwData[PWValueSlot.RET])
                     break
     self._setData(fishPool, fpMultiple)
     mo = MsgPack()
     mo.setCmd("prize_wheel_bet")
     mo.setResult("betType", betType)
     mo.setResult("gameId", FISH_GAMEID)
     mo.setResult("userId", self.userId)
     mo.setResult("code", code)
     mo.setResult("bet", bet)
     mo.setResult("rewards", rewards)
     GameMsg.sendMsg(mo, self.userId)
     self.sendEnergyProgress(self.fishPool, fpMultiple, self.roomId, 0)
示例#20
0
def getResComplement(userId, count=0):
    """
    获得珍珠、紫水晶、黄水晶道具补足
    """
    effect = {}
    treasureConf = config.getTreasureConf(effectType=EffectType.ResComplement)
    if treasureConf:
        kindId = treasureConf["kindId"]
        level, levelConf = getTreasureInfo(userId, kindId)
        if not levelConf:
            return
        refreshTreasureState(userId, kindId)
        treasureData = getTreasure(userId, kindId)
        if treasureData[INDEX_FINISH_COUNT] >= treasureConf["limitCount"]:
            return
        rewards = []
        lang = util.getLanguage(userId)
        for _kindId, _complementCount in levelConf.get("params", {}).iteritems():
            _kindId = int(_kindId)
            _surplusCount = util.balanceItem(userId, _kindId)
            if _complementCount > _surplusCount:
                _reward = {
                    "name": _kindId,
                    "count": _complementCount - _surplusCount,
                    "chgCount": [_surplusCount, _complementCount]
                }
                rewards.append(_reward)
                treasureName = config.getMultiLangTextConf(treasureConf["name"], lang=lang)
                countStr = util.formatScore(_complementCount, lang=lang)
                message = config.getMultiLangTextConf("ID_CONFIG_TREASURE_SUPPLY_%s" % _kindId, lang=lang)
                message = message.format(countStr, treasureName, countStr)
                GameMsg.sendPrivate(FISH_GAMEID, userId, 0, message)
        if rewards:
            util.addRewards(userId, rewards, "BI_NFISH_TREASURE_REWARDS", kindId)
            activeTreasure(userId, kindId, treasureData)
            effect = {
                "kindId": kindId,
                "level": level,
                "rewards": rewards
            }
    return effect
示例#21
0
def getCoinComplement(userId, coin=0):
    """
    获得金币补足
    :param userId:
    :param coin: 当处于渔场中时,使用渔场传过来的金币数
    """
    effect = {}
    userCoin = coin if coin > 0 else userchip.getChip(userId)
    treasureConf = config.getTreasureConf(effectType=EffectType.CoinComplement)
    if treasureConf:
        kindId = treasureConf["kindId"]
        level, levelConf = getTreasureInfo(userId, kindId)
        if not levelConf:
            return
        refreshTreasureState(userId, kindId)
        treasureData = getTreasure(userId, kindId)
        if treasureData[INDEX_FINISH_COUNT] >= treasureConf["limitCount"]:
            return
        coinComplement = levelConf.get("params", {}).get("value", 0)
        if coinComplement > userCoin:
            lang = util.getLanguage(userId)
            rewards = [{"name": config.CHIP_KINDID,
                        "count": coinComplement - userCoin,
                        "chgCount": [userCoin, coinComplement]}]
            util.addRewards(userId, rewards, "BI_NFISH_TREASURE_REWARDS", kindId)
            activeTreasure(userId, kindId, treasureData)
            treasureName = config.getMultiLangTextConf(treasureConf["name"], lang=lang)
            coinStr = util.formatScore(coinComplement, lang=lang)
            message = config.getMultiLangTextConf("ID_CONFIG_TREASURE_SUPPLY_101", lang=lang)
            message = message.format(coinStr, treasureName, coinStr)
            GameMsg.sendPrivate(FISH_GAMEID, userId, 0, message)
            effect = {
                "kindId": kindId,
                "level": level,
                "rewards": rewards
            }
    return effect
示例#22
0
def getLevelRewards(userId, level):
    """
    领取等级奖励
    """
    clientId = util.getClientId(userId)
    module_tip.cancelModuleTipEvent(userId, "levelrewards", level)
    code = 1
    userLevel = util.getUserLevel(userId)
    levels = gamedata.getGameAttrJson(userId, config.FISH_GAMEID,
                                      GameData.levelRewards, [])
    levelRewards = config.getLevelRewards(clientId, level)
    rewards = []
    chestRewards = {}
    if levelRewards and level not in levels and level <= userLevel:
        for val in levelRewards.get("rewards", []):
            itemId = val["name"]
            if util.isChestRewardId(itemId):
                chestRewards["chestId"] = itemId
                chestRewards["rewards"] = chest_system.getChestRewards(
                    userId, itemId)
                code = chest_system.deliveryChestRewards(
                    userId, itemId, chestRewards["rewards"],
                    "BI_NFISH_GET_LEVEL_REWARDS")
            else:
                r = [{"name": val["name"], "count": val["count"]}]
                rewards.extend(r)
                code = util.addRewards(userId, r, "BI_NFISH_GET_LEVEL_REWARDS",
                                       level)
        if levelRewards.get("rechargeBonus", 0) > 0:
            util.incrUserRechargeBonus(userId,
                                       levelRewards.get("rechargeBonus", 0))
        levels.append(level)
        gamedata.setGameAttr(userId, config.FISH_GAMEID, GameData.levelRewards,
                             json.dumps(levels))

    mo = MsgPack()
    mo.setCmd("levelRewards")
    mo.setResult("gameId", config.FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("code", code)
    mo.setResult("level", level)
    mo.setResult("rewards", rewards)
    mo.setResult("chestRewards", chestRewards)
    router.sendToUser(mo, userId)
    ftlog.debug("level_rewards, userId =", userId, "code =", code, "level =",
                level, "userLevel =", userLevel, "rewards =", rewards,
                "levels =", levels)

    getLevelRewardsData(userId)
示例#23
0
def convertTreasure(userId, kindId, count):
    """
    兑换宝藏碎片
    """
    code, rewards = 1, None
    treasureConf = config.getTreasureConf(kindId)
    convert = treasureConf.get("convert")
    if convert:
        surplusCount = util.balanceItem(userId, convert["kindId"])
        consumeCount = convert["rate"] * count
        if surplusCount >= consumeCount:
            consume = [{"name": convert["kindId"], "count": -abs(consumeCount)}]
            rewards = [{"name": kindId, "count": count}]
            consume.extend(rewards)
            code = util.addRewards(userId, consume, "BI_NFISH_TREASURE_CONVERT", kindId)
            return code, rewards
    return code, rewards
示例#24
0
def _getOnceResult(userId, luckyNum, configInfo):
    itemTotalWeight = int(
        sum([
            dict(rewardInfo)["weight"]
            for rewardInfo in configInfo if rewardInfo
        ]) + luckyNum / LuckyAdd)
    code = 0
    if itemTotalWeight > 0:
        itemWeight = random.randint(1, itemTotalWeight)
        for j, rewardInfo in enumerate(configInfo):
            _weight = rewardInfo["weight"]
            if rewardInfo["Id"] == 1:  # 微信红包权重增加
                _weight = _weight + luckyNum / LuckyAdd
            if rewardInfo and itemWeight - _weight <= 0:
                if userId:
                    code = util.addRewards(userId, rewardInfo["rewards"],
                                           "BI_NFISH_WISH_REWARDS")
                return code, j, rewardInfo["rewards"][0]["name"], rewardInfo[
                    "clearLucky"]
            itemWeight -= _weight
    return code, -1, 0
示例#25
0
def deliveryChestRewards(userId, chestId, rewards, eventId=None, fromType=None, param01=0, param02=0):
    """
    发放宝箱物品
    """
    if not rewards:
        ftlog.error("deliveryChestRewards->not rewards", userId, chestId)
        return 4
    if not eventId:
        eventId = "BI_NFISH_OPEN_CHEST_REWARDS"
    code = util.addRewards(userId, rewards, eventId, int(chestId), param01=param01, param02=param02)
    if code != 0:
        ftlog.error("deliveryChestRewards->add gain error", userId, chestId, rewards)
        return code
    gamedata.incrGameAttr(userId, FISH_GAMEID, GameData.openChestCount, 1)
    bireport.reportGameEvent("BI_NFISH_GE_CHEST_OPEN", userId, FISH_GAMEID, 0,
                             0, int(chestId), 0, 0, 0, [], util.getClientId(userId))
    if fromType:
        from newfish.game import TGFish
        from newfish.entity.event import GainChestEvent
        event = GainChestEvent(userId, FISH_GAMEID, chestId, fromType)
        TGFish.getEventBus().publishEvent(event)
    return 0
示例#26
0
 def receiveActivityReward(self, taskId=None, extend=None):
     """
     领取活动奖励
     """
     assert (self.activityData)
     if self.activityData["state"] == ActivityState.Normal:
         if isinstance(self.activityConfig.get("extends"), dict):
             self.activityData["state"] = self.activityConfig[
                 "extends"].get("receiveState", ActivityState.Normal)
     if self.activityData["state"] == ActivityState.Received:
         return CodeType.Received, []
     if self.activityData["state"] == ActivityState.Complete:
         self.activityData["state"] = ActivityState.Received
         self.activityData["receiveTime"] = int(time.time())
         self.saveActivityData()
         rewards = self.activityConfig["reward"]
         code = util.addRewards(self.userId, rewards,
                                "BI_NFISH_ACTIVITY_REWARDS")
         module_tip.cancelModuleTipEvent(self.userId, "activity",
                                         self.activityId)
         return code, rewards
     return CodeType.NotComplete, []
示例#27
0
def receiveInvitTaskReward(userId, taskId, actionType):
    weakDatas = weakdata.getDayFishDataAll(userId, FISH_GAMEID)
    taskConf = config.getInviteTaskConf(taskId, actionType)
    code = 0
    chestId = 0
    rewards = []
    taskState = []
    saveKey = "inviteTasks"
    if not taskConf:
        return 999, chestId, rewards, taskState
    if actionType == NewPlayerAction:
        taskState = strutil.loads(weakDatas.get("inviteTasks", "[]"))
        playerNums = len(strutil.loads(weakDatas.get("inviteNewPlayers", "[]")))
    else:
        saveKey = "recallTasks"
        taskState = strutil.loads(weakDatas.get("recallTasks", "[]"))
        playerNums = len(strutil.loads(weakDatas.get("recallPlayers", "[]")))

    if taskConf["target"] > playerNums:
        return 1, chestId, rewards, taskState

    if taskId in taskState:
        return 2, chestId, rewards, taskState

    rewards = taskConf["rewards"]
    for _reward in taskConf["rewards"]:
        kindId = _reward["name"]
        if util.isChestRewardId(kindId):
            chestId = kindId
            rewards = chest_system.getChestRewards(userId, kindId)
            code = chest_system.deliveryChestRewards(userId, kindId, rewards, "BI_NFISH_INVITE_TASK_REWARDS")
        else:
            code = util.addRewards(userId, [_reward], "BI_NFISH_INVITE_TASK_REWARDS", int(taskId))
    taskState.append(taskId)
    weakdata.setDayFishData(userId, saveKey, strutil.dumps(taskState))
    # 更新小红点
    module_tip.cancelModuleTipEvent(userId, "invitetasks", taskId)
    return code, chestId, rewards, taskState
示例#28
0
    def _receiveTaskReward(self):
        """领取奖励"""
        assert (self.taskData)
        if self.isTaskOver():  # 已领取
            return 1, None
        targetCount = self.taskData["targetNum"]
        if self.taskData["progress"] < targetCount:  # 未达成
            return 1, None
        _rewards = self._getDropItems()
        if not _rewards:
            _rewards = self.taskConfig["rewards"]     # 普通奖励
        if _rewards and util.isChestRewardId(_rewards[0]["name"]):      # 宝箱奖励(新手宝箱奖励固定)
            if util.isNewbieRoom(self.player.table.typeName):
                _rewards = [
                    {"name": 101, "count": 500},
                    {"name": 1145, "count": 1},
                    {"name": 1149, "count": 1}
                    # {"name": 1137, "count": 3}
                ]
            else:
                from newfish.entity.chest import chest_system
                _rewards = chest_system.getChestRewards(self.userId, _rewards[0]["name"])

        rewards = []
        for _, reward in enumerate(_rewards):
            if reward["name"] <= 0:
                continue
            rwDict = {}
            rwDict["name"] = reward["name"]
            rwDict["count"] = reward["count"]
            rewards.append(rwDict)

        code = 0
        self.taskData["state"] = TaskState.Success  # 改变状态
        if rewards:
            code = util.addRewards(self.userId, rewards, "BI_NFISH_TABLE_TASK_REWARDS", int(self.taskId))
        return code, rewards
示例#29
0
def doBuyGift(userId, clientId, giftId, buyType, itemId=0):
    """
    购买礼包
    """
    if ftlog.is_debug():
        ftlog.debug("doBuyGift===>", userId, clientId, giftId, buyType)
    giftConf = config.getDailyGiftConf(clientId).get(str(giftId), {})
    continuousDay = _getContinuousDay(userId, giftId)
    dayIdx = _getGiftDayIdx(clientId, giftId, continuousDay)
    lang = util.getLanguage(userId, clientId)
    commonRewards = []
    chestRewards = []
    chestId = 0
    giftName = config.getMultiLangTextConf(giftConf["giftName"], lang=lang)
    # 使用其他货币(非direct)购买
    if giftConf.get("otherBuyType", {}).get(buyType):
        price = giftConf.get("otherBuyType", {}).get(buyType)
        # 代购券购买礼包
        if buyType == BT_VOUCHER:
            _consume = [{"name": VOUCHER_KINDID, "count": abs(price)}]
            _ret = util.consumeItems(userId,
                                     _consume,
                                     "BI_NFISH_BUY_ITEM_CONSUME",
                                     intEventParam=int(giftId),
                                     param01=int(giftId))
            if not _ret:
                code = 1
                _sendBuyGiftRet(userId, clientId, giftId, code, chestId,
                                commonRewards, chestRewards)
                return
            else:
                code = 0
                vip_system.addUserVipExp(FISH_GAMEID,
                                         userId,
                                         abs(price) * 10,
                                         "BUY_PRODUCT",
                                         pokerconf.productIdToNumber(
                                             giftConf["productId"]),
                                         giftConf["productId"],
                                         rmbs=abs(price))
                # message = u"您使用%s代购券,购买商品【%s】, 获得%s" % (price, giftConf["giftName"], giftConf["giftName"])
                message = config.getMultiLangTextConf(
                    "ID_BUY_GIFT_RET_BY_VOUCHER",
                    lang=lang).format(price, giftName, giftName)
                GameMsg.sendPrivate(FISH_GAMEID, userId, 0, message)
        else:
            code = 1
            _sendBuyGiftRet(userId, clientId, giftId, code, chestId,
                            commonRewards, chestRewards)
            return
    elif buyType == config.BT_DIAMOND:
        price = giftConf.get("price", 0)
        price, isSucc = store.getUseRebateItemPrice(userId, itemId, price,
                                                    buyType, giftId, clientId)
        code = 0
        if price > 0:
            consumeCount = 0
            if isSucc:
                store.autoConvertVoucherToDiamond(userId, price)
                consumeCount, final = userchip.incrDiamond(
                    userId,
                    FISH_GAMEID,
                    -abs(price),
                    0,
                    "BI_NFISH_BUY_ITEM_CONSUME",
                    int(giftId),
                    util.getClientId(userId),
                    param01=giftId)
            if not isSucc or abs(consumeCount) != price:
                code = 1
                _sendBuyGiftRet(userId, clientId, giftId, code, chestId,
                                commonRewards, chestRewards)
                return
    else:
        code = 0
        # message = u"您购买商品【%s】, 获得%s" % (giftConf["giftName"], giftConf["giftName"])
        message = config.getMultiLangTextConf("ID_BUY_GIFT_RET_BY_DRIECT",
                                              lang=lang).format(
                                                  giftName, giftName)
        GameMsg.sendPrivate(FISH_GAMEID, userId, 0, message)

    # 记录存档
    boughtGift = weakdata.getDayFishData(userId, WeakData.buyFishDailyGift, [])
    boughtGift.append(giftId)
    weakdata.setDayFishData(userId, WeakData.buyFishDailyGift,
                            json.dumps(boughtGift))

    # 记录每日礼包购买次数.
    buyFishDailyGiftTimes = gamedata.getGameAttrJson(
        userId, FISH_GAMEID, GameData.buyFishDailyGiftTimes, {})
    buyFishDailyGiftTimes.setdefault(str(giftId), 0)
    buyFishDailyGiftTimes[str(giftId)] += 1
    gamedata.setGameAttr(userId, FISH_GAMEID, GameData.buyFishDailyGiftTimes,
                         json.dumps(buyFishDailyGiftTimes))

    purchaseData = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                            GameData.continuousPurchase, {})
    data = purchaseData.get(str(giftId), [0, 0])
    if util.getDayStartTimestamp(
            data[0]) + 24 * 60 * 60 < util.getDayStartTimestamp(
                int(time.time())):
        data[1] = 1
    else:
        data[1] += 1
    data[0] = int(time.time())
    purchaseData[str(giftId)] = data
    gamedata.setGameAttr(userId, FISH_GAMEID, GameData.continuousPurchase,
                         json.dumps(purchaseData))
    # 发奖励
    mail_rewards = []
    giftInfo = giftConf.get("giftInfo", [])
    for gift in giftInfo:
        if gift["day_idx"] == dayIdx:
            for item in gift.get("items", []):
                if util.isChestRewardId(item["itemId"]):  # 宝箱
                    chestId = item["itemId"]
                    rewards = chest_system.getChestRewards(userId, chestId)
                    if buyType == BT_VOUCHER or buyType == config.BT_DIAMOND:
                        code = chest_system.deliveryChestRewards(
                            userId, chestId, rewards, "BI_NFISH_BUY_ITEM_GAIN")
                    else:
                        code = 0
                        gamedata.incrGameAttr(userId, FISH_GAMEID,
                                              GameData.openChestCount, 1)
                        bireport.reportGameEvent("BI_NFISH_GE_CHEST_OPEN",
                                                 userId, FISH_GAMEID, 0, 0,
                                                 int(chestId), 0, 0, 0, [],
                                                 util.getClientId(userId))
                    chestRewards.extend(rewards)
                    mail_rewards.extend([{"name": item["itemId"], "count": 1}])
                else:  # 资产/道具
                    rewards = [{
                        "name": item["itemId"],
                        "count": item["count"]
                    }]
                    if buyType == BT_VOUCHER or buyType == config.BT_DIAMOND:
                        code = util.addRewards(userId,
                                               rewards,
                                               "BI_NFISH_BUY_ITEM_GAIN",
                                               int(giftId),
                                               param01=int(giftId))
                    else:
                        code = 0
                    commonRewards.extend(rewards)
                    mail_rewards.extend(rewards)
            break
    if buyType == BT_VOUCHER or buyType == config.BT_DIAMOND:
        _sendBuyGiftRet(userId, clientId, giftId, code, chestId, commonRewards,
                        chestRewards)
    else:
        message = config.getMultiLangTextConf("ID_DO_BUY_GIFT_MSG",
                                              lang=lang) % giftName
        title = config.getMultiLangTextConf("ID_MAIL_TITLE_DAILY_GIFT",
                                            lang=lang)
        mail_system.sendSystemMail(userId,
                                   mail_system.MailRewardType.SystemReward,
                                   mail_rewards, message, title)
        doSendGift(userId, clientId)
    # 购买礼包事件
    from newfish.game import TGFish
    from newfish.entity.event import GiftBuyEvent
    event = GiftBuyEvent(userId, FISH_GAMEID, giftConf["productId"], buyType,
                         giftId)
    TGFish.getEventBus().publishEvent(event)
    util.addProductBuyEvent(userId, giftConf["productId"], clientId)
示例#30
0
    def setRewards(self, fpMultiple, bet, betType=None):
        """
        确定转盘奖励结果
        """
        rewards = []
        fishPool = str(self.fishPool)
        pwData = self._getData(fishPool, fpMultiple)
        prizeConf = self.getPrizeConf(fishPool, fpMultiple)
        weightList = []
        if self._enable(fishPool, fpMultiple):
            for idx, item in enumerate(prizeConf.get("wheel", [])):
                enable = 1 if idx not in pwData[PWValueSlot.TAKEN] else 0
                weightList.append(item["rate"] if enable else 0)
        code = 1
        if pwData[PWValueSlot.STATE] in [
                PWState.NOT_TAKE_REWARD, PWState.FAIL_SPIN
        ] and len(pwData[PWValueSlot.RET]) > 0:
            consumeDiamond, _rewards = self.getConsumeDiamond(pwData)
            if pwData[PWValueSlot.
                      STATE] == PWState.FAIL_SPIN and betType == "paid":
                diamondCount = userchip.getDiamond(self.userId)
                if diamondCount >= consumeDiamond:
                    code = 0
                    clientId = util.getClientId(self.userId)
                    userchip.incrDiamond(self.userId,
                                         config.FISH_GAMEID,
                                         -consumeDiamond,
                                         self.roomId,
                                         "BI_NFISH_BUY_ITEM_CONSUME",
                                         config.DIAMOND_KINDID,
                                         clientId,
                                         param01="prize_wheel")
                    datachangenotify.sendDataChangeNotify(
                        FISH_GAMEID, self.userId, ["chip"])
                    ratioList = self._buildRetData(fishPool, fpMultiple,
                                                   _rewards)
                    pwData[PWValueSlot.RET] = ratioList
                    pwData[PWValueSlot.STATE] = PWState.NOT_TAKE_REWARD
                    self._setData(fishPool, fpMultiple)
                    self.getInfo(fpMultiple)

            elif pwData[PWValueSlot.
                        STATE] == PWState.FAIL_SPIN and betType == "give_up":
                code = 0
                self._resetPrizeWheelState(fishPool, fpMultiple)
                if ftlog.is_debug():
                    ftlog.debug("prize_wheel,  giveup, userId =", self.userId,
                                "fishPool =", self.fishPool,
                                pwData[PWValueSlot.STATE])

            elif pwData[PWValueSlot.
                        STATE] == PWState.NOT_TAKE_REWARD and betType == "bet":
                for item in pwData[PWValueSlot.RET]:
                    if item["ratio"] != bet:
                        continue
                    try:
                        rewards = [item["rewards"][item["ret"]]]
                        code = 0
                        if rewards and rewards[0].get("count",
                                                      0) > 0:  # 抽奖成功,获得奖励
                            code = util.addRewards(
                                self.userId,
                                rewards, "BI_NFISH_PRIZE_WHEEL_REWARDS",
                                int(fishPool), self.roomId, fpMultiple)
                            self.addRoomLotteryProfitCoin(rewards)
                            self._resetPrizeWheelState(fishPool, fpMultiple)
                        else:  # 抽奖失败,谢谢参与
                            pwData[PWValueSlot.STATE] = PWState.FAIL_SPIN
                            pwData[PWValueSlot.BET] = bet
                            self._setData(fishPool, fpMultiple)
                            self.getInfo(fpMultiple)
                    except:
                        ftlog.error("prize_wheel, userId =", self.userId,
                                    "fishPool =", fishPool, "bet =", bet, code,
                                    "data =", pwData[PWValueSlot.RET])
                    break
        self._setData(fishPool, fpMultiple)
        mo = MsgPack()
        mo.setCmd("prize_wheel_bet")
        mo.setResult("betType", betType)
        mo.setResult("gameId", FISH_GAMEID)
        mo.setResult("userId", self.userId)
        mo.setResult("code", code)
        mo.setResult("bet", bet)
        mo.setResult("rewards", rewards)
        GameMsg.sendMsg(mo, self.userId)
        self.sendEnergyProgress(self.fishPool, fpMultiple, self.roomId, 0)