Exemplo n.º 1
0
def doSendLevelGift(userId, clientId):
    """
    获取升级礼包数据
    """
    message = MsgPack()
    message.setCmd("levelGiftData")
    message.setResult("gameId", FISH_GAMEID)
    message.setResult("userId", userId)
    giftInfo = []
    if not util.isVersionLimit(userId) and not util.isPurchaseLimit(userId) and util.isFinishAllNewbieTask(userId):
        levelGiftConf = config.getLevelGiftConf()
        gunLv = util.getGunLevelVal(userId, config.MULTIPLE_MODE)
        for giftId, giftConf in levelGiftConf.iteritems():
            if _isBought(userId, giftId):
                continue
            if not (giftConf["minLevel"] <= gunLv <= giftConf["maxLevel"]):
                continue
            now = int(time.time())
            timeout = giftConf["showTime"] * 60
            data = weakdata.getDayFishData(userId, WeakData.LevelUpCountDownData, [])
            if not data:
                weakdata.setDayFishData(userId, WeakData.LevelUpCountDownData, json.dumps([giftId, now]))
            else:
                if data[0] == giftId:
                    if timeout - (now - data[1]) > 0:
                        timeout = timeout - (now - data[1])
                    else:
                        timeout = 0
                else:
                    weakdata.setDayFishData(userId, WeakData.LevelUpCountDownData, json.dumps([giftId, now]))
            giftInfo.append(getGiftDetail(giftConf, util.getLanguage(userId, clientId), timeout))
    message.setResult("giftInfo", giftInfo)
    router.sendToUser(message, userId)
    return giftInfo
Exemplo n.º 2
0
 def sendGrandPrixInfo(self):
     """
     发送大奖赛信息 大奖赛相关信息(进入渔场后服务器主动推送)
     """
     if not grand_prix.isGrandPrixOpenTime():  # 是否为大奖赛开放时段 00:00 —— 23:00
         self._resetGrandPrixData()
         self._freeTimes = 0  # 免费次数
         weakdata.setDayFishData(self.userId,
                                 WeakData.grandPrix_getPointsInfo,
                                 json.dumps([]))
         weakdata.setDayFishData(self.userId, WeakData.grandPrix_freeTimes,
                                 self._freeTimes)
     if ftlog.is_debug():
         ftlog.debug("sendGrandPrixInfo", self.grandPrixStartTS,
                     self.isGrandPrixMode())
     signUpState = 1 if self.isGrandPrixMode() else 0  # 是否已经报名
     remainFreeTimes = config.getVipConf(self.vipLevel).get(
         "grandPrixFreeTimes", 0) - self._freeTimes  # 剩余免费次数
     openTime = "-".join(config.getGrandPrixConf("openTimeRange"))  # 时间范围
     mo = MsgPack()
     mo.setCmd("grand_prix_info")
     mo.setResult("gameId", FISH_GAMEID)
     mo.setResult("userId", self.userId)
     mo.setResult("seatId", self.seatId)
     mo.setResult("remainFreeTimes", remainFreeTimes)
     mo.setResult("fee", config.getGrandPrixConf("fee"))  # 报名费
     mo.setResult("openTime", openTime)  # 00:00 - 23:00
     mo.setResult(
         "isInOpenTime",
         1 if grand_prix.isGrandPrixOpenTime() else 0)  # 大奖在是否在开放时间段
     mo.setResult("signUpState", signUpState)  # 是否已报名大奖赛
     mo.setResult(
         "todayRankType",
         RankType.TodayGrandPrix)  # 今日榜Type,使用fish_ranking获取排行榜数据,下同
     mo.setResult("todayDate", util.timestampToStr(int(time.time()),
                                                   "%m/%d"))  # 今日榜时间
     mo.setResult("yesterdayRankType", RankType.LastGrandPrix)
     mo.setResult("yesterdayDate",
                  util.timestampToStr(int(time.time() - 86400), "%m/%d"))
     mo.setResult(
         "des",
         config.getMultiLangTextConf(
             config.getGrandPrixConf("info").get("des"),
             lang=self.lang))  # 每日积分超过2400送100珍珠,今日榜单每10分钟刷新1次,最终排名00:00公布
     mo.setResult("pointsInfo", grand_prix.getPointInfo(
         self.userId))  # 奖励积分 道具Id、道具数量、是否领取了奖励0|1
     mo.setResult("todayMaxPoints",
                  weakdata.getDayFishData(self.userId,
                                          WeakData.grandPrix_point,
                                          0))  # 今日最高积分
     GameMsg.sendMsg(mo, self.userId)
     if ftlog.is_debug():
         ftlog.debug("FishGrandPrixPlayer, userId =", self.userId, "mo =",
                     mo)
Exemplo n.º 3
0
def _main():
    userId = 116009
    import time
    import json
    from newfish.entity import config, util, store, weakdata
    from newfish.entity.redis_keys import GameData, WeakData
    import freetime.util.log as ftlog
    data = weakdata.getDayFishData(userId, 'ceshishuju', [])
    if not data:
        weakdata.setDayFishData(userId, 'ceshishuju', json.dumps(["7909", time.time()]))
        weakdata.setDayFishData(userId, 'ceshishuju', json.dumps(["7903", time.time()]))
Exemplo n.º 4
0
def _incQuestValue(userId, taskType, incVlaue, resetTime=0, fishPool=0, fpMultiple=0, gunX=0):
    """
    更新每日任务进度并检测;任务是否完成
    """
    if util.getDayStartTimestamp(resetTime) != util.getDayStartTimestamp(int(time.time())):
        resetTime = weakdata.getDayFishData(userId, "resetTime")
        if not resetTime:
            weakdata.setDayFishData(userId, WeakData.resetTime, int(time.time()))
            refreshDailyQuestData(userId)
    key = _getUserDailyQuestKey(userId)
    newValue = daobase.executeUserCmd(userId, "HINCRBY", key, str(taskType), incVlaue)
    confs = config.getDailyQuestConfsByType(taskType)
    todayQuest, _ = getTodayQuest(userId)
    questInfo = getUserQuestInfoData(userId)
    update = False
    for conf in confs:
        if conf and conf["taskId"] in todayQuest:
            if isinstance(conf.get("fishPool"), list) and conf.get("fishPool") and fishPool not in conf.get("fishPool"):
                continue
            if conf.get("fpMultiple", 0) > 0 and fpMultiple < conf.get("fpMultiple", 0):
                continue
            if conf.get("gunX", 0) > 0 and gunX < conf.get("gunX", 0):
                continue
            taskId = conf["taskId"]
            targetsNum = conf.get("targetsNum")
            process, state = questInfo.get(str(taskId), [0, QuestTaskState.Normal])
            # if newValue >= targetsNum and newValue - incVlaue < targetsNum:
            if state == QuestTaskState.Normal:
                update = True
                questInfo[str(taskId)] = [process + incVlaue, state]
                if process < targetsNum <= process + incVlaue:
                    questInfo[str(taskId)] = [targetsNum, QuestTaskState.Complete]
                    quest = todayQuest[taskId]
                    _sendQuestFinished(userId, quest)
                    module_tip.addModuleTipEvent(userId, "task", taskId)
                    taskLevel = conf.get("taskLevel", 0)
                    # questData = getDailyQuestData(userId)
                    # finishedStar = questData.get("finishedStar", 0)
                    # dailyQuestRewardFinishedStars = config.getDailyQuestRewardFinishedStars()
                    # for star in dailyQuestRewardFinishedStars:
                    #     if finishedStar >= star and finishedStar - taskLevel < star:
                    #         module_tip.addModuleTipEvent(userId, "task", star)
                    #         break
                    # 发送完成任务事件
                    from newfish.entity.event import DailyTaskFinishEvent
                    from newfish.game import TGFish
                    event = DailyTaskFinishEvent(userId, FISH_GAMEID, int(conf["taskId"]), taskLevel)
                    TGFish.getEventBus().publishEvent(event)
                    bireport.reportGameEvent("BI_NFISH_GE_TASK_FINISHED", userId, FISH_GAMEID, 0,
                                             0, int(conf["taskId"]), int(taskLevel), 0, 0, [], util.getClientId(userId))
    if update:
        setUserQuestInfoData(userId, questInfo)
Exemplo n.º 5
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)
 def _initData(self, userId, activityId, inTable):
     super(OneDayClearActivity, self)._initData(userId, activityId, inTable)
     self.isCleared = weakdata.getDayFishData(userId, activityId, 0)
     if self.isCleared == 0:
         ftlog.debug("OneDayClearActivity_initData")
         self.isCleared = 1
         weakdata.setDayFishData(self.userId, self.activityId, 1)
     if self.activityType == ActivityType.OneDayClearAc:
         self.timeDesc = " "
     else:
         if self.activityConfig["effectiveTime"]:
             self.timeDesc = config.getMultiLangTextConf("ID_ACTIVITY_TIME_DESC_2", lang=self.lang) % \
                             (self.getTimeDescStr(self.activityConfig["effectiveTime"]["start"]),
                             self.getTimeDescStr(self.activityConfig["effectiveTime"]["end"]))
         else:
             self.timeDesc = " "
Exemplo n.º 7
0
 def _resetGrandPrixData(self):
     """
     重置大奖赛相关数据
     """
     self.grandPrixStartTS = 0  # 大奖赛开始的时间戳
     self.grandPrixFireCount = 0  # 大奖赛剩余开火次数
     self.grandPrixTargetFish = {}  # 大奖赛目标鱼捕获数量
     self.grandPrixUseSkillTimes = []  # 大奖赛剩余技能使用次数
     self.grandPrixFishPoint = 0  # 捕鱼积分
     self.grandPrixSurpassCount = 0  # 大奖赛超越自己次数
     # self.grandPrixLevelFpMultiple = None        # 大奖赛火炮等级和倍率
     self._rankListCache = []  # 要超越的玩家缓存
     self._surpassUser = {}  # 要超越玩家数据
     self._saveGrandPrixData()  # 保存大奖赛信息
     weakdata.setDayFishData(self.userId, WeakData.grandPrix_surpassCount,
                             0)  # 大奖赛超越自己次数
Exemplo n.º 8
0
def addShareGroupId(userId, groupId):
    """
    添加分享到群的群ID
    """
    shareGroupIds = weakdata.getDayFishData(userId, "shareGroupIds", [])
    if ftlog.is_debug():
        ftlog.debug("addShareGroupId", userId, groupId, shareGroupIds)
    if groupId and groupId not in shareGroupIds:
        shareGroupIds.append(groupId)
        weakdata.setDayFishData(userId, WeakData.shareGroupIds, json.dumps(shareGroupIds))
        shareGroupTotalCount = config.getCommonValueByKey("shareGroupTotalCount")
        isReceiveReward = weakdata.getDayFishData(userId, "shareGroupReward", 0)
        if not isReceiveReward and len(shareGroupIds) >= shareGroupTotalCount:
            weakdata.setDayFishData(userId, WeakData.shareGroupReward, 1)
            if not util.isVersionLimit(userId):
                module_tip.addModuleTipEvent(userId, "invite", 0)
        getShareTaskInfo(userId)
Exemplo n.º 9
0
 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
Exemplo n.º 10
0
def getQuestInfo(userId, clientId):
    """
    获取玩家每日任务数据
    """
    resetTime = weakdata.getDayFishData(userId, "resetTime")
    if not resetTime:
        weakdata.setDayFishData(userId, "resetTime", int(time.time()))
        refreshQuestData(userId)                                            # 重置每日任务存档
    dailyQuestData = daily_quest.getDailyQuestData(userId)                  # 获取玩家每日任务数据
    mainQuestData = main_quest.getMainQuestData(userId, clientId)           # 获取主线任务数据
    mo = MsgPack()
    mo.setCmd("task")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("action", "update")
    mo.setResult("dailyTask", dailyQuestData)
    mo.setResult("mainTask", mainQuestData)
    router.sendToUser(mo, userId)
Exemplo n.º 11
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.º 12
0
def finishCheckin(userId, rewards=None, checkinDay=None, ts=None):
    """
    完成签到
    """
    # if not rewards or not checkinDay:
    #     kindId, rewards, checkinDay = getTodayCheckinRewards(userId)
    # if checkinDay:
    #     gamedata.setGameAttr(userId, FISH_GAMEID, GameData.checkinDay, checkinDay)
    #     weakdata.setDayFishData(userId, "isCheckin", 1)
    #     module_tip.resetModuleTipEvent(userId, "checkin")
    #     from newfish.game import TGFish
    #     from newfish.entity.event import CheckinEvent
    #     event = CheckinEvent(userId, FISH_GAMEID, checkinDay, rewards)
    #     TGFish.getEventBus().publishEvent(event)
    ts = ts or int(time.time())
    if not rewards or not checkinDay:
        checkinDay, rewards, _ = getTodayCheckinRewards(userId)
    if checkinDay:
        _isCheckContinuousBreak(userId, ts)
        gamedata.setGameAttr(userId, FISH_GAMEID,
                             GameData.continuousCheckinDayTS,
                             util.getDayStartTimestamp(int(ts)) + 86400)
        weakdata.setDayFishData(userId, "isCheckin", 1)
        module_tip.resetModuleTipEvent(userId, "checkin")
        vipLevel = util.getVipRealLevel(userId)
        # 注册当天签到不增加充值奖池.
        registTime = gamedata.getGameAttrInt(userId, FISH_GAMEID,
                                             GameData.registTime)
        if util.getDayStartTimestamp(int(
                time.time())) > util.getDayStartTimestamp(registTime):
            util.increaseExtraRechargeBonus(
                userId,
                config.getVipConf(vipLevel).get("checkinRechargeBonus", 0))
        from newfish.game import TGFish
        from newfish.entity.event import CheckinEvent
        event = CheckinEvent(userId, FISH_GAMEID, checkinDay, rewards)
        TGFish.getEventBus().publishEvent(event)
Exemplo n.º 13
0
 def _saveGrandPrixData(self):
     """
     保存大奖赛数据
     """
     weakdata.setDayFishData(self.userId, WeakData.grandPrix_startTS,
                             self.grandPrixStartTS)
     weakdata.setDayFishData(self.userId, WeakData.grandPrix_fireCount,
                             self.grandPrixFireCount)
     weakdata.setDayFishData(self.userId, WeakData.grandPrix_fishPoint,
                             self.grandPrixFishPoint)
     weakdata.setDayFishData(self.userId, WeakData.grandPrix_surpassCount,
                             self.grandPrixSurpassCount)
     weakdata.setDayFishData(self.userId, WeakData.grandPrix_useSkillTimes,
                             json.dumps(self.grandPrixUseSkillTimes))
     weakdata.setDayFishData(self.userId, WeakData.grandPrix_targetFish,
                             json.dumps(self.grandPrixTargetFish))
Exemplo n.º 14
0
def _exchange(userId, mgType, mode, idx, count):
    """
    兑换逻辑, 通过mgType+mode+idx可以唯一确定兑换数据.
    """
    code = 1
    key = "%s_%d" % (mgType, mode)
    exchangedTimes = weakdata.getDayFishData(userId,
                                             WeakData.superbossExchangedTimes,
                                             {})
    exchangedTimes.setdefault(key, {})
    conf = config.getSuperBossExchangeConf("exchange").get(key, {})
    rewards = []
    reList = ""
    costList = ""
    lang = util.getLanguage(userId)
    info = config.getMultiLangTextConf("ID_EXCHANGE_ERR_INFO_8", lang=lang)
    # 根据兑换类型找到bigRoomId,用于bi事件参数.
    bigRoomId = 0
    for _bigRoomId, val in config.getSuperBossCommonConf().iteritems():
        if val["mgType"] == mgType:
            bigRoomId = int(str(_bigRoomId)[0:5])
            break
    for _exchangeItem in conf.get("exchangeItems", []):
        _id = _exchangeItem["idx"]
        if _id != idx:
            continue
        remainTimes = _exchangeItem["exchangeTimes"]
        remainTimes = max(0, remainTimes - exchangedTimes[key].get(
            str(_id), 0)) if remainTimes >= 0 else remainTimes
        if not (count >= 1 and (remainTimes == -1 or remainTimes >= count)):
            continue
        costItems = _exchangeItem.get("costItems", [])
        gainItems = _exchangeItem.get("gainItems", [])
        for _val in costItems:
            _val["count"] *= count
            kindName = config.getMultiLangTextConf("ID_CONFIG_KINDID_ITEM:%s" %
                                                   _val["name"],
                                                   lang=lang)
            costDes = kindName + "x" + str(_val["count"])
            costList = costList + costDes + " "
            if util.balanceItem(userId, _val["name"]) < _val["count"]:
                code = 2
                break
        _ret = util.consumeItems(userId, costItems,
                                 "BI_NFISH_SUPERBOSS_EXCHANGE", bigRoomId,
                                 mode)
        if not _ret:
            code = 2
        else:
            code = 0
            if remainTimes > 0:
                exchangedTimes[key][str(_id)] = exchangedTimes[key].setdefault(
                    str(_id), 0) + count
                weakdata.setDayFishData(userId,
                                        WeakData.superbossExchangedTimes,
                                        json.dumps(exchangedTimes))
            reDict = {}
            for i in range(count):
                for val in gainItems:
                    if val.get("minCount", 0) and val.get("maxCount", 0):
                        reDict.setdefault(val["name"], 0)
                        reDict[val["name"]] += random.randint(
                            val["minCount"], val["maxCount"])
            for k, v in reDict.iteritems():
                rewards.append({"name": k, "count": v})
                if k == config.CHIP_KINDID:
                    kindName = config.getMultiLangTextConf(
                        "ID_CONFIG_KINDID_USER:CHIP", lang=lang)
                else:
                    kindName = config.getMultiLangTextConf(
                        "ID_CONFIG_KINDID_ITEM:%s" % k, lang=lang)
                reDes = kindName + "x" + str(v)
                reList = reList + reDes + " "
            if util.addRewards(userId, rewards, "BI_NFISH_SUPERBOSS_EXCHANGE",
                               bigRoomId, mode) != 0:
                ftlog.error("item_exchange, userId =", userId, "bigRoomId =",
                            bigRoomId, "mode =", mode, "idx =", idx, "count =",
                            count, "rewards =", rewards, "key =", key)
    if code == 0:
        bireport.reportGameEvent("BI_NFISH_GE_ITEM_EXCHANGE", userId,
                                 FISH_GAMEID, 0, 0, 0, 0, 0, 0,
                                 [userId, mgType, mode, idx],
                                 util.getClientId(userId))
        from newfish.game import TGFish
        event = MiniGameBossExchange(userId, config.FISH_GAMEID, count)
        TGFish.getEventBus().publishEvent(event)
        info = config.getMultiLangTextConf(
            "ID_EXCHANGE_RESULT_INFO_1",
            lang=lang).format(time.strftime("%X", time.localtime()), reList,
                              costList)
    return code, rewards, info
Exemplo n.º 15
0
def playMinigame(roomId, userId, idx, mode, userIds, groupIdx):
    """
    点击小游戏
    """
    bigRoomId, _ = util.getBigRoomId(roomId)
    subkey = "%s_%d" % (bigRoomId, mode)
    mgType = config.getSuperBossCommonConf().get(str(subkey), {}).get("mgType", "")
    key = "%s_%d" % (mgType, mode)
    mo = MsgPack()
    mo.setCmd("superboss_minigame")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("roomId", roomId)
    mo.setResult("mode", mode)
    mo.setResult("idx", idx)
    mo.setResult("type", mgType)
    code = 1
    data = {}
    gainItems =[]
    if mgType in MINIGAME_TYPE_LIST:
        superbossPlayedTimes = weakdata.getDayFishData(userId, WeakData.superbossMGPlayedTimes, {})
        playedTimes = superbossPlayedTimes.setdefault(key, 0)
        conf = config.getSuperBossMiniGameConf()
        vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
        maxTimesList = conf.get("info", {}).get(key, {}).get("maxTimes", [])
        maxTimes = maxTimesList[vipLevel] if maxTimesList and len(maxTimesList) > vipLevel else 0
        items = conf.get("game", {}).get(key, [])
        rewards = []
        _idx = 0
        isCanPlay = True
        # 只能抽取满足消耗的最高等级抽奖.
        # if mgType == "queen":
        #     # 抽奖消耗由多到少配置。
        #     for _idx, _val in enumerate(itemsinfo):
        #         # 检查消耗是否满足条件
        #         for v in _val["costs"]:
        #             if util.balanceItem(userId, v["name"]) < v["count"]:
        #                 break
        #         else:
        #             isCanPlay = (idx == _idx)
        #             break
        if 0 <= idx < len(items) and (maxTimes == -1 or maxTimes > playedTimes) and isCanPlay:
            costItems = items[idx]["costs"]
            if mgType == "box":
                gainItems = items[idx]["rewards"][groupIdx].values()[0]
            else:
                gainItems = items[idx]["rewards"]
            for _val in costItems:
                if util.balanceItem(userId, _val["name"]) < _val["count"]:
                    code = 2
                    break
            else:
                _ret = util.consumeItems(userId, costItems, "BI_NFISH_SUPERBOSS_EXCHANGE", bigRoomId, mode)
                if not _ret:
                    code = 2
                else:
                    superbossPlayedTimes[key] += 1
                    weakdata.setDayFishData(userId, WeakData.superbossMGPlayedTimes, json.dumps(superbossPlayedTimes))
                    _idx = util.selectIdxByWeight([v["probb"] for v in gainItems])
                    if _idx >= 0:
                        rewards = [{"name": gainItems[_idx]["name"], "count": gainItems[_idx]["count"]}]
                        isIn, roomId, tableId, _ = util.isInFishTable(userId)
                        if isIn:
                            code = table_remote.addRewardsToTable(roomId, tableId, userId, rewards, "BI_NFISH_SUPERBOSS_BOX", mode)
                        else:
                            code = util.addRewards(userId, rewards, "BI_NFISH_SUPERBOSS_BOX", bigRoomId, mode)
                        if code != 0:
                            ftlog.error("minigame, userId =", userId, "bigRoomId =", key, "idx =", idx, "rewards =", rewards)
            playedTimes = superbossPlayedTimes.get(key, 0)
            remainTimes = max(0, maxTimes - playedTimes) if maxTimes >= 0 else -1
            data = {"remainTimes": remainTimes, "rewards": rewards, "rewardIndex": _idx}
    else:
        ftlog.warn("minigame, type error, userId =", userId, "roomId =", roomId, "mode =", mode, "idx =", idx, "mgType =", mgType)
    mo.setResult("code", code)
    turntable_rewards = []
    if mgType == "dragon":
        for gainItem in gainItems:
            for key in gainItem.keys():
                if key == "count":
                    turntable_rewards.append(gainItem[key])
        data["turntable_rewards"] = turntable_rewards
    mo.setResult("data", data)
    router.sendToUser(mo, userId)
    if mgType == "dragon" and code == 0:
        userIds = userIds
        GameMsg.sendMsg(mo, userIds)
    if code == 0:
        from newfish.game import TGFish
        event = PlayMiniGame(userId, config.FISH_GAMEID)
        TGFish.getEventBus().publishEvent(event)
    checkModuleTip(bigRoomId, userId, mode)
Exemplo n.º 16
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.º 17
0
def doBuyFishGift(userId, clientId, giftId, buyType=None, itemId=0):
    """
    购买礼包
    """
    if ftlog.is_debug():
        ftlog.debug("doBuyFishGift===>", userId, clientId, giftId, buyType,
                    itemId)
    giftConf = getGiftConf(clientId, giftId)
    if not giftConf:
        return
    buyType = buyType or giftConf.get("buyType")
    # 使用钻石购买
    if buyType == config.BT_DIAMOND:
        price = giftConf.get("discountPrice", 0)
        price, isSucc = store.getUseRebateItemPrice(userId, itemId, price,
                                                    buyType, giftId,
                                                    clientId)  # 满减券之后的钻石 满减券
        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:
                _sendBuyFishGiftRet(userId, clientId, giftId, 1)  # 钻石购买结果
                return
    # 使礼包变为可领取状态
    code, extraRwards = 1, None
    if giftConf["giftType"] == GiftType.BANKRUPT:  # 破产礼包
        code = BankruptGift(userId, clientId).addGiftData(int(giftId))
        if code == 0:
            # 购买成功后更新破产礼包购买次数并存储礼包等级.
            bankruptGiftInfo = gamedata.getGameAttrJson(
                userId, FISH_GAMEID, GameData.bankruptGiftInfo, [])
            if bankruptGiftInfo:
                fishPool, grade = bankruptGiftInfo[:2]
                buyBankruptGift = weakdata.getDayFishData(
                    userId, WeakData.buyBankruptGiftTimesPerPool, {})
                buyBankruptGift.setdefault(str(fishPool),
                                           {}).setdefault("count", 0)
                buyBankruptGift[str(fishPool)]["count"] += 1  # 购买次数
                buyBankruptGift[str(fishPool)]["grade"] = grade  # 购买等级
                weakdata.setDayFishData(userId,
                                        WeakData.buyBankruptGiftTimesPerPool,
                                        json.dumps(buyBankruptGift))
        gamedata.delGameAttr(userId, FISH_GAMEID, GameData.bankruptGiftInfo)
    elif giftConf["giftType"] == GiftType.MONTHCARD:  # 月卡|永久月卡礼包
        code, extraRwards = MonthCardGift(userId,
                                          clientId).addGiftData(int(giftId))
    _sendBuyFishGiftRet(userId, clientId, giftId, code, extraRwards)
    # 购买礼包事件
    if code != 0:
        return
    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.º 18
0
def loginGame(userId, gameId, clientId, iscreate, isdayfirst):
    """
    用户登录一个游戏, 游戏自己做一些其他的业务或数据处理
    """
    if ftlog.is_debug():
        ftlog.debug("userId =", userId, "gameId =", gameId, "clientId =",
                    clientId, "iscreate =", iscreate, "isdayfirst =",
                    isdayfirst, gdata.name())
    gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.gunLevel_m, 2101)
    if isdayfirst:
        sendVipSpringFestivalRewards(userId)
    if isdayfirst:
        vipAutoSupplyPerDay(userId)
    if isdayfirst:
        from newfish.entity.quest import daily_quest
        from newfish.entity import weakdata
        resetTime = weakdata.getDayFishData(userId, "resetTime")
        if not resetTime:
            weakdata.setDayFishData(userId, "resetTime", int(time.time()))
            daily_quest.refreshDailyQuestData(userId)
        # FTLoopTimer(1, 0, util.doSendFishNotice, userId).start()
    gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.vipShow, 1)
    serverVersion = gamedata.getGameAttrInt(userId, gameId,
                                            GameData.serverVersion)
    if isdayfirst and gamedata.getGameAttr(
            userId, FISH_GAMEID, GameData.hasBoughtMonthCard) is None:
        from hall.entity import hallitem
        userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
        item = userBag.getItemByKindId(config.PERMANENT_MONTH_CARD_KINDID) or \
               userBag.getItemByKindId(config.MONTH_CARD_KINDID)
        bought = 1 if item else 0
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.hasBoughtMonthCard,
                             json.dumps(bought))
    if serverVersion and serverVersion <= 20180907:
        # 珍珠数量调整
        util.adjustPearlCount(userId)
    if serverVersion and serverVersion <= 20180918:
        # 老玩家屏蔽10元话费卡兑换
        gamedata.setGameAttr(userId, gameId, GameData.exchangeCount, 1)
    if serverVersion and serverVersion <= 20180928:
        # 老玩家金猪出现次数数据迁移
        from newfish.entity import share_system
        from newfish.entity.share_system import FlyingPig
        shareClass = FlyingPig(userId)
        flyPigFinishCount = shareClass.shareData[
            share_system.INDEX_FINISH_COUNT]
        gamedata.incrGameAttr(userId, FISH_GAMEID, GameData.flyPigFinishCount,
                              flyPigFinishCount)
    # 清理金币购买记录,19/12/25日0点后开始检测
    if int(time.time()) >= util.getTimestampFromStr("2019-12-25 00:00:00") and \
            not gamedata.getGameAttrInt(userId, gameId, "resetBuyCoinCount"):
        gamedata.delGameAttr(userId, FISH_GAMEID, GameData.buyCoinCount)
        gamedata.setGameAttr(userId, gameId, "resetBuyCoinCount", 1)
    if not serverVersion or int(serverVersion) != SERVER_VERSION:
        gamedata.setGameAttr(userId, gameId, GameData.serverVersion,
                             SERVER_VERSION)

    if not util.isFinishAllNewbieTask(userId):  # 没完成所有新手引导,不主动弹出每日签到和最新消息
        return

    # 限定玩家比赛幸运值.
    from newfish.entity.match_record import MatchRecord
    vip = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
    for roomId in [44102]:
        key = "initLuckyValue:%d" % int(roomId)
        initVal = config.getVipConf(vip).get(key, 10000)
        record = MatchRecord.loadRecord(FISH_GAMEID, userId, roomId)
        record.luckyValue = min(record.luckyValue, initVal)
        MatchRecord.saveRecord(FISH_GAMEID, userId, roomId, record)
Exemplo n.º 19
0
def saveGrandPrixData(userId, startTs, fireCount, fishPoint, useSkillTimes,
                      targetFish, getPointsInfo, todayMaxPoints, freeTimes):
    """
    保存大奖赛数据
    """
    weakdata.setDayFishData(userId, WeakData.grandPrix_startTS, startTs)
    weakdata.setDayFishData(userId, WeakData.grandPrix_fireCount, fireCount)
    weakdata.setDayFishData(userId, WeakData.grandPrix_fishPoint, fishPoint)
    weakdata.setDayFishData(userId, WeakData.grandPrix_useSkillTimes,
                            json.dumps(useSkillTimes))
    weakdata.setDayFishData(userId, WeakData.grandPrix_targetFish,
                            json.dumps(targetFish))
    # weakdata.setDayFishData(userId, WeakData.grandPrix_levelFpMultiple, json.dumps(levelFpMultiple))
    weakdata.setDayFishData(userId, WeakData.grandPrix_getPointsInfo,
                            json.dumps(getPointsInfo))
    weakdata.setDayFishData(userId, WeakData.grandPrix_point, todayMaxPoints)
    weakdata.setDayFishData(userId, WeakData.grandPrix_freeTimes, freeTimes)