Beispiel #1
0
def _processQuestReward(userId, quest):
    """
    处理每日任务奖励数据
    """
    _rewards = []
    for reward in quest.get("rewards", []):
        dropId = reward["name"]
        dropConf = config.getDropConf(dropId)
        if dropConf:
            _, rds = drop_system.getDropItem(dropId)
            rds["count"] *= reward["count"]
            _rewards.append(rds)
    # 普通奖励
    if not _rewards:
        _rewards = quest.get("rewards", [])
    # 宝箱奖励
    if _rewards and util.isChestRewardId(_rewards[0]["name"]):
        from newfish.entity.chest import chest_system
        _rewards = chest_system.getChestRewards(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)
    return rewards
Beispiel #2
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 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
Beispiel #4
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)
Beispiel #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)
Beispiel #6
0
 def _getTaskReceiveReward(self, taskId, extend):
     """领取任务奖励"""
     rewardInfos, _ = self._getConfigRewards(taskId)
     rewards = []
     chestId = None
     for reward in rewardInfos:
         itemId = reward["name"]
         if self._isChestReward(itemId):
             chestId = itemId
             rds = chest_system.getChestRewards(self.userId, itemId)
             rewards.extend(rds)
         else:
             rewards.append(reward)
     return rewards, chestId
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)
Beispiel #8
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)
Beispiel #9
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
Beispiel #10
0
def _getAllRewardInfo(userId, mailReward):
    """
    拆分邮件中的奖励并返回相应信息
    """
    from newfish.entity.chest import chest_system
    commonRewards = []
    chestRewards = []
    totalRewards = []
    for reward in mailReward:
        itemId = reward["name"]
        if util.isChestRewardId(itemId):
            rewards = chest_system.getChestRewards(userId, itemId)
            chestRewards.append({"name": itemId, "reward": rewards})
            totalRewards.extend(rewards)
        else:
            commonRewards.append(reward)
            totalRewards.append(reward)
    return commonRewards, chestRewards, totalRewards
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
Beispiel #12
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
Beispiel #13
0
def buyFishVipGift(userId, level, clientId, buyType=None, itemId=0):
    """
    购买特定VIP等级的礼包
    """
    mo = MsgPack()
    mo.setCmd("buy_fish_vip_gift")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("level", level)
    vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
    vipGiftBought = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                             GameData.vipGiftBought, [])
    code = 1
    commonRewards = []
    chestRewards = []
    buyType = buyType if buyType else config.BT_DIAMOND
    from newfish.entity import store
    from newfish.entity.gun import gun_system
    if vipLevel < level or level in vipGiftBought:
        mo.setResult("code", code)
        router.sendToUser(mo, userId)
        return
    vipConf = config.getVipConf(level)
    if vipConf:
        price = vipConf["price"]
        vipGiftRewards = vipConf["vipGift"]
        price, isSucc = store.getUseRebateItemPrice(userId, itemId, price,
                                                    buyType,
                                                    vipConf["productId"],
                                                    clientId)  # 满减券之后的钻石 满减券
        consumeCount = 0
        if price > 0 and isSucc:
            store.autoConvertVoucherToDiamond(userId, price)  # 代购券
            consumeCount, final = userchip.incrDiamond(
                userId,
                FISH_GAMEID,
                -abs(price),
                0,
                "BI_NFISH_BUY_ITEM_CONSUME",
                int(config.DIAMOND_KINDID),
                util.getClientId(userId),
                param01=vipConf["productId"])
        if not isSucc or abs(consumeCount) != price:
            code = 2
        else:
            eventId = "BI_NFISH_BUY_ITEM_GAIN"
            for item in vipGiftRewards:
                if item["type"] == 1:  # 宝箱
                    chestId = item["name"]
                    from newfish.entity.chest import chest_system
                    rewards = chest_system.getChestRewards(userId, chestId)
                    code = chest_system.deliveryChestRewards(
                        userId, chestId, rewards, eventId)
                    chestRewards.extend(rewards)
                elif item["type"] == 2:  # 等级
                    from newfish.entity.gift.gift_system import _makeUserLevelUp
                    _makeUserLevelUp(userId, item["count"])
                    code = 0
                elif item["type"] == 3:  # 资产/道具
                    rewards = [{"name": item["name"], "count": item["count"]}]
                    code = util.addRewards(userId,
                                           rewards,
                                           eventId,
                                           int(level),
                                           param01=int(level))
                    commonRewards.extend(rewards)
                elif item["type"] == 5:  # 皮肤炮皮肤
                    skinId = item["name"]
                    ret = gun_system.addEquipGunSkinSkin(
                        userId, skinId, clientId)
                    if ret:
                        code = 0
                        rewards = [{
                            "name": item["name"],
                            "count": item["count"],
                            "type": item["type"]
                        }]
                        commonRewards.extend(rewards)
                elif item["type"] == 6:  # 直升炮台
                    upToLevel = item["count"]
                    success = gun_system.upgradeGun(userId,
                                                    False,
                                                    MULTIPLE_MODE,
                                                    byGift=True,
                                                    upToLevel=upToLevel)
                    if success:
                        code = 0
            vipGiftBought.append(level)
            gamedata.setGameAttr(userId, FISH_GAMEID, GameData.vipGiftBought,
                                 json.dumps(vipGiftBought))
        if code == 0:
            mo.setResult("rewards", vipGiftRewards)
    mo.setResult("code", code)
    router.sendToUser(mo, userId)
Beispiel #14
0
def getTodayCheckinRewards(userId, isShare=False):
    """
    当天未签到时,获得签到奖励详情
    """
    # kindId, rewards = None, None
    # checkinDay = getCheckinDay(userId)
    # if checkinDay:
    #     rewardConf = config.getCheckinConf(checkinDay)
    #     reward = rewardConf["normalReward"]
    #     if isShare:
    #         reward = rewardConf["shareReward"]
    #     kindId = reward["name"]
    #     if util.isChestRewardId(kindId):
    #         rewards = chest_system.getChestRewards(userId, kindId)
    #     else:
    #         rewards = [reward]
    # return kindId, rewards, checkinDay
    rewardsDict = {}
    totalRewards = []
    totalRewardsDict = {}
    checkinDay = getCheckinDay(userId)
    multiple = 1
    vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0)
    if checkinDay:
        for k, v in config.getCheckinConf("checkinData").iteritems():
            if v["unlockdays"] > checkinDay:
                if k == "rewards":
                    rewardsDict.update({"kindId": 0, "rewards": []})
                elif k == "rewards2":
                    rewardsDict.update({"kindId2": 0, "rewards2": []})
            else:
                idx = util.selectIdxByWeight(
                    [item["rate"] for item in v["datas"]])
                item = v["datas"][idx]
                if k == "multiple":
                    multiple = item["rewards"]
                else:
                    reward = item["rewards"]
                    kindId = reward["name"]
                    if util.isChestRewardId(kindId):
                        rewards = chest_system.getChestRewards(userId, kindId)
                    else:
                        rewards = [reward]
                    totalRewards.extend(rewards)
                    if k == "rewards":
                        rewardsDict.update({
                            "kindId": kindId,
                            "rewards": rewards
                        })
                    else:
                        rewardsDict.update({
                            "kindId2": kindId,
                            "rewards2": rewards
                        })
    rewardsDict.update({"multiple": multiple})
    ftlog.debug("checkin, userId =", userId, "totalRewards =", totalRewards,
                "multiple =", multiple, "isShare =", isShare)
    for item in totalRewards:
        itemCount = item["count"] * multiple * (2 if vipLevel >= 1 else 1)
        totalRewardsDict[item["name"]] = totalRewardsDict.get(item["name"],
                                                              0) + itemCount
    totalRewards = []
    for k, v in totalRewardsDict.iteritems():
        totalRewards.append({"name": k, "count": v})
    return checkinDay, totalRewards, rewardsDict
Beispiel #15
0
def getSectionStarRewards(userId, clientId, sectionId, star):
    """
    领取章节星级奖励
    """
    mo = MsgPack()
    mo.setCmd("task")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("action", "sectionStarReward")
    mo.setResult("star", star)
    code = 1
    # honorId = 0
    sectionConf = config.getMainQuestSectionConf(clientId, sectionId)
    currSectionId = gamedata.getGameAttr(userId, FISH_GAMEID,
                                         GameData.currSectionId)
    gotReward = []
    # 检查领取的章节是否为当前生效章节.
    if sectionConf and sectionId == currSectionId:
        sectionData = getSection(userId, sectionId)
        # 检查该星级是否已经领取过.
        star = int(star)
        if star not in sectionData[SectionIndex.TakenStars]:
            starRewards = sectionConf["starRewards"]
            stars = []
            for val in starRewards:
                stars.append(val["star"])
                if val["star"] == star:
                    code = 0
                    rewards = {
                        "name": val["rewards"][0]["itemId"],
                        "count": val["rewards"][0]["count"]
                    }
                    sectionData[SectionIndex.TakenStars].append(star)
                    gotReward = sectionData[SectionIndex.TakenStars]
                    sectionData[SectionIndex.FinishTime] = int(time.time())
                    kindId = rewards["name"]
                    if util.isChestRewardId(kindId):
                        rewards = chest_system.getChestRewards(userId, kindId)
                        chest_system.deliveryChestRewards(
                            userId,
                            kindId,
                            rewards,
                            "BI_NFISH_MAIN_QUEST_STAR_REWARDS",
                            param01=star)
                    else:
                        util.addRewards(userId, [rewards],
                                        "BI_NFISH_MAIN_QUEST_STAR_REWARDS",
                                        int(sectionId), star)
                    module_tip.cancelModuleTipEvent(userId, "mainquest",
                                                    "star_%d" % star)
                    mo.setResult("rewards", rewards)
            if code == 0:
                # 章节任务全部完成并且星级奖励全部领取即可跳转章节.
                finishTaskIds = sectionData[SectionIndex.FinishTasks]
                if len(set(sectionConf["taskIds"]) -
                       set(finishTaskIds)) == 0 and len(
                           set(stars) -
                           set(sectionData[SectionIndex.TakenStars])) == 0:
                    # honorId = sectionConf["honorId"]
                    sectionData[
                        SectionIndex.State] = QuestState.Received  # 领取星级奖励
                    module_tip.cancelModuleTipEvent(userId, "mainquest",
                                                    sectionId)
                    switchToNextSection(userId, clientId,
                                        currSectionId)  # 解锁下一个章节
                    from newfish.game import TGFish
                    event = MainQuestSectionFinishEvent(
                        userId, FISH_GAMEID, sectionId, currSectionId)
                    TGFish.getEventBus().publishEvent(event)
                setSection(userId, sectionId, sectionData)  # 保存当前章节数据
    mo.setResult("code", code)
    mo.setResult("gotReward", gotReward)
    router.sendToUser(mo, userId)
    pushCurrTask(userId)
Beispiel #16
0
def getLevelFundsRewards(userId, clientId, productId, level=0, rewardType=0):
    """
    领取基金奖励
    """
    code = 0
    rewards = []
    rewardsState = []
    isQuickGet = (level == 0)
    # 根据商品Id确定游戏模式.
    mode = config.CLASSIC_MODE
    for _m in [config.CLASSIC_MODE, config.MULTIPLE_MODE]:
        fundsConf = config.getLevelFundsConf(clientId, _m)
        for val in fundsConf.get("funds"):
            if val.get("productId") == productId:
                mode = _m
                break
    lf_rewards = _getRewardsState(userId, mode)
    lf_funds = _getBoughtFunds(userId, mode)
    userLv = util.getGunLevelVal(userId, mode)
    fundsConf = config.getLevelFundsConf(clientId, mode)
    funds = fundsConf.get("funds")
    rewardsConf = fundsConf.get("rewards")
    rewardsTypeStr = ["free_rewards", "funds_rewards"]
    if rewardType in [0, 1]:
        for val in funds:
            if val.get("productId") != productId:
                continue
            rewardsData = rewardsConf.get(str(val["idx"]))
            isChanged = False
            for lvData in rewardsData:
                lv = lvData["level"]
                if (isQuickGet and lv <= userLv) or (not isQuickGet and lv == level):
                    lf_rewards.setdefault(str(lv), [0, 0])
                    # 一键领取时需要检测两种奖励是否可以领取。
                    typeList = [rewardType]
                    if isQuickGet:
                        typeList = [0, 1]
                    for _type in typeList:
                        if lf_rewards[str(lv)][_type] == 0 and (_type == 0 or val["idx"] in lf_funds):
                            isChanged = True
                            lf_rewards[str(lv)][_type] = 2
                            for _reward in lvData[rewardsTypeStr[_type]]:
                                itemId = _reward["name"]
                                if util.isChestRewardId(itemId):
                                    chestRewards = {}
                                    chestRewards["chestId"] = itemId
                                    chestRewards["rewards"] = chest_system.getChestRewards(userId, itemId)
                                    chest_system.deliveryChestRewards(userId, itemId, chestRewards["rewards"],
                                                                      "BI_NFISH_GET_LEVEL_FUNDS", param01=lv, param02=_type)
                                    rewards.append(chestRewards)
                                else:
                                    rewards.append([_reward])
                                    util.addRewards(userId, [_reward], "BI_NFISH_GET_LEVEL_FUNDS", param01=lv, param02=_type)
                            if _type == 0 and lvData.get("rechargeBonus", 0) > 0:
                                util.incrUserRechargeBonus(userId, lvData["rechargeBonus"])
            if isChanged:
                daobase.executeUserCmd(userId, "HSET", _getRdKey(userId, mode), GameData.lf_rewards, json.dumps(lf_rewards))
            hasTip, rewardsState = _getLevelFundsRewardState(userId, clientId, val["idx"], mode, lf_funds=lf_funds, lf_rewards=lf_rewards)
            if not hasTip:
                if mode == 1:
                    module_tip.cancelModuleTipEvent(userId, "levelfundsNew", productId)
                else:
                    module_tip.cancelModuleTipEvent(userId, "levelfunds", productId)
            break
        else:
            code = 1
    else:
        code = 2
    message = MsgPack()
    message.setCmd("levelFundsRewards")
    message.setResult("gameId", config.FISH_GAMEID)
    message.setResult("userId", userId)
    message.setResult("productId", productId)
    message.setResult("code", code)
    message.setResult("rewards", rewards)
    message.setResult("rewardType", rewardType)
    message.setResult("rewardsState", rewardsState)
    router.sendToUser(message, userId)
Beispiel #17
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)
Beispiel #18
0
def doGetFishGiftReward(userId, clientId, giftId):
    """
    领取礼包
    """
    giftConf = getGiftConf(clientId, giftId)
    if not giftConf:
        return
    code = 1
    chestId = 0
    commonRewards = []
    chestRewards = []
    availableGift = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                             GameData.availableGift, [])
    canGetRewards = False
    if giftConf["giftType"] == GiftType.MONTHCARD:
        userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
        itemId = giftConf["monthCard"]["name"]
        item = userBag.getItemByKindId(itemId)
        if item and not item.isDied(int(time.time())):
            if itemId == config.MONTH_CARD_KINDID:
                canGetRewards = weakdata.getDayFishData(
                    userId, WeakData.getMonthCardGift, 0) == 0
            else:
                canGetRewards = weakdata.getDayFishData(
                    userId, WeakData.getPermanentMonthCardGift, 0) == 0
    else:
        canGetRewards = giftId in availableGift

    if not canGetRewards:
        return

    eventId = "BI_NFISH_BUY_ITEM_GAIN"
    for item in giftConf.get("items", []):
        if item["type"] == 1:  # 宝箱
            chestId = item["itemId"]
            rewards = chest_system.getChestRewards(userId, chestId)
            code = chest_system.deliveryChestRewards(userId, chestId, rewards,
                                                     eventId)
            chestRewards.extend(rewards)
        elif item["type"] == 2:  # 等级
            _makeUserLevelUp(userId, item["count"])
            code = 0
        elif item["type"] == 3:  # 资产/道具
            rewards = [{"name": item["itemId"], "count": item["count"]}]
            code = util.addRewards(userId,
                                   rewards,
                                   eventId,
                                   int(giftId),
                                   param01=int(giftId))
            commonRewards.extend(rewards)
        elif item["type"] == 5:  # 皮肤炮皮肤
            skinId = item["itemId"]
            ret = gun_system.addEquipGunSkinSkin(userId, skinId, clientId)
            if ret:
                code = 0
                rewards = [{
                    "name": item["itemId"],
                    "count": item["count"],
                    "type": item["type"]
                }]
                commonRewards.extend(rewards)
        elif item["type"] == 6:  # 直升炮台
            upToLevel = item["count"]
            success = gun_system.upgradeGun(userId,
                                            False,
                                            MULTIPLE_MODE,
                                            byGift=True,
                                            upToLevel=upToLevel)
            if success:
                code = 0

    message = MsgPack()
    if giftConf["giftType"] == GiftType.MONTHCARD:
        message.setCmd("monthGiftGet")
    else:
        message.setCmd("fishGiftReward")
    message.setResult("gameId", FISH_GAMEID)
    message.setResult("userId", userId)
    message.setResult("giftId", giftId)
    message.setResult("chestId", chestId)
    if code == 0 and (commonRewards or chestRewards):
        if giftConf["giftType"] == GiftType.MONTHCARD:
            itemId = giftConf["monthCard"]["name"]
            if itemId == config.MONTH_CARD_KINDID:
                weakdata.incrDayFishData(userId, WeakData.getMonthCardGift, 1)
            else:
                weakdata.incrDayFishData(userId,
                                         WeakData.getPermanentMonthCardGift, 1)
        else:
            availableGift.remove(giftId)
            gamedata.setGameAttr(userId, FISH_GAMEID, GameData.availableGift,
                                 json.dumps(availableGift))
        message.setResult("commonRewards", commonRewards)
        message.setResult("chestRewards", chestRewards)
    message.setResult("code", code)
    router.sendToUser(message, userId)

    productId = giftConf.get("productId", "")
    isIn, roomId, tableId, seatId = util.isInFishTable(userId)
    if isIn:
        mo = MsgPack()
        mo.setCmd("table_call")
        mo.setParam("action", "take_gift_reward")
        mo.setParam("gameId", FISH_GAMEID)
        mo.setParam("clientId", util.getClientId(userId))
        mo.setParam("userId", userId)
        mo.setParam("roomId", roomId)
        mo.setParam("tableId", tableId)
        mo.setParam("seatId", seatId)
        mo.setParam("productId", productId)
        router.sendTableServer(mo, roomId)