Exemplo n.º 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
Exemplo n.º 2
0
def getGiftDetail(giftConf, hasBought, enableDayIdx, lang):
    """获取礼包的详细信息"""
    gift = {}
    gift["giftId"] = giftConf["giftId"]
    # gift["giftName"] = giftConf["giftName"]
    gift["giftName"] = config.getMultiLangTextConf(giftConf["giftName"],
                                                   lang=lang)
    gift["productId"] = giftConf["productId"]
    gift["available"] = 0
    gift["price"] = giftConf["price"]
    gift["price_direct"] = giftConf.get("price_direct", 0)
    gift["price_diamond"] = giftConf.get("price_diamond", 0)
    gift["buyType"] = giftConf["buyType"]
    gift["otherBuyType"] = giftConf.get("otherBuyType", {})
    gift["otherProductInfo"] = {}
    # 特殊处理代购券商品数据
    from newfish.entity import store
    # gift["otherProductInfo"][BT_VOUCHER] = store.getVoucherProduct(gift["otherBuyType"])
    gift["otherProductInfo"] = store.getOtherBuyProduct(
        giftConf.get("otherBuyType", {}), giftConf["buyType"])
    gift["items"] = []
    for item in giftConf["giftInfo"]:
        newItems = []
        for v in item["items"]:
            newVal = config.rwcopy(v)
            if util.isChestRewardId(v["itemId"]):
                newVal["info"] = chest_system.getChestInfo(v["itemId"])
            newItems.append(newVal)
        gift["items"].append({item["day_idx"] + 1: newItems})
    gift["hasBought"] = hasBought
    gift["enableDayIdx"] = enableDayIdx
    return gift
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
Exemplo n.º 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)
Exemplo n.º 5
0
def getMainQuestData(userId, clientId):
    """
    获取主线任务数据
    """
    mainQuestDict = {}
    try:
        if not isFinishAllMainQuest(userId):
            currSectionId = gamedata.getGameAttr(
                userId, FISH_GAMEID, GameData.currSectionId)  # 当前章节 642000
            if currSectionId:
                sectionConf = config.getMainQuestSectionConf(
                    clientId, currSectionId)
                finishTaskIds = getSection(
                    userId, currSectionId)[SectionIndex.FinishTasks]
                mainQuestDict["sectionId"] = sectionConf["sectionId"]
                mainQuestDict["sortId"] = sectionConf["sortId"]
                mainQuestDict["progress"] = [
                    len(finishTaskIds),
                    len(sectionConf["taskIds"])
                ]
                # mainQuestDict["honorId"] = sectionConf["honorId"]                             # 勋章Id
                # mainQuestDict["sectionRewards"] = sectionConf["rewards"]                      # 章节奖励
                # mainQuestDict["state"] = getSection(userId, sectionConf["sectionId"])[SectionIndex.State]     # 章节奖励状态
                mainQuestDict["display"] = gamedata.getGameAttrInt(
                    userId, FISH_GAMEID, GameData.mainQuestDisplay)
                mainQuestDict["tasks"] = getSectionTasksInfo(
                    userId, sectionConf["sectionId"])  # 章节小任务
                starRewards = []
                sectionData = getSection(userId, currSectionId)  # 获取章节数据
                gotReward = []
                for val in sectionConf["starRewards"]:
                    chestRewards = []
                    for v in val["rewards"]:
                        itemId = v["itemId"]
                        if util.isChestRewardId(itemId):
                            chestRewards.append({
                                "chestId":
                                itemId,
                                "chestInfo":
                                chest_system.getChestInfo(itemId)
                            })
                    starRewards.append({
                        "rewards": val["rewards"],
                        "finishedStar": val["star"],
                        "chestRewards": chestRewards
                    })
                    if int(val["star"]) in sectionData[
                            SectionIndex.TakenStars]:
                        gotReward.append(int(val["star"]))
                mainQuestDict["rewardData"] = starRewards
                mainQuestDict["finishedStar"] = _getSectionStar(
                    userId, clientId, currSectionId)
                mainQuestDict["gotReward"] = gotReward
    except:
        ftlog.error()
    return mainQuestDict
def getAllRewardList():
    """
    获取奖励列表,摇钱树界面左边显示的界面
    """
    temRewardList = []
    rewardListConf = config.getLuckyTreeConf("rewardList")
    for _val in rewardListConf:
        itemId = _val.get("reward", {}).get("name", 0)
        if util.isChestRewardId(itemId):
            chestReward = chest_system.getChestInfo(itemId)
            _val["reward"] = chestReward
        temRewardList.append(_val)
    return temRewardList
Exemplo n.º 7
0
def getInviteTasks(userId, actionType):
    weakDatas = weakdata.getDayFishDataAll(userId, FISH_GAMEID)
    taskConfs_ = config.getInviteTasks(actionType)
    taskConfs = taskConfs_.values()
    taskConfs = sorted(taskConfs, key=lambda data: data["Id"])
    if actionType == NewPlayerAction:
        taskState = strutil.loads(weakDatas.get("inviteTasks", "[]"))
        playerNums = len(strutil.loads(weakDatas.get("inviteNewPlayers", "[]")))

    else:
        taskState = strutil.loads(weakDatas.get("recallTasks", "[]"))
        playerNums = len(strutil.loads(weakDatas.get("recallPlayers", "[]")))

    taskStartIndex = len(taskState) / OneGroupNum * OneGroupNum
    taskStartIndex = min((len(taskConfs) / OneGroupNum - 1) * OneGroupNum, taskStartIndex)

    # 奖励
    taskInfos = []
    tipsTaskIds = []
    for m in range(taskStartIndex, taskStartIndex + 5):
        if m >= len(taskConfs):
            break
        taskConf = taskConfs[m]
        taskId = taskConf["Id"]
        taskInfo = {}
        taskInfo["Id"] = taskId
        rewards = []
        for _reward in taskConf["rewards"]:
            rewardMap = {}
            kindId = _reward["name"]
            rewardMap["name"] = kindId
            rewardMap["count"] = _reward["count"]
            rewardMap["info"] = {}
            if util.isChestRewardId(kindId):
                rewardMap["info"] = chest_system.getChestInfo(kindId)
            rewards.append(rewardMap)
        taskInfo["rewards"] = rewards
        taskInfo["target"] = taskConf["target"]
        state = 0
        if taskId in taskState:
            state = 2
        elif playerNums >= taskConf["target"]:
            tipsTaskIds.append(taskId)
            state = 1
        taskInfo["state"] = state
        taskInfos.append(taskInfo)

    module_tip.resetModuleTip(userId, "invitetasks")
    if tipsTaskIds:
        module_tip.addModuleTipEvent(userId, "invitetasks", tipsTaskIds)
    return taskInfos, playerNums
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 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
Exemplo n.º 11
0
def sendFishCheckinInfo(userId, continueWindow=0):
    """
    发送签到详情
    :param continueWindow: 0:用户点击签到请求 1:客户端登录时自动请求
    """
    if util.isVersionLimit(userId):
        return
    checkinDay = gamedata.getGameAttrInt(userId, FISH_GAMEID,
                                         GameData.checkinDay)
    isCheckin = weakdata.getDayFishData(userId, "isCheckin", 0)
    code = 1
    if (continueWindow and isCheckin):
        code = 2
    elif util.isFinishAllNewbieTask(userId):
        code = 0
        if not isCheckin:
            if checkinDay == len(config.getCheckinConf()):
                checkinDay = 0
                gamedata.setGameAttr(userId, FISH_GAMEID, GameData.checkinDay,
                                     checkinDay)
            module_tip.addModuleTipEvent(userId, "checkin", checkinDay)
    mo = MsgPack()
    mo.setCmd("fishCheckin")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("loginDays",
                 gamedata.getGameAttr(userId, FISH_GAMEID, GameData.loginDays))
    mo.setResult("day", checkinDay if isCheckin else checkinDay + 1)
    mo.setResult("checkin", isCheckin)
    rewards = []
    for rewardConf in config.getCheckinConf().values():
        if util.isChestRewardId(rewardConf["shareReward"]["name"]):
            rewards.append(rewardConf["shareReward"])
        else:
            rewards.append(rewardConf["normalReward"])
    mo.setResult("rewards", rewards)
    mo.setResult("continueWindow", continueWindow)
    mo.setResult("code", code)
    router.sendToUser(mo, userId)
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
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)
Exemplo n.º 15
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)
Exemplo n.º 16
0
def getDailyQuestData(userId):
    """
    获取玩家每日任务数据
    """
    level = util.getUserLevel(userId)
    if level < config.getCommonValueByKey("dailyQuestOpenLevel"):
        return {}
    if not util.isFinishAllNewbieTask(userId):
        return {}
    lang = util.getLanguage(userId)
    # 替换为新版任务时,重置玩家每日任务数据.
    key = _getUserDailyQuestGroupLvKey(userId)
    groupLvData = gamedata.getGameAttrJson(userId, FISH_GAMEID, key, {})
    if len(groupLvData) == 0:
        refreshDailyQuestData(userId)
    groupIdList = config.getDailyQuestGroupOrder()
    dailyQuestData = {}
    todayQuest, activeLv = getTodayQuest(userId)
    # userData = _getUserQuestData(userId)
    finishedStar = 0
    key = _getUserDailyQuestWeeklyRewardKey(userId)
    ret = json.loads(weakdata.getWeekFishData(userId, key, "{}"))
    finishedWeekStar = ret.get("star", 0)
    questInfo = getUserQuestInfoData(userId)
    tasks = []
    update = False
    questList = sorted(todayQuest.items(), key=lambda val: groupIdList.index(val[1]["groupId"]))
    all = len(todayQuest) == len(groupIdList)
    # for k, v in todayQuest.iteritems():
    for _val in questList:
        k, v = _val
        task = {}
        task["taskId"] = k
        task["taskLevel"] = v["taskLevel"]
        task["targetsNum"] = v["targetsNum"]
        # progress = userData.get(v["taskType"], 0)
        progress, state = questInfo.get(str(k), [0, QuestTaskState.Normal])
        if progress >= task["targetsNum"] or state >= QuestTaskState.Complete:
            progress = task["targetsNum"]
            # 已领取
            if state == QuestTaskState.Received:
                finishedStar += task["taskLevel"]
            elif state == QuestTaskState.Normal:
                state = QuestTaskState.Complete
                questInfo[str(k)] = [progress, state]
                update = True
        task["progress"] = progress
        task["taskState"] = state
        task["rewards"] = v["rewards"]
        task["chestRewards"] = []
        for val in v["rewards"]:
            itemId = val["name"]
            if util.isChestRewardId(itemId):
                task["chestRewards"].append({"chestId": itemId, "chestInfo": chest_system.getChestInfo(itemId)})
        # if v["taskType"] == TaskType.CoinNum and v["des"].find("%s") >= 0:
        #    task["des"] = v["des"] % util.formatScore(v["targetsNum"])
        # elif v["des"].find("%d") >= 0:
        #    task["des"] = v["des"] % v["targetsNum"]
        # else:
        #    task["des"] = v["des"]
        vDesId = v["des"]
        vDes = config.getMultiLangTextConf(str(vDesId), lang=lang)
        if v["taskType"] == TaskType.CoinNum and vDes.find("%s") >= 0:
            task["des"] = vDes % util.formatScore(v["targetsNum"], lang=lang)
        elif vDes.find("%d") >= 0:
            task["des"] = vDes % v["targetsNum"]
        elif vDes.count("{}") >= 2:
            task["des"] = vDes.format(v["gunX"], v["targetsNum"])
        else:
            task["des"] = vDes
        tasks.append(task)
    if update:
        setUserQuestInfoData(userId, questInfo)
    dailyQuestReward = config.getDailyQuestRewardConf(activeLv, all)
    gotReward = _getUserQuestRewardData(userId, "day")
    gotWeekReward = _getUserQuestRewardData(userId, "week")
    dailyQuestData["tasks"] = tasks
    rewardData = [dailyQuestReward[str(key)] for key in sorted(map(int, dailyQuestReward.keys()))]
    for v in rewardData:
        v["chestRewards"] = []
        for val in v["rewards"]:
            itemId = val["itemId"]
            if util.isChestRewardId(itemId):
                v["chestRewards"].append({"chestId": itemId, "chestInfo": chest_system.getChestInfo(itemId)})
    dailyQuestData["rewardData"] = rewardData
    dailyQuestData["finishedStar"] = finishedStar
    dailyQuestData["gotReward"] = gotReward
    dailyQuestData["finishedWeekStar"] = finishedWeekStar
    dailyQuestData["gotWeekReward"] = gotWeekReward
    dailyQuestData["refreshData"] = config.getDailyQuestRefreshConf()
    dailyQuestData["refreshedTimes"] = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.refreshDailyQuestTimes)
    return dailyQuestData
Exemplo n.º 17
0
 def _isChestReward(self, itemId):
     # chestType = int(str(itemId)[0:2])
     # if len(str(itemId)) >= 5 and 31 <= chestType <= 37:
     #     return True
     # return False
     return util.isChestRewardId(itemId)
Exemplo n.º 18
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
Exemplo n.º 19
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)
Exemplo n.º 20
0
def getLevelRewardsData(userId):
    """
    获取等级奖励数据
    """
    clientId = util.getClientId(userId)
    userLevel = util.getUserLevel(userId)
    levels = gamedata.getGameAttrJson(userId, config.FISH_GAMEID,
                                      GameData.levelRewards, [])
    levelRewards = config.getLevelRewards(clientId)
    _level = userLevel
    _rewards = []
    if util.isFinishAllNewbieTask(userId):
        isIn, roomId, _, _ = util.isInFishTable(userId)
        if isIn and util.getRoomTypeName(roomId) in config.NORMAL_ROOM_TYPE:
            lang = util.getLanguage(userId)
            sortedLevelRewards = sorted(levelRewards.items(),
                                        key=lambda v: int(v[0]))
            for item in sortedLevelRewards:
                level, val = item
                level = int(level)
                if val and level not in levels:
                    _level = level
                    for _r in val.get("rewards", []):
                        itemId = _r["name"]
                        desId = _r.get("des")
                        if desId:
                            des = config.getMultiLangTextConf(str(desId),
                                                              lang=lang)
                        else:
                            des = ""
                        if util.isChestRewardId(itemId):
                            _rewards.append({
                                "name":
                                itemId,
                                "count":
                                _r["count"],
                                "des":
                                des,
                                "info":
                                chest_system.getChestInfo(itemId)
                            })
                        else:
                            _rewards.append({
                                "name": itemId,
                                "count": _r["count"],
                                "des": des,
                                "info": {}
                            })
                    if level <= userLevel:
                        module_tip.addModuleTipEvent(userId, "levelrewards",
                                                     _level)
                    break

    mo = MsgPack()
    mo.setCmd("levelRewardsData")
    mo.setResult("gameId", config.FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("level", _level)
    mo.setResult("rewards", _rewards)
    router.sendToUser(mo, userId)
    ftlog.debug("level_rewards, userId =", userId, "userLevel =", userLevel,
                "level =", _level, "rewards =", _rewards)