def refreshTreasureState(userId, kindId): """ 刷新宝藏状态等数据 """ treasureData = getTreasure(userId, kindId) lastTimestamp = treasureData[INDEX_FINISH_TIME] if util.getDayStartTimestamp(int(time.time())) != util.getDayStartTimestamp(lastTimestamp): treasureData[INDEX_FINISH_COUNT] = 0 setTreasure(userId, kindId, treasureData)
def refreshInviteData(userId): """ 刷新邀请数据 """ inviteList = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.inviteList, []) for _, inviteData in enumerate(inviteList[:]): if inviteData.get("receiveTime"): if util.getDayStartTimestamp(inviteData["receiveTime"]) != util.getDayStartTimestamp(int(time.time())): inviteList.remove(inviteData) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.inviteList, json.dumps(inviteList)) return inviteList
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)
def _checkContinuosPurchase(userId, giftId): """检查持续购买""" giftId = str(giftId) purchaseData = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.continuousPurchase, {}) data = purchaseData.get(giftId, [0, 0]) if util.getDayStartTimestamp( data[0]) + 24 * 60 * 60 + 60 < util.getDayStartTimestamp( int(time.time())): data[0] = int(time.time()) data[1] = 0 gamedata.setGameAttr(userId, FISH_GAMEID, GameData.continuousPurchase, json.dumps(purchaseData))
def refreshReturnerMissionData(userId, lastLoginTime): """ 刷新回归豪礼数据 """ currTime = int(time.time()) lastLoginTime = util.getDayStartTimestamp(lastLoginTime) returnerMissionConf = config.getReturnerMissionConf() # 判断是否激活回归豪礼 if currTime - lastLoginTime >= returnerMissionConf["daysLost"] * 24 * 3600: returnerMission = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.returnerMission, {}) lastActiveTime = util.getDayStartTimestamp(returnerMission.get("lastActiveTime", currTime)) isActive = False if returnerMission: if currTime - lastActiveTime >= returnerMissionConf["daysBetween"] * 24 * 3600: isActive = True else: isActive = True if isActive: userLevel = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.level) vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level vipExp = hallvip.userVipSystem.getUserVip(userId).vipExp returnerMission = {} returnerMission["lastActiveTime"] = currTime returnerMission["userLevel"] = userLevel returnerMission["vipExp"] = vipExp returnerMission["tasks"] = initTaskData() gamedata.setGameAttr(userId, FISH_GAMEID, GameData.returnerMission, json.dumps(returnerMission)) bireport.reportGameEvent("BI_NFISH_GE_RETURNER_MISSION", userId, FISH_GAMEID, vipLevel, vipExp, userLevel, 0, 0, 0, [], util.getClientId(userId)) returnerMission = getReturnerMissionData(userId) if returnerMission: # 解锁新任务 lastActiveTime = util.getDayStartTimestamp(returnerMission["lastActiveTime"]) fewDays = (datetime.fromtimestamp(currTime) - datetime.fromtimestamp(lastActiveTime)).days + 1 fewDays = max(1, min(fewDays, len(returnerMission["tasks"]))) # 第N天之前的任务都会解锁 isUnlock = False taskIds = [] for _index, taskConf in enumerate(config.getReturnerMissionConf("tasks")): if taskConf["taskId"] in returnerMission["tasks"]: if _index < fewDays and returnerMission["tasks"][taskConf["taskId"]]["state"] == 0: returnerMission["tasks"][taskConf["taskId"]]["state"] = 1 isUnlock = True elif returnerMission["tasks"][taskConf["taskId"]]["state"] == 2: taskIds.append(taskConf["taskId"]) if isUnlock: gamedata.setGameAttr(userId, FISH_GAMEID, GameData.returnerMission, json.dumps(returnerMission)) if taskIds: module_tip.addModuleTipEvent(userId, "returnerMission", taskIds) else: module_tip.resetModuleTipEvent(userId, "returnerMission")
def _triggerEnterTableEvent(self, event): tableId = event.tableId userId = event.userId if tableId in self._allTableDict: self._allPlayerDict[userId] = tableId self._allTableSeatDict[tableId].add(userId) if ftlog.is_debug(): ftlog.debug("_triggerEnterTableEvent", self._allPlayerDict) import time from poker.util import strutil from newfish.entity.task.task_system_user import RedState from newfish.entity.config import FISH_GAMEID from newfish.entity.redis_keys import GameData newbie7DayGiftData = gamedata.getGameAttrJson( userId, FISH_GAMEID, GameData.newbie7DayGiftData) # 新手7日礼包数据 if isinstance(newbie7DayGiftData, list) and len(newbie7DayGiftData) == 2: return redState = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.redState) # 新手任务状态 if redState < RedState.Complete: gamedata.setGameAttr( userId, FISH_GAMEID, GameData.newbie7DayGiftData, strutil.dumps( [util.getDayStartTimestamp(int(time.time())), []]))
def getReturnerMission(userId, clientId): """ 获取回归豪礼 """ timeLeft = 0 currTime = int(time.time()) returnerMission = getReturnerMissionData(userId) returnerMissionConf = config.getReturnerMissionConf() if returnerMission: # 获取回归豪礼结束倒计时 expireDays = returnerMissionConf["expireDays"] * 24 * 3600 endTime = returnerMission["lastActiveTime"] + expireDays timeLeft = max(endTime - currTime, 0) mo = MsgPack() mo.setCmd("returner_mission") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("timeLeft", timeLeft) if timeLeft > 0: # 是否首次登录弹出 dayFirst = weakdata.incrDayFishData(userId, WeakData.returnerMission, 1) # 当前是激活后的第几个任务(按天处理) lastActiveTime = util.getDayStartTimestamp(returnerMission["lastActiveTime"]) fewDays = (datetime.fromtimestamp(currTime) - datetime.fromtimestamp(lastActiveTime)).days + 1 fewDays = max(1, min(fewDays, len(returnerMission["tasks"]))) currentTaskId = returnerMissionConf["tasks"][fewDays - 1]["taskId"] lang = util.getLanguage(userId, clientId) # 任务数据 tasks = buildTaskData(returnerMission, lang) mo.setResult("dayFirst", 1 if dayFirst == 1 else 0) mo.setResult("currentTaskId", currentTaskId) mo.setResult("rule", config.getMultiLangTextConf(returnerMissionConf["rule"], lang=lang)) mo.setResult("tasks", tasks) router.sendToUser(mo, userId)
def setNewbie7Day(userId): """ 设置新手八日礼包数据 """ ts = int(time.time()) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.newbie7DayGiftData, strutil.dumps([util.getDayStartTimestamp(ts), []]))
def updateLoginData(userId): """ 更新用户登录数据 """ curTime = int(time.time()) lastLoginTime = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.lastloginTime) or curTime returner_mission.refreshReturnerMissionData(userId, lastLoginTime) # 刷新回归豪礼数据 lastLoginTime = util.getDayStartTimestamp(lastLoginTime) todayStartTime = util.getDayStartTimestamp(curTime) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.lastloginTime, curTime) # 过天 if todayStartTime - lastLoginTime > 24 * 3600: gamedata.incrGameAttr(userId, FISH_GAMEID, GameData.loginDays, 1) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.continuousLogin, 1) elif todayStartTime - lastLoginTime == 24 * 3600: # 正好一天 gamedata.incrGameAttr(userId, FISH_GAMEID, GameData.loginDays, 1) gamedata.incrGameAttr(userId, FISH_GAMEID, GameData.continuousLogin, 1)
def isGrandPrixOpenTime(): """ 是否为大奖赛开放时段 00:00 -- 23:00 """ curTime = int(time.time()) dayStartTS = util.getDayStartTimestamp(curTime) openTimeRange = config.getGrandPrixConf("openTimeRange") return util.timeStrToInt( openTimeRange[0]) < (curTime - dayStartTS) < util.timeStrToInt( openTimeRange[1])
def _isCheckin(userId, ts=None): """ 判断今日是否已签到 """ ts = ts or int(time.time()) # 当日签到后时间戳会设置为第二天的0点 continuousCheckinDayTS = gamedata.getGameAttrInt( userId, FISH_GAMEID, GameData.continuousCheckinDayTS) isCheckin = 1 if continuousCheckinDayTS == util.getDayStartTimestamp( ts) + 86400 else 0 return isCheckin
def queryNewbie7DayGift(userId, clientId): """ 返回新手礼包数据 """ module_tip.resetModuleTipEvent(userId, "newbie7DaysGift") message = MsgPack() message.setCmd("newbie_7_gift_query") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) message.setResult("clientId", clientId) redState = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.redState) message.setResult("redState", redState) giftState = checkNewbie7DaysGiftState(userId, redState) rewardsList = [] curDayIdx = 0 newbie7DayGiftData = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.newbie7DayGiftData) if giftState == 1 and isinstance(newbie7DayGiftData, list) and len(newbie7DayGiftData) == 2: startTS, takenDays = newbie7DayGiftData curTime = int(time.time()) curDayStartTS = util.getDayStartTimestamp(curTime) curDayIdx = (curDayStartTS - startTS) / 86400 daysConf = config.getNewbie7DaysGiftConf() # 最后一天已领取或是已过期 if daysConf[-1].get( "idx") in takenDays or curDayIdx > daysConf[-1].get("idx"): giftState = 2 curDayIdx = 0 else: for _val in daysConf: _idx = _val.get("idx") _state = 1 if _idx in takenDays else 0 _rewards = _processRewards(_val.get("rewards")) rewardsList.append({ "rewards": _rewards, "idx": _idx, "state": _state }) if _state == 0 and _idx == curDayIdx: module_tip.addModuleTipEvent(userId, "newbie7DaysGift", curDayIdx) message.setResult("nextRefreshTime", 86400 - (curTime - curDayStartTS)) message.setResult("giftState", giftState) message.setResult("rewardsList", rewardsList) message.setResult("curDayIdx", curDayIdx) ignoreClient = config.isClientIgnoredConf("clientIds", clientId, clientId) message.setResult("isPureClient", 1 if ignoreClient else 0) router.sendToUser(message, userId) if ftlog.is_debug(): ftlog.debug("newbie7DaysGift, userId =", userId, newbie7DayGiftData, "message =", message)
def _getDataKey(ts, resetTime): """ 获取数据存储key值 """ curDayStartTS = util.getDayStartTimestamp(ts) if resetTime == -1: return str(curDayStartTS) resetTS = curDayStartTS + resetTime * 3600 if ts < resetTS: _key = str(resetTS - 86400) else: _key = str(resetTS) return _key
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)
def removeExpiredData(bigRoomId): """ 去除过期的存档数据 """ curDayStartTS = util.getDayStartTimestamp(int(time.time())) # subKey = (MixData.superbossBonuspool % bigRoomId) datas = daobase.executeMixCmd("HGETALL", _getSuperbossKey()) delKeys = [] for key in datas[0::2]: val = key.split('_') if len(val) == 2 and int(val[0]) < curDayStartTS - 2 * 86400 and ( val[1] == (MixData.superbossBonuspool % bigRoomId) or val[1] == (MixData.superbossBonuspool % bigRoomId)): delKeys.append(key) for key in delKeys: daobase.executeMixCmd("HDEL", _getSuperbossKey(), key)
def incrCompBonusPool(bigRoomId, mode, pool, ts=None): """ 增加超级boss奖池 """ return 0 ts = ts or int(time.time()) dayStartTS = util.getDayStartTimestamp(ts) subKey = "%d_%s" % (dayStartTS, (MixData.superbossBonuspool % bigRoomId)) if mode == 1: subKey = "%d_%s" % (dayStartTS, (MixData.superbossBonusRingpool % bigRoomId)) if pool: bonusPool = daobase.executeMixCmd("HINCRBY", _getSuperbossKey(), subKey, pool) else: bonusPool = daobase.executeMixCmd("HGET", _getSuperbossKey(), subKey) if ftlog.is_debug(): ftlog.debug("gameplay, bonusPool =", bonusPool, "key =", subKey) return bonusPool
def checkNewbie7DaysGiftState(userId, redState): """ 检测新手7日礼包状态,0:未开启,1:已开启,2:已结束 """ newbie7DayGiftData = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.newbie7DayGiftData) if isinstance(newbie7DayGiftData, list) and len(newbie7DayGiftData) == 2: startTS, takenDays = newbie7DayGiftData curDayStartTS = util.getDayStartTimestamp(int(time.time())) curDayIdx = (curDayStartTS - startTS) / 86400 daysConf = config.getNewbie7DaysGiftConf() # 最后一天已领取或是已过期 if daysConf[-1].get( "idx") in takenDays or curDayIdx > daysConf[-1].get("idx"): giftState = 2 else: giftState = 1 else: from newfish.entity.task.task_system_user import RedState giftState = 2 if redState >= RedState.Complete else 0 return giftState
def setTipTimer(self): """ 设置比赛开始和结束的通知消息 """ if self.grandPrixTipTimer: self.grandPrixTipTimer.cancel() self.grandPrixTipTimer = None self.sendGrandPrixInfo() # 发送大奖赛信息 curTime = int(time.time()) dayStartTS = util.getDayStartTimestamp(curTime) openTimeRange = config.getGrandPrixConf("openTimeRange") pastTime = curTime - dayStartTS # 03:00|23:10 beginTime = util.timeStrToInt(openTimeRange[0]) # 00:00 endTime = util.timeStrToInt(openTimeRange[1]) # 23:00 if pastTime < beginTime: interval = beginTime - pastTime + 5 # 开始的通知 elif beginTime <= pastTime <= endTime: interval = endTime - pastTime + 5 # 结束的通知 else: interval = 86400 + beginTime - pastTime + 5 # 开始的通知 self.grandPrixTipTimer = FTLoopTimer(interval, 0, self.setTipTimer) # 死循环 self.grandPrixTipTimer.start()
def getSuperbossBonusPool(bigRoomId, mode, ts=None): """ 获取超级boss奖池 """ return 0 if not bigRoomId: ftlog.error("gameplay, bigRoomId error !", bigRoomId, ts) return 0 ts = ts or int(time.time()) dayStartTS = util.getDayStartTimestamp(ts) subKey = "%d_%s" % (dayStartTS, MixData.superbossBonuspool % bigRoomId) if mode == 1: subKey = "%d_%s" % (dayStartTS, (MixData.superbossBonusRingpool % bigRoomId)) # 获取指定时间的奖池 bonusPool = daobase.executeMixCmd("HGET", _getSuperbossKey(), subKey) # 当奖池为空时(首次开启奖池)添加初始奖池,后续每天的初始奖池从前一天的房间奖池中划分一部分. if bonusPool is None: bonusPool = 100000 daobase.executeMixCmd("HSET", _getSuperbossKey(), subKey, bonusPool) if ftlog.is_debug(): ftlog.debug("gameplay, bonusPool =", bonusPool, "key =", subKey) return bonusPool
def _isCheckContinuousBreak(userId, ts=None): """ 检查是否需要中断连续签到 """ ts = ts or int(time.time()) dayStartTS = util.getDayStartTimestamp(int(ts)) gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.breakContinuousCheckinTS, dayStartTS) gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.continuousCheckinDayTS, dayStartTS) # 未连续签到时要中断. continuousCheckinDayTS = gamedata.getGameAttrInt( userId, FISH_GAMEID, GameData.continuousCheckinDayTS) if continuousCheckinDayTS + 86400 <= dayStartTS: breakContinuousCheckinTS = dayStartTS continuousCheckinDayTS = dayStartTS gamedata.setGameAttrs(userId, FISH_GAMEID, [ GameData.breakContinuousCheckinTS, GameData.continuousCheckinDayTS ], [breakContinuousCheckinTS, continuousCheckinDayTS]) # vip小于配置时,每周按照配置日期中断连续签到数据. st = time.localtime(dayStartTS) vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) conf = config.getCheckinConf("resetInfo") resetVip = conf.get("vip", 0) resetWeekDay = conf.get("resetWeekDay", 0) if vipLevel <= resetVip and st.tm_wday == resetWeekDay: breakContinuousCheckinTS = gamedata.getGameAttrInt( userId, FISH_GAMEID, GameData.breakContinuousCheckinTS) if breakContinuousCheckinTS < dayStartTS: breakContinuousCheckinTS = dayStartTS continuousCheckinDayTS = dayStartTS gamedata.setGameAttrs(userId, FISH_GAMEID, [ GameData.breakContinuousCheckinTS, GameData.continuousCheckinDayTS ], [breakContinuousCheckinTS, continuousCheckinDayTS]) ftlog.debug("checkin, reset, userId =", userId, "resetTS =", dayStartTS)
def grandPrixEnterRoom(cls, userId): """ 大奖赛房间能否进入 """ startDay = config.getGrandPrixConf("info").get("startDay") currentTime = int(time.time()) if startDay and currentTime < util.getTimestampFromStr(startDay): return cls.ENTER_ROOM_REASON_NOT_OPEN if weakdata.getDayFishData(userId, WeakData.grandPrix_startTS, 0) == 0: dayStartTimestamp = util.getDayStartTimestamp(currentTime) remainGrandPrixTimeSeconds = util.timeStrToInt( config.getGrandPrixConf("openTimeRange")[1]) - ( currentTime - dayStartTimestamp) # 大奖赛剩余时间 if not grand_prix.isGrandPrixOpenTime( ) or remainGrandPrixTimeSeconds < 10: return cls.ENTER_ROOM_REASON_GRAND_PRIX_NOE_OPEN vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level if config.getVipConf(vipLevel).get("grandPrixFreeTimes", 0) <= \ weakdata.getDayFishData(userId, WeakData.grandPrix_freeTimes, 0): # 用免费次数已经用完 fee = config.getGrandPrixConf("fee")[0] surplusCount = util.balanceItem(userId, fee["name"]) if surplusCount < fee["count"]: return cls.ENTER_ROOM_REASON_GRAND_PRIX_LESS_FEES return cls.ENTER_ROOM_REASON_OK
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)
def addRobotToGrandPrix(): """ 机器人进入大奖赛排行榜 "robot": [1, 30, [2, 2]] """ global _addRobotToGrandPrixRankTimestamp curTime = int(time.time()) startDay = config.getGrandPrixConf("info").get("startDay") if startDay and curTime < util.getTimestampFromStr(startDay): return if curTime < _addRobotToGrandPrixRankTimestamp: return robotConf = config.getGrandPrixConf("info").get("robot", []) if len(robotConf) < 3 or len(robotConf[2]) < 2: _addRobotToGrandPrixRankTimestamp = curTime + 10 * 60 # 10分钟 return # 不启用机器人 if robotConf[0] == 0: _addRobotToGrandPrixRankTimestamp = curTime + 10 * 60 return startInterval = robotConf[1] * 60 dayStartTS = util.getDayStartTimestamp(curTime) openTimeRange = config.getGrandPrixConf("openTimeRange") if util.timeStrToInt(openTimeRange[0]) + startInterval >= ( curTime - dayStartTS) or ( curTime - dayStartTS) >= util.timeStrToInt(openTimeRange[1]): _addRobotToGrandPrixRankTimestamp = curTime return nextAddInterval = random.randint(robotConf[2][0] * 60, robotConf[2][1] * 60) _addRobotToGrandPrixRankTimestamp = curTime + nextAddInterval rdKey = redis_keys.MixData.grandPrixRobotData % config.FISH_GAMEID robotDatas = config.getGrandPrixConf("robotData") maxCount = sum([val["count"] for val in robotDatas ]) # {"count": 1, "points": [58001, 60000]}, dayStartTS = util.getDayStartTimestamp(int(time.time())) robotDatas = daobase.executeMixCmd("HGET", rdKey, str(dayStartTS)) if robotDatas: robotDatas = json.loads(robotDatas) else: robotDatas = {} robotDatas.setdefault("uids", []) robotDatas.setdefault("ranks", []) uidList = robotDatas.get("uids") rankList = robotDatas.get("ranks") if len(uidList) >= maxCount: _addRobotToGrandPrixRankTimestamp = curTime + 10 * 60 return datas = daobase.executeMixCmd("HGETALL", rdKey) if datas: for ts in datas[0::2]: if int(ts) < dayStartTS: daobase.executeMixCmd("HDEL", rdKey, ts) startRobotUid = 0 ruid = random.randint(startRobotUid + 1, startRobotUid + maxCount) while ruid in uidList: ruid = random.randint(startRobotUid + 1, startRobotUid + maxCount) rrank = random.randint(1, maxCount) while rrank in rankList: rrank = random.randint(1, maxCount) uidList.append(ruid) rankList.append(rrank) daobase.executeMixCmd("HSET", rdKey, str(dayStartTS), json.dumps(robotDatas)) robotDatas = config.getGrandPrixConf("robotData") for val in robotDatas: if rrank > val["count"]: rrank -= val["count"] else: fishPoint = random.randint(val["points"][0], val["points"][1]) if userdata.checkUserData(ruid): refreshGrandPrixPoint(ruid, fishPoint) # else: # ftlog.error("addRobotToGrandPrix, error", "uid =", ruid) # if ftlog.is_debug(): # ftlog.debug("addRobotToGrandPrix", "uid =", ruid, "rank =", rrank, "point =", fishPoint, maxCount) break
def refreshDailyQuestGroupLv(userId): """ 刷新每日任务难度等级 """ gunLevel_m = util.getGunLevelVal(userId, config.MULTIPLE_MODE) curDayStartTs = util.getDayStartTimestamp(int(time.time())) initLv = getInitQuestLv(userId) dailyQuestConf = config.getDailyQuestConf() key = _getUserDailyQuestGroupLvKey(userId) groupLvData = gamedata.getGameAttrJson(userId, FISH_GAMEID, key, {}) questInfo = getUserQuestInfoData(userId) for taskId, state in questInfo.iteritems(): state = state[-1] if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, taskId, state, dailyQuestConf.get(str(taskId), {})) groupId = dailyQuestConf.get(str(taskId), {}).get("groupId", 0) if groupId: groupId = str(groupId) if groupId in groupLvData.keys(): # 玩家没有连续登陆, 清零难度经验进度 ts = 0 if len(groupLvData[groupId]) > 2: ts = groupLvData[groupId][2] dayStartTs = util.getDayStartTimestamp(ts) if dayStartTs + 86400 < curDayStartTs: groupLvData[groupId][1] = 0 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "reset exp !") else: if state >= QuestTaskState.Complete: # 完成任务增加难度经验 if groupLvData[groupId][1] < 2: groupLvData[groupId][1] += 1 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "increase exp !") else: # 未完成任务, 且前一天游戏时长超过20分钟则削减难度经验 _key = GameData.playGameTime % (FISH_GAMEID, userId, dayStartTs) playGameTime = daobase.executeUserCmd(userId, "GET", _key) or 0 if playGameTime >= 20: # 降级变更为1天不完成并且游戏时长大于20分钟就降级,即满足要求+1,不满足-2 if groupLvData[groupId][1] > -2 and groupLvData[groupId][0] > 1: groupLvData[groupId][1] -= 2 # 1 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "decrease exp !") # if groupLvData[groupId][1] >= 2: # groupLvData[groupId][0] += 1 # groupLvData[groupId][1] = 0 # ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "increase lv !") if groupLvData[groupId][1] <= -2 and groupLvData[groupId][0] > 1: groupLvData[groupId][0] -= 1 groupLvData[groupId][1] = 0 if ftlog.is_debug(): ftlog.debug("daily_quest, userId =", userId, "groupId =", groupId, "decrease lv !") groupLvData[groupId][2] = curDayStartTs else: _, lv = getQuestTaskId(groupId, initLv, gunLevel_m, userId) groupLvData[groupId] = [lv, 0, curDayStartTs] # groupLvData[groupId][0] = min(10, max(1, groupLvData[groupId][0])) if len(groupLvData) == 0: groupIdList = config.getDailyQuestGroupOrder() for groupId in groupIdList: _, lv = getQuestTaskId(groupId, initLv, gunLevel_m, userId) groupLvData[groupId] = [lv, 0, curDayStartTs] else: for k in groupLvData.keys(): groupLvData[k][2] = curDayStartTs gamedata.setGameAttr(userId, FISH_GAMEID, key, json.dumps(groupLvData)) if ftlog.is_debug(): ftlog.debug("daily_quest, user ="******"groupLvData =", groupLvData)
def _initSaveLoad(userId, clientId): """ 初始化存档 """ _ts = int(time.time()) / 60 * 60 vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) piggyBankconf = config.getPiggyBankConf(clientId, vipLevel) key = UserData.piggyBankData % (FISH_GAMEID, userId) if not daobase.executeUserCmd(userId, "EXISTS", key): curDayStartTS = util.getDayStartTimestamp(_ts) freeData = { GameData.pb_enable: 1, GameData.pb_saveMoneyTS: _ts, GameData.pb_moneyCount: piggyBankconf.get("free", {}).get("initVal", 0), GameData.pb_getMoneyTS: 0., GameData.pb_savedMoneyCount: { str(curDayStartTS): 0. } } paidData = { GameData.pb_enable: 0, GameData.pb_saveMoneyTS: _ts, GameData.pb_moneyCount: piggyBankconf.get("paid", {}).get("initVal", 0), GameData.pb_getMoneyTS: 0., GameData.pb_savedMoneyCount: { str(curDayStartTS): 0. } } daobase.executeUserCmd(userId, "HSET", key, "free", json.dumps(freeData)) daobase.executeUserCmd(userId, "HSET", key, "paid", json.dumps(paidData)) if True: freeData = daobase.executeUserCmd(userId, "HGET", key, "free") freeData = json.loads(freeData or "{}") resetTime = _getResetTime( piggyBankconf.get("free", {}).get("resetTime", -1)) if resetTime != -1: resetKey = _getDataKey(_ts, resetTime) freeData.setdefault(GameData.pb_moneyCountDict, {}) freeData[GameData.pb_moneyCountDict].setdefault( resetKey, piggyBankconf.get("free", {}).get("initVal", 0)) freeData[GameData.pb_moneyCount] = freeData[ GameData.pb_moneyCountDict][resetKey] daobase.executeUserCmd(userId, "HSET", key, "free", json.dumps(freeData)) ftlog.debug("piggy_bank, userId =", userId, "free", freeData) else: # 之前是重置的存钱罐,使用最近一次的存档存档. ts_keys = freeData.get(GameData.pb_moneyCountDict, {}).keys() if isinstance(ts_keys, list) and len(ts_keys) > 0: ts_keys = [int(_t) for _t in ts_keys] ts_keys.sort() freeData[GameData.pb_moneyCount] = freeData[ GameData.pb_moneyCountDict][str(ts_keys[-1])] del freeData[GameData.pb_moneyCountDict] daobase.executeUserCmd(userId, "HSET", key, "free", json.dumps(freeData)) ftlog.debug("piggy_bank, use old saveload, userId =", userId, "free =", freeData) paidData = daobase.executeUserCmd(userId, "HGET", key, "paid") paidData = json.loads(paidData or "{}") resetTime = _getResetTime( piggyBankconf.get("paid", {}).get("resetTime", -1)) if resetTime != -1: resetKey = _getDataKey(_ts, resetTime) paidData.setdefault(GameData.pb_moneyCountDict, {}) paidData[GameData.pb_moneyCountDict].setdefault( resetKey, piggyBankconf.get("paid", {}).get("initVal", 0)) paidData[GameData.pb_moneyCount] = paidData[ GameData.pb_moneyCountDict][resetKey] daobase.executeUserCmd(userId, "HSET", key, "paid", json.dumps(paidData)) ftlog.debug("piggy_bank, userId =", userId, "paid", paidData) else: # 之前是重置的存钱罐,使用最近一次的存档存档. ts_keys = paidData.get(GameData.pb_moneyCountDict, {}).keys() if isinstance(ts_keys, list) and len(ts_keys) > 0: ts_keys = [int(_t) for _t in ts_keys] ts_keys.sort() paidData[GameData.pb_moneyCount] = paidData[ GameData.pb_moneyCountDict][str(ts_keys[-1])] del paidData[GameData.pb_moneyCountDict] daobase.executeUserCmd(userId, "HSET", key, "paid", json.dumps(paidData)) ftlog.debug("piggy_bank, use old saveload, userId =", userId, "paid =", paidData)
def saveMoneyToPiggyBank(userId, clientId): """ 向存钱罐存钱 """ vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) conf = config.getPiggyBankConf(clientId, vipLevel) key = UserData.piggyBankData % (FISH_GAMEID, userId) ts = int(time.time()) / 60 * 60 curDayStartTS = util.getDayStartTimestamp(ts) # 初始化存档. _initSaveLoad(userId, clientId) for k, v in conf.iteritems(): piggyBankData = daobase.executeUserCmd(userId, "HGET", key, k) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} # ftlog.debug("piggy_bank, userId =", userId, piggyBankData) lastTS = piggyBankData.get(GameData.pb_saveMoneyTS, 0) if lastTS == 0: continue endcoolingTs = piggyBankData.get(GameData.pb_endcoolingTS, 0) unitCount = v.get("outroom", 0) resetTime = _getResetTime(v.get("resetTime", -1)) # 处理跨天逻辑. while lastTS < curDayStartTS: if resetTime != -1: resetTS = util.getDayStartTimestamp(lastTS) + resetTime * 3600 if lastTS < endcoolingTs < resetTS: lastTS = endcoolingTs elif resetTS < endcoolingTs: lastTS = resetTS if lastTS < resetTS: interval = (resetTS - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(resetTS)) addMoneyToPiggyBank(userId, clientId, k, addCount, resetTS - 1) lastTS = resetTS nextStartDayTS = util.getDayStartTimestamp(lastTS) + 86400 if lastTS < endcoolingTs < nextStartDayTS: lastTS = endcoolingTs elif nextStartDayTS < endcoolingTs: lastTS = nextStartDayTS interval = (nextStartDayTS - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(nextStartDayTS)) addMoneyToPiggyBank(userId, clientId, k, addCount, nextStartDayTS - 1) lastTS = nextStartDayTS if resetTime != -1: resetTS = util.getDayStartTimestamp(lastTS) + resetTime * 3600 if lastTS < resetTS < ts: if lastTS < endcoolingTs < resetTS: lastTS = endcoolingTs elif resetTS < endcoolingTs: lastTS = resetTS interval = (resetTS - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(resetTS)) addMoneyToPiggyBank(userId, clientId, k, addCount, resetTS - 1) lastTS = resetTS if lastTS < endcoolingTs < ts: lastTS = endcoolingTs elif ts < endcoolingTs: lastTS = ts interval = (ts - lastTS) / 60 addCount = interval * unitCount if interval > 0: ftlog.debug("piggy_bank, userId =", userId, "type =", k, "interval =", interval, "vip =", vipLevel, "addCount =", addCount, piggyBankData, util.timestampToStr(lastTS), util.timestampToStr(ts)) addMoneyToPiggyBank(userId, clientId, k, addCount, ts) # 清理过期的每日积累上线key for k, v in conf.iteritems(): piggyBankData = daobase.executeUserCmd(userId, "HGET", key, k) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} isChanged = False resetTime = _getResetTime(v.get("resetTime", -1)) _resetTS = int(_getDataKey(int(time.time()), resetTime)) ts_keys = piggyBankData[GameData.pb_savedMoneyCount].keys() for ts in ts_keys: if int(ts) < _resetTS: ftlog.debug( "piggy_bank, delete pb_savedMoneyCount expired ts key, userId =", userId, "type =", k, "ts =", util.timestampToStr(int(ts)), "val =", piggyBankData[GameData.pb_savedMoneyCount][ts]) del piggyBankData[GameData.pb_savedMoneyCount][ts] isChanged = True if resetTime != -1: ts_keys = piggyBankData.get(GameData.pb_moneyCountDict, {}).keys() for ts in ts_keys: if int(ts) < _resetTS: ftlog.debug( "piggy_bank, delete pb_moneyCountDict expired ts key, userId =", userId, "type =", k, "ts =", util.timestampToStr(int(ts)), "val =", piggyBankData[GameData.pb_moneyCountDict][ts]) del piggyBankData[GameData.pb_moneyCountDict][ts] isChanged = True if isChanged: # ftlog.debug("piggy_bank, piggyBankData changed, userId =", userId, piggyBankData) daobase.executeUserCmd(userId, "HSET", key, k, json.dumps(piggyBankData))
def startGrandPrix(self): """ 大奖赛开始 grandPrixStartTS=0 报名大奖赛/ grandPrixStartTS > 0 直接进入渔场 """ curTime = int(time.time()) dayStartTimestamp = util.getDayStartTimestamp(curTime) remainGrandPrixTimeSeconds = util.timeStrToInt( config.getGrandPrixConf("openTimeRange")[1]) - ( curTime - dayStartTimestamp) # 大奖赛剩余时间 # 当局进入大奖赛 if self.grandPrixStartTS == 0: event = JoinGrandPrixEvent(self.userId, FISH_GAMEID, self.table.bigRoomId) # 参加大奖赛事件 TGFish.getEventBus().publishEvent(event) # 距离大奖赛结束不足10秒不可参赛 if not grand_prix.isGrandPrixOpenTime( ) or remainGrandPrixTimeSeconds < 10: code = SignupCode.SC_NOT_OPEN elif config.getVipConf(self.vipLevel).get( "grandPrixFreeTimes", 0) > self._freeTimes: # 用免费次数报名 self._freeTimes = weakdata.incrDayFishData( self.userId, WeakData.grandPrix_freeTimes, 1) code = SignupCode.SC_SUCC else: # 扣除报名费 fee = config.getGrandPrixConf("fee")[0] _consume = [{ "name": fee.get("name"), "count": fee.get("count") }] _ret = util.consumeItems(self.userId, _consume, "ITEM_USE", self.table.roomId) if _ret: code = SignupCode.SC_SUCC else: code = SignupCode.SC_FEE_NOT_ENOUGH if code == SignupCode.SC_SUCC: # 选择目标鱼 for _val in config.getGrandPrixConf( "group").values(): # 1、2、3个组 idx = random.randint(0, len(_val) - 1) # 一组鱼 _cnt = config.getGrandPrixConf("target").get( str(_val[idx]), {}).get("count", 999) # 某一种鱼 捕获数量 _point = config.getGrandPrixConf("target").get( str(_val[idx]), {}).get("point", 0) # 某一种鱼 获得的积分 self.grandPrixTargetFish[str( _val[idx])] = [0, _cnt, _point] # 备份技能数据. self.grandPrixUseSkillTimes = [] for i in range(skill_system.MAX_INSTALL_NUM - 1): self.grandPrixUseSkillTimes.append({ "skillId": 0, "state": 0, "star": 0, "grade": 0, "count": config.getGrandPrixConf("fireCount")[1], # 技能使用次数3 "skillType": 0 if i < skill_system.MAX_INSTALL_NUM else 1 # 0主技能 1辅助技能 }) for idx, _skillId in enumerate(self.skillSlots): _skill = self.getSkill(_skillId, 0) self.grandPrixUseSkillTimes[idx]["skillId"] = _skillId self.grandPrixUseSkillTimes[idx][ "state"] = _skill.skillState self.grandPrixUseSkillTimes[idx]["star"] = _skill.skillStar self.grandPrixUseSkillTimes[idx][ "grade"] = _skill.skillGrade if self.inGameTimes: bireport.reportGameEvent("BI_NFISH_GRAND_PRIX_INGAMETIMES", self.userId, FISH_GAMEID, 0, 0, self.grandPrixStartTS, self.inGameTimes, 0, 0, [], util.getClientId(self.userId)) self.inGameTimes = 0 self.grandPrixFishPoint = 0 self.grandPrixSurpassCount = 0 self.grandPrixStartTS = curTime # 大奖赛开始的时间戳 self.grandPrixFireCount = config.getGrandPrixConf( "fireCount")[0] self._saveGrandPrixData() # 保存大奖赛数据 else: if not grand_prix.isGrandPrixOpenTime(): # 现在不可参赛 code = SignupCode.SC_NOT_OPEN elif not self.isGrandPrixMode(): code = SignupCode.SC_SUCC else: code = SignupCode.SC_UNFINISH if code in [SignupCode.SC_SUCC, SignupCode.SC_UNFINISH]: interval = max(0.1, remainGrandPrixTimeSeconds) if self.grandPrixFireCount == 0: # 3秒之后结束大奖赛 interval = 0.1 if self.grandPrixEndTimer: self.grandPrixEndTimer.cancel() self.grandPrixEndTimer = None self.grandPrixEndTimer = FTLoopTimer(interval, 0, self.endGrandPrix) # 启动结束定时器 self.grandPrixEndTimer.start() # 取消处于使用中的技能,以免干扰技能使用次数计数 if self.offline == 0: # 玩家在线 self.cancelUsingSkills() self.unloadSkills() self.loadAllSkillData() self.syncSkillSlots() elif code == SignupCode.SC_NOT_OPEN: # 没开启 self._resetGrandPrixData() # 重置大奖赛相关数据 self._getSurpassTarget() # 获取要超越的玩家数据 mo = MsgPack() mo.setCmd("start_grand_prix") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", self.userId) mo.setResult("seatId", self.seatId) mo.setResult("fireCount", self.grandPrixFireCount) mo.setResult("fishPoint", self.grandPrixFishPoint) mo.setResult("targetFish", self.grandPrixTargetFish) mo.setResult( "useSkillTimes", { val.get("skillId", 0): val.get("count", 0) for val in self.grandPrixUseSkillTimes }) 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)
def getMoney(userId, clientId, productId): """ 取钱 """ key = UserData.piggyBankData % (FISH_GAMEID, userId) vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0) conf = config.getPiggyBankProduct(clientId, productId) type = conf.get("type") iscooling = conf.get("iscooling", 0) ts = int(time.time()) / 60 * 60 endcoolingTS = 0 if iscooling: endcoolingTime = conf.get("endcoolingTime", 0) endcoolingTS = util.getDayStartTimestamp(ts) + endcoolingTime * 60 * 60 if ts >= endcoolingTS: endcoolingTS += 86400 piggyBankData = daobase.executeUserCmd(userId, "HGET", key, type) if piggyBankData: piggyBankData = json.loads(piggyBankData) else: piggyBankData = {} code = 4 totalMoney = 0 getMoneyCount = 0 rewards = [] if piggyBankData.get( GameData.pb_enable, 0) == 1 and piggyBankData.get(GameData.pb_getMoneyTS, 0) <= ts: code = 0 resetTime = _getResetTime(conf.get("resetTime", -1)) _resetKey = _getDataKey( ts, resetTime) # str(util.getDayStartTimestamp(ts)) if resetTime == -1: totalMoney = int(piggyBankData.get(GameData.pb_moneyCount, 0)) else: totalMoney = int( piggyBankData.get(GameData.pb_moneyCountDict, {}).get(_resetKey, 0)) getMoneyCount = min(totalMoney, conf.get("maxCount", 0)) if getMoneyCount > 0: piggyBankData[GameData.pb_savedMoneyCount].setdefault(_resetKey, 0) piggyBankData[GameData.pb_savedMoneyCount][_resetKey] = 0 # piggyBankData[GameData.pb_moneyCount] -= getMoneyCount if type == "free": piggyBankData[ GameData. pb_getMoneyTS] = ts + FREE_PIGGY_BANK_COOLDOWN_INTERVAL else: if iscooling: piggyBankData[GameData.pb_endcoolingTS] = endcoolingTS piggyBankData[GameData.pb_getMoneyTS] = piggyBankData[ GameData.pb_endcoolingTS] else: piggyBankData[GameData.pb_getMoneyTS] = 0 piggyBankData[GameData.pb_enable] = 0 piggyBankData[GameData.pb_saveMoneyTS] = ts conf = config.getPiggyBankConf(clientId, vipLevel).get(type, {}) if resetTime == -1: piggyBankData[GameData.pb_moneyCount] = conf.get("initVal", 0) else: piggyBankData.setdefault(GameData.pb_moneyCountDict, {}) piggyBankData[ GameData.pb_moneyCountDict][_resetKey] = conf.get( "initVal", 0) piggyBankData[GameData.pb_moneyCount] = piggyBankData[ GameData.pb_moneyCountDict][_resetKey] daobase.executeUserCmd(userId, "HSET", key, type, json.dumps(piggyBankData)) rewards = [{"name": config.CHIP_KINDID, "count": getMoneyCount}] util.addRewards(userId, rewards, "BI_NFISH_GET_PIGGY_BANK", vipLevel) ftlog.debug("piggy_bank, userId =", userId, "type =", type, "totalMoney =", totalMoney, "getMoneyCount =", getMoneyCount, "code =", code, "piggyBankData =", piggyBankData, util.timestampToStr(ts)) return code, rewards
def takeGiftRewards(userId, clientId, idx, fireCount, level): code = 1 rewards = [] lang = util.getLanguage(userId) errTxt = config.getMultiLangTextConf("ID_NEWBIE_7_DAYS_GIFT_COND", lang) newbie7DayGiftData = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.newbie7DayGiftData) if isinstance(newbie7DayGiftData, list) and len(newbie7DayGiftData) == 2: startTS, takenDays = newbie7DayGiftData curDayStartTS = util.getDayStartTimestamp(int(time.time())) curDayIdx = (curDayStartTS - startTS) / 86400 daysConf = config.getNewbie7DaysGiftConf() # 未过期前只能领取当前奖励 if curDayIdx == idx and curDayIdx not in takenDays and curDayIdx <= daysConf[ -1].get("idx"): rewards = daysConf[idx].get("rewards", []) if daysConf[idx].get("cond"): for key, val in daysConf[idx].get("cond", {}).iteritems(): # 玩家等级 if key == "level" and level < val: errTxt = config.getMultiLangTextConf( daysConf[idx].get("des"), lang) break # 开火次数 elif key == "fire": if not isinstance(val, list) or len(val) != 2: break if val[0] and fireCount.get(val[0]) < val[1]: errTxt = config.getMultiLangTextConf( daysConf[idx].get("des"), lang) break if not val[0] and sum(fireCount.values()) < val[1]: errTxt = config.getMultiLangTextConf( daysConf[idx].get("des"), lang) break else: code = 0 else: code = 0 if code == 0: errTxt = "" newbie7DayGiftData[-1].append(curDayIdx) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.newbie7DayGiftData, json.dumps(newbie7DayGiftData)) util.addRewards(userId, rewards, "BI_NFISH_NEWBIE_7DAYS_GIFT", param01=idx + 1) util.increaseExtraRechargeBonus( userId, daysConf[idx].get("rechargeBonus", 0)) message = MsgPack() message.setCmd("newbie_7_gift_take") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) message.setResult("clientId", clientId) message.setResult("idx", idx) message.setResult("code", code) message.setResult("errTxt", errTxt) _rewards = _processRewards(rewards) message.setResult("rewards", _rewards) router.sendToUser(message, userId) if ftlog.is_debug(): ftlog.debug("newbie7DaysGift, userId =", userId, newbie7DayGiftData, "message =", message)