示例#1
0
 def sendCmpttTaskInfo(self):
     """
     发送夺宝赛任务倒计时信息
     """
     userIds = []
     for uid in self.table.getBroadcastUids():
         if util.isFinishAllNewbieTask(uid):
             userIds.append(uid)
     if self.sendInfoTimer:
         self.sendInfoTimer.cancel()
     if not userIds:
         return
     if self.state == 0:
         self.sendInfoTimer = FTLoopTimer(self.sendInfoTime, 0,
                                          self.sendCmpttTaskInfo)
         self.sendInfoTimer.start()
     else:
         return
     timeLeft = int(
         self.taskInterval) - int(time.time() - self.recordReloadTime)
     if timeLeft <= 0:
         return
     msg = MsgPack()
     msg.setCmd("cmptt_task")
     msg.setResult("gameId", FISH_GAMEID)
     msg.setResult("action", "info")
     msg.setResult("timeLeft", timeLeft)
     GameMsg.sendMsg(msg, userIds)
示例#2
0
def sendFishCheckinRewardInfo(userId, day):
    """
    领取签到奖励
    """
    mo = MsgPack()
    mo.setCmd("fishCheckinReward")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    ts = int(time.time())
    code = 1
    if util.isFinishAllNewbieTask(userId):
        # kindId, rewards, checkinDay = getTodayCheckinRewards(userId)
        # if kindId and rewards :
        #     code = util.addRewards(userId, rewards, "BI_NFISH_CHECKIN_REWARDS")
        #     if code == 0:
        #         finishCheckin(userId, rewards, checkinDay)
        #         mo.setResult("kindId", kindId)
        #         mo.setResult("rewards", rewards)
        checkinDay, totalRewards, rd = getTodayCheckinRewards(userId)
        if totalRewards:
            code = util.addRewards(userId, totalRewards,
                                   "BI_NFISH_CHECKIN_REWARDS")
            finishCheckin(userId, totalRewards, checkinDay, ts=ts)
            for k, v in rd.iteritems():
                mo.setResult(k, v)
            mo.setResult("totalRewards", totalRewards)
            if code != 0:
                ftlog.error("checkin, userId =", userId, "day =", day,
                            "checkinday =", checkinDay, "rd =", rd)
    mo.setResult("day", day)
    mo.setResult("code", code)
    router.sendToUser(mo, userId)
示例#3
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
示例#4
0
def getLevelFundsData(userId, clientId, mode):
    """
    获取成长基金数据
    """
    message = MsgPack()
    message.setCmd("levelFundsData")
    message.setResult("gameId", config.FISH_GAMEID)
    message.setResult("userId", userId)
    if mode == -1:
        show = []
        for m in [config.CLASSIC_MODE, config.MULTIPLE_MODE]:
            isAllTaken = isShow(userId, clientId, m)[-1]
            if isAllTaken:
                show.append(1)
            else:
                show.append(0)
        message.setResult("show", show)
        message.setResult("mode", mode)
        router.sendToUser(message, userId)
        return
    if mode == 1:
        module_tip.resetModuleTipEvent(userId, "levelfundsNew")
    else:
        module_tip.resetModuleTipEvent(userId, "levelfunds")
    userLv, funds, userIdxs, lf_funds, lf_rewards, isAllTaken = isShow(userId, clientId, mode)
    message.setResult("level", userLv)
    fundsList = []
    addTipPIds = []
    isIn, roomId, _, _ = util.isInFishTable(userId)
    if isIn and not isAllTaken and util.isFinishAllNewbieTask(userId):
        for idx in userIdxs:
            productConf = funds[idx - 1]
            _funds = {}
            productId = productConf.get("productId")
            _funds["Id"] = productId
            _funds["state"] = 1 if idx in lf_funds else 0
            _funds["title"] = productConf.get("title")
            _funds["name"] = config.getMultiLangTextConf(productConf.get("name"), lang=util.getLanguage(userId))
            _funds["price_direct"] = productConf.get("price_direct")
            _funds["price_diamond"] = productConf.get("price_diamond")
            _funds["buyType"] = productConf.get("buyType")
            _funds["otherBuyType"] = productConf.get("otherBuyType")
            from newfish.entity import store
            _funds["otherProductInfo"] = store.getOtherBuyProduct(productConf.get("otherBuyType"), productConf.get("buyType"))
            hasTip, _funds["rewardsState"] = _getLevelFundsRewardState(userId, clientId, idx, mode, lf_rewards, lf_funds)
            if hasTip:
                addTipPIds.append(productId)
            fundsList.append(_funds)
    message.setResult("fundsList", fundsList)
    message.setResult("mode", mode)
    router.sendToUser(message, userId)
    if addTipPIds:
        if ftlog.is_debug():
            ftlog.debug("getLevelFundsData", mode)
        if mode == 1:
            module_tip.addModuleTipEvent(userId, "levelfundsNew", addTipPIds)
        else:
            module_tip.addModuleTipEvent(userId, "levelfunds", addTipPIds)
示例#5
0
def receiveTaskReward(userId, taskId):
    """
    领取荣耀任务奖励
    """
    # 分组信息
    if isLimitLevel(userId):
        return 7, None, None, None
    if not util.isFinishAllNewbieTask(userId):
        return 6, None, None, None
    honorId = int(taskId) / 100
    tasksConf = config.getAchievementTaskInfo(str(honorId))
    if not tasksConf or not tasksConf.get(str(taskId)):
        return 99, None, None, None

    curLevel = honor_system.getHonor(userId, honorId)[1]
    code = 0
    totalExp = 0
    level = 0
    # 当前的任务信息
    for level in xrange(1, int(taskId) % 100 + 1):
        taskId = honorId * 100 + level
        taskConf = tasksConf.get(str(taskId))
        if not tasksConf:
            continue
        # 为了兼容老玩家数据,需要从第一个任务开始检测.
        if level <= curLevel and taskConf[
                "type"] != AchieveType.CompleteMainQuestSection:
            continue
        taskClass = FishAchievementTask(userId, taskConf)
        # 领取奖励
        code, exp_ = taskClass.receiveTaskReward(taskConf["Id"])
        if code != 0:
            continue
        totalExp += exp_
    if code == 0:
        if honorId:
            # 发送增加称号事件
            # 称号升级.
            from newfish.entity.event import GetAchievementTaskRewardEvent
            from newfish.game import TGFish
            event = GetAchievementTaskRewardEvent(userId, FISH_GAMEID, taskId,
                                                  honorId, level)
            TGFish.getEventBus().publishEvent(event)
        if totalExp:  # 增加经验值
            levelClass = AchievementLevel(userId)
            levelClass.addAchievementExp(totalExp)

        # 更新小红点和进度
        updateAchievementModuleTips(userId, True)
    return code, honorId, level, totalExp
示例#6
0
def doGetAllMails(userId, mailSenderType):
    """
    发送收件箱邮件列表消息
    """
    if util.isFinishAllNewbieTask(userId):
        message = MsgPack()
        message.setCmd("fishMailList")
        message.setResult("gameId", FISH_GAMEID)
        message.setResult("userId", userId)
        message.setResult("mailTypeList", MAIL_SENDER_TYPE_LIST)
        message.setResult("mailType", mailSenderType)
        mails = getAllMail(userId).get(mailSenderType, [])
        message.setResult("mails", mails)
        router.sendToUser(message, userId)
示例#7
0
 def taskReady(self, *args):
     """
     任务准备
     """
     self.state = 1
     if self.sendInfoTimer:
         self.sendInfoTimer.cancel()
     tasks = config.getCmpttTaskConf(self.table.runConfig.fishPool)
     if len(tasks) == 0 or len(self.table.getBroadcastUids()) == 0:
         endTimer = FishTableTimer(self.table)
         endTimer.setup(0, "task_end", {"uid": 0, "task": self.taskName})
         return
     self.taskId = "%d-%d" % (self.table.tableId, int(time.time()))
     randTask = random.choice(tasks)
     self.currentTask = copy.deepcopy(randTask)
     for uid in self.table.getBroadcastUids():
         if util.isFinishAllNewbieTask(uid):
             self.userIds.append(uid)
     if len(self.userIds) <= 2:
         self.chestRewardId = self.currentTask["chestReward"][0]
     elif len(self.userIds) == 3:
         self.chestRewardId = self.currentTask["chestReward"][1]
     elif len(self.userIds) >= 4:
         self.chestRewardId = self.currentTask["chestReward"][2]
     for uid in self.userIds:
         self.usersData[uid] = {
             "uid": uid,
             "task": self.currentTask,
             "score": 0,
             "results": {},
             "lastCatchId": 0
         }
     readySeconds = self.currentTask["readySeconds"]
     msg = MsgPack()
     msg.setCmd("cmptt_task")
     msg.setResult("gameId", FISH_GAMEID)
     msg.setResult("action", "ready")
     msg.setResult("taskId", self.currentTask["taskId"])
     msg.setResult("taskType", self.currentTask["taskType"])
     msg.setResult("targets", self.currentTask["targets"])
     msg.setResult("reward", {"name": self.chestRewardId, "count": 1})
     GameMsg.sendMsg(msg, self.userIds)
     self.startTimer.setup(readySeconds, "task_start",
                           {"task": self.taskName})
示例#8
0
def doGetAllAchievementTasks(userId, honorId):
    """
    获取荣誉任务中一个称号的信息
    """
    message = MsgPack()
    message.setCmd("achievement_tasks")
    message.setResult("gameId", FISH_GAMEID)
    message.setResult("userId", userId)
    if isLimitLevel(userId):
        message.setResult("code", 7)
        router.sendToUser(message, userId)
        return
    if not util.isFinishAllNewbieTask(userId):
        message.setResult("code", 7)
        router.sendToUser(message, userId)
        return
    message.setResult("code", 0)
    tasks = getAllTaskInfo(userId, honorId)  # 勋章Id
    message.setResult("achievementTasks", tasks)  # 里面的成就任务
    message.setResult("honorId", honorId)
    router.sendToUser(message, userId)
示例#9
0
 def taskReady(self, tideId):
     """准备消息"""
     tideId = str(tideId)
     if tideId not in self.conf:
         return
     if len(self.table.getBroadcastUids()) == 0:
         return
     task = self.conf[tideId]
     if not task:
         return
     if self.state != TaskState.TS_End:
         return
     self.taskId = "%d-%d" % (self.table.tableId, int(time.time()))
     for uid in self.table.getBroadcastUids():
         if util.isFinishAllNewbieTask(uid):
             self.userIds.append(uid)
     self.state = TaskState.TS_TIP
     targets = task["targets"]
     for uid in self.userIds:
         self.usersData[uid] = {
             "uid": uid,
             "task": task,
             "targets": targets,
             "state": TaskState.TS_Ready,
             "rewardType": task["rewardType"],
             "results": {}
         }
     msg = MsgPack()
     msg.setCmd("tide_task")
     msg.setResult("gameId", FISH_GAMEID)
     msg.setResult("action", "ready")
     msg.setResult("taskId", task["taskId"])
     msg.setResult("taskType", task["taskType"])
     msg.setResult("targets", targets)
     msg.setResult("rewards", task["rewards"])
     GameMsg.sendMsg(msg, self.userIds)
     FTLoopTimer(
         int(task["tipSeconds"]) + int(task["readySeconds"]), 0,
         self.taskStart, tideId).start()  # 提示秒数 准备秒数4s 3、2、1、开始比赛
示例#10
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)
示例#11
0
def sendFishCheckinInfo(userId, continueWindow=0):
    """
    发送签到详情
    :param continueWindow: 0:用户点击签到请求 1:客户端登录时自动请求
    """
    _isCheckContinuousBreak(userId)

    checkinDay = _getCheckinDay(userId)
    isCheckin = _isCheckin(userId)
    code = 1
    if (continueWindow and isCheckin):
        code = 2
    elif util.isFinishAllNewbieTask(userId):
        code = 0
        if not isCheckin:
            module_tip.addModuleTipEvent(userId, "checkin", checkinDay)
    mo = MsgPack()
    mo.setCmd("fishCheckin")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    # 签到日
    day = checkinDay if isCheckin else checkinDay + 1
    mo.setResult("loginDays", day)
    mo.setResult("day", day)
    mo.setResult("checkin", isCheckin)
    msgRewardsDict = _getMsgRewardsDict(userId)
    for k, v in msgRewardsDict.iteritems():
        mo.setResult(k, v)
    mo.setResult("continueWindow", continueWindow)
    mo.setResult("code", code)
    enableItems = []
    for k, v in config.getCheckinConf("checkinData").iteritems():
        if v["unlockdays"] <= day:
            enableItems.append(k)
    mo.setResult("enableItems", enableItems)
    router.sendToUser(mo, userId)
    ftlog.debug("checkin, userId =", userId, checkinDay, mo)
示例#12
0
 def _chooseRoom(cls, userId, gameId, gameMode=config.MULTIPLE_MODE):
     """
     服务端为玩家选择房间
     """
     candidateRoomIds = cls._getCandidateRoomIds(gameId, "")
     newbieRoomId = config.getCommonValueByKey("newbieRoomId")
     if not util.isFinishAllNewbieTask(userId):
         return newbieRoomId, cls.ENTER_ROOM_REASON_OK
     uLevel = util.getUserLevel(userId)
     gunLevel = util.getGunLevel(userId, gameMode)
     userChip = userchip.getChip(userId)
     candidateRoomId = 0
     for roomId in sorted(candidateRoomIds, reverse=True):
         isOK = cls.matchEnterRoom(roomId, uLevel, gunLevel, userChip,
                                   gameMode)
         if isOK:
             candidateRoomId = roomId
             break
     if ftlog.is_debug():
         ftlog.debug("_chooseRoom", userId, gameId, gameMode,
                     candidateRoomId)
     if candidateRoomId > 0:
         return candidateRoomId, cls.ENTER_ROOM_REASON_OK
     return 0, cls.ENTER_ROOM_REASON_LESS_LEVEL
示例#13
0
def doSendGift(userId, clientId):
    """
    获取礼包数据
    """
    message = MsgPack()
    message.setCmd("fishDailyGift")
    message.setResult("gameId", FISH_GAMEID)
    message.setResult("userId", userId)
    vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0)
    dailyGiftConf = config.getDailyGiftConf(clientId)
    lang = util.getLanguage(userId, clientId)
    giftInfo = []
    if not util.isVersionLimit(userId) and not util.isPurchaseLimit(
            userId) and util.isFinishAllNewbieTask(userId):
        for id, giftConf in dailyGiftConf.iteritems():
            vipRange = giftConf.get("vipRange", [0, 0])
            if vipRange[0] <= vipLevel <= vipRange[1]:
                hasBought = _isBought(userId, id)
                continuousDay = _getContinuousDay(userId, id)
                if continuousDay < len(giftConf.get("giftInfo", [])):
                    hasBought = 0
                dayIdx = _getGiftDayIdx(clientId, id, continuousDay)
                giftInfo.append(
                    getGiftDetail(giftConf, hasBought, dayIdx, lang))
                if ftlog.is_debug():
                    ftlog.debug("doSendGift", userId, id, hasBought,
                                continuousDay, dayIdx)
    message.setResult("btnVisible", bool(len(giftInfo) > 0))
    message.setResult("giftInfo", giftInfo)
    giftTestMode = config.getPublic("giftTestMode", None)
    if giftTestMode is None:
        giftTestMode = "a" if userId % 2 == 0 else "b"
    message.setResult("testMode", giftTestMode)
    router.sendToUser(message, userId)
    if ftlog.is_debug():
        ftlog.debug("doSendGift===>", userId, giftInfo)
示例#14
0
    def canQuickEnterRoom(cls, userId, gameId, roomId, kindId):
        """
        判断能否进入房间
        """
        try:
            if util.isFinishAllNewbieTask(userId):
                newbieRoomId = config.getCommonValueByKey("newbieRoomId")
                if gdata.getBigRoomId(roomId) == gdata.getBigRoomId(
                        newbieRoomId):
                    return cls.ENTER_ROOM_REASON_INNER_ERROR
            else:
                newbieRoomId = config.getCommonValueByKey("newbieRoomId")
                if gdata.getBigRoomId(roomId) != gdata.getBigRoomId(
                        newbieRoomId):
                    return cls.ENTER_ROOM_REASON_INNER_ERROR
            gameMode = util.getRoomGameMode(roomId)
            isOldPlayerV2 = util.isOldPlayerV2(userId)
            if gameMode == config.CLASSIC_MODE and not isOldPlayerV2:
                return cls.ENTER_ROOM_REASON_INNER_ERROR
            uLevel = util.getUserLevel(userId)
            gunLevel = util.getGunLevel(userId, gameMode)
            if not uLevel or not gunLevel:
                return cls.ENTER_ROOM_REASON_INNER_ERROR
            gunLevelVal = config.getGunLevelConf(gunLevel, gameMode).get(
                "levelValue", 1)
            userChip = userchip.getUserChipAll(userId)
            vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
            if ftlog.is_debug():
                ftlog.debug("canQuickEnterRoom->",
                            gdata.roomIdDefineMap()[roomId].configure)
            roomConf = gdata.roomIdDefineMap()[roomId].configure
            fee = roomConf.get("fee_%s" % kindId, {}) or roomConf.get(
                "fee", {})
            minLevel = roomConf.get("minLevel", 1)
            minGunLevelVal = roomConf.get("minGunLevelVal", 1)
            minCoin = roomConf.get("minCoin", 1)
            minVip = roomConf.get("minVip", 0)
            timeLimit = roomConf.get("timeLimit", [])
            bulletLimit = roomConf.get("bulletLimit", {})
            protectionLimit = roomConf.get("protectionLimit", {})
            if fee:
                surplusCount = util.balanceItem(userId, fee["kindId"])
                if surplusCount < fee["count"]:
                    return cls.ENTER_ROOM_REASON_LESS_FEES
            if bulletLimit and not kindId:
                isCan = False
                for kindId in bulletLimit:
                    surplusCount = util.balanceItem(userId, kindId)
                    if surplusCount >= bulletLimit[kindId]:
                        isCan = True
                        break
                if not isCan:
                    return cls.ENTER_ROOM_REASON_LESS_BULLET
            if timeLimit:
                isCan = False
                currentTime = int(time.time())
                for timeRange in timeLimit:
                    startTime = util.getTodayTimestampFromStr(timeRange[0])
                    endTime = util.getTodayTimestampFromStr(timeRange[1])
                    if startTime <= currentTime <= endTime:
                        isCan = True
                        break
                if not isCan:
                    return cls.ENTER_ROOM_REASON_TIME_LIMIT
            if uLevel < minLevel and not kindId:
                if roomConf.get("typeName") == config.FISH_ROBBERY:
                    if vipLevel >= minVip:
                        return cls.ENTER_ROOM_REASON_OK
                return cls.ENTER_ROOM_REASON_LESS_LEVEL
            if gunLevelVal < minGunLevelVal:
                return cls.ENTER_ROOM_REASON_LESS_LEVEL
            if userChip < minCoin:
                return cls.ENTER_ROOM_REASON_LESS_COIN
            if protectionLimit:
                dailyProfitCoin, monthlyProfitCoin = 0, 0
                if roomConf.get("typeName") == config.FISH_ROBBERY:
                    dailyProfitCoin, monthlyProfitCoin = util.getRobberyProfitCoin(
                        userId)
                elif roomConf.get("typeName") == config.FISH_POSEIDON:
                    dailyProfitCoin, monthlyProfitCoin = util.getPoseidonProfitCoin(
                        userId)
                if (dailyProfitCoin <= protectionLimit["dailyLoss"] or
                        monthlyProfitCoin <= protectionLimit["monthlyLoss"]):
                    return cls.ENTER_ROOM_REASON_EXCESSIVE_LOSS
            # 检测大奖赛开放时间
            if roomConf.get("typeName") in [config.FISH_GRAND_PRIX]:
                state = cls.grandPrixEnterRoom(userId)
                if state != cls.ENTER_ROOM_REASON_OK:
                    return state
            return cls.ENTER_ROOM_REASON_OK

        except Exception as e:
            ftlog.error("canQuickEnterRoom error", userId, e)
            return cls.ENTER_ROOM_REASON_INNER_ERROR
示例#15
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)
示例#16
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)
示例#17
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