def sendWelcomeMail(userId): """ 发送欢迎邮件 """ message = None welcomeMailConfs = config.getCommonValueByKey("ignoreConf") clientId = util.getClientId(userId) ftlog.debug("sendWelcomeMail", userId, "clientId = ", clientId) lang = util.getLanguage(userId) rewards = config.getCommonValueByKey("welcomeMailRewards") for welcomeMailConf in welcomeMailConfs: if clientId in welcomeMailConf.get("clientIds", []): # 不可显示实物、人民币相关描述 message = config.getMultiLangTextConf( "ID_CONFIG_BAN_ENTITY_WELCOME_MSG", lang=lang) else: # 可显示实物、人民币相关描述 message = config.getMultiLangTextConf( "ID_CONFIG_ALLOW_ENTITY_WELCOME_MSG", lang=lang) if message: mail_system.sendSystemMail(userId, mail_system.MailRewardType.SystemReward, rewards, message=message, title=config.getMultiLangTextConf( "ID_MAIL_TITLE_HOT_WELCOME", lang=lang))
def addShareInvitedUserId(shareUserId, invitedUserId, isNewUser=False): """ 添加分享邀请人信息 :param shareUserId: 分享卡片的分享者 :param invitedUserId: 点击卡片的被邀请者 :param isNewUser: 是否为新用户 """ inviteCount = weakdata.getDayFishData(shareUserId, "inviteCount", 0) if inviteCount < config.getCommonValueByKey("inviteLimitCount", 99999): if not isNewUser: inviteOldUserCount = weakdata.getDayFishData(shareUserId, "inviteOldUserCount", 0) if inviteOldUserCount > config.getCommonValueByKey("inviteLimitOldCount", 99999): return weakdata.incrDayFishData(shareUserId, "inviteOldUserCount", 1) inviteList = gamedata.getGameAttrJson(shareUserId, FISH_GAMEID, GameData.inviteList, []) inviteId = gamedata.incrGameAttr(shareUserId, FISH_GAMEID, GameData.inviteId, 1) inviteData = { "inviteId": inviteId, "userId": invitedUserId, "inviteTime": int(time.time()), "isNewUser": isNewUser, "isAppUser": 1 if util.isAppClient(invitedUserId) else 0 } inviteList.append(inviteData) gamedata.setGameAttr(shareUserId, FISH_GAMEID, GameData.inviteList, json.dumps(inviteList)) weakdata.incrDayFishData(shareUserId, "inviteCount", 1) module_tip.addModuleTipEvent(shareUserId, "invite", inviteId) getShareTaskInfo(shareUserId) from newfish.game import TGFish from newfish.entity.event import InvitedFinishEvent event = InvitedFinishEvent(shareUserId, FISH_GAMEID) TGFish.getEventBus().publishEvent(event)
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 sendIdentifyReward(userId): """ 实名认证领奖 """ mo = MsgPack() mo.setCmd("id_card_identify_reward") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) identifyReward = [] if ftlog.is_debug(): ftlog.debug("user_system.sendIdentifyReward IN", "userId=", userId) try: rewarded = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.idCardRewarded) if rewarded: code = 1 else: idCardReward = config.getCommonValueByKey("idCardReward", []) if ftlog.is_debug(): ftlog.debug("user_system.sendIdentifyReward send reward", "userId=", userId, "idCardReward=", idCardReward) code = util.addRewards(userId, idCardReward, "BI_NFISH_NEW_USER_REWARDS") if code == 0: identifyReward = idCardReward gamedata.setGameAttr(userId, FISH_GAMEID, GameData.idCardRewarded, 1) except Exception as e: ftlog.error("user_system.sendIdentifyReward error", e, "userId=", userId) code = 3 mo.setResult("code", code) mo.setResult("reward", identifyReward) router.sendToUser(mo, userId)
def _sendQuestFinished(userId, quest): """发送完成的每日任务""" level = util.getUserLevel(userId) if level < config.getCommonValueByKey("dailyQuestOpenLevel"): return lang = util.getLanguage(userId) mo = MsgPack() mo.setCmd("task") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("action", "finished") mo.setResult("taskId", quest["taskId"]) # if quest["taskType"] == TaskType.CoinNum and quest["des"].find("%s") >= 0: # des = quest["des"] % util.formatScore(quest["targetsNum"]) # elif quest["des"].find("%d") >= 0: # des = quest["des"] % quest["targetsNum"] # else: # des = quest["des"] questDes = config.getMultiLangTextConf(quest["des"], lang=lang) if questDes.find("%s") >= 0: des = questDes % util.formatScore(quest["targetsNum"], lang=lang) elif questDes.find("%d") >= 0: des = questDes % quest["targetsNum"] elif questDes.count("{}") >= 2: des = questDes.format(quest["gunX"], quest["targetsNum"]) else: des = questDes mo.setResult("des", des) router.sendToUser(mo, userId)
def loginByInvited(userId, shareUserId, isNewPlayer): """ :param userId: 被邀请人 :param shareUserId: 分享者(邀请人) :param isNewPlayer: 是否为新用户 """ isCanInvite = config.getCommonValueByKey("canInvite") isInvite = weakdata.getDayFishData(userId, "isInvited", 0) if not isCanInvite or isInvite: return False userdata.checkUserData(shareUserId) if isNewPlayer: from newfish.game import TGFish from newfish.entity.event import AddInvitedNewUserEvent # 存储邀请人信息 from hall.entity import hallvip from newfish.entity.redis_keys import GameData shareUserVip = int(hallvip.userVipSystem.getUserVip(shareUserId).vipLevel.level) inviterInfo = { "userId": shareUserId, "inviteTime": int(time.time()), "vip": shareUserVip } gamedata.setGameAttr(userId, FISH_GAMEID, GameData.inviterInfo, json.dumps(inviterInfo)) saveKey = "inviteNewPlayers" actionType = NewPlayerAction event = AddInvitedNewUserEvent(shareUserId, FISH_GAMEID, userId) TGFish.getEventBus().publishEvent(event) else: saveKey = "recallPlayers" actionType = RecallPlayerAction user_rpc.addInviteNum(shareUserId, userId, actionType, saveKey, isNewPlayer) return True
def checkCondition(self, player, fishConf): """ 检查出现条件 """ userId = player.userId chestFishInterval = int( config.getCommonValueByKey("chestFishInterval", 120)) if time.time() - self.chestFishTime >= chestFishInterval: chestPoolCoin = 0 if self.table.room.lotteryPool: chestPoolCoin = self.table.room.lotteryPool.getChestPoolCoin() chestFishConf = config.getChestFishConf( self.table.runConfig.fishPool) playerMaxCoin = chestFishConf["maxCoin"] profitForChest = player.profitForChest.get( str(self.table.runConfig.fishPool), 0) resultNum = (math.sqrt(fishConf["score"]) - 30 * math.pow(profitForChest / playerMaxCoin, 3)) / 500 randomNum = random.randint(1, 10000) if chestPoolCoin > 0 and randomNum <= resultNum * 10000: chestScore = self._getChestScore(chestFishConf) player.clearProfitChest() self._addChestFishGroup(userId, chestScore) self.chestFishTime = time.time() if ftlog.is_debug(): ftlog.debug("ChestFishGroup->checkCondition", userId, chestPoolCoin, profitForChest, chestScore)
def getMultipleFishMultiple(self, player, fishConf, fpMultiple, gunMultiple, gunX): """ 获得倍率鱼的倍率 """ betDict = config.getCommonValueByKey("newbieBetFish") curTaskId = player.taskSystemUser.curTask.getTaskId() pass
def catchFish(self, kindId, fIds=None, lockFid=0): """ 处理技能道具效果 """ data = self.player.skills_item_slots if kindId not in data: return item_data = data[kindId] addTimeGroups = [] frozenFishes = [] duration = item_data["conf"]["duration"] # 冰冻时间 endTime = time.time() + duration frozenBuffer = [5104, endTime, self.userId, 1, 1, duration, 0] frozenNum = 0 for fId in fIds: isOK = self.table.findFish(fId) if not isOK: continue bufferEffect = [ 1 for buffer in self.table.fishMap[fId]["buffer"] if buffer[0] == 5104 and time.time() < buffer[1] ] if len(bufferEffect) > 0 and lockFid != fId: frozenNum += 1 continue fishConf = config.getFishConf(self.table.fishMap[fId]["fishType"], self.table.typeName, self.table.runConfig.multiple) # 计算能否冰冻 isCoverFrozen, lastFrozenTime, frozenTime, _ = self.table.checkCoverFrozen( fId, duration, endTime) if isCoverFrozen: isCoverFrozen = random.randint( 1, 10000) <= config.getCommonValueByKey( "freezeProbb", 6500) if isCoverFrozen: frozenFishes.append( [fId, lastFrozenTime, frozenTime, fishConf["probb2"]]) if SkillItem.FREEZE_NUM - frozenNum > 0: if len(frozenFishes) >= SkillItem.FREEZE_NUM - frozenNum: frozenFishes.sort(key=lambda x: x[-1], reverse=True) frozenFishes = frozenFishes[:SkillItem.FREEZE_NUM - frozenNum] frozenNewFishes = [] for frozenInfo in frozenFishes: self.table.frozenFish(frozenInfo[0], frozenBuffer, frozenInfo[1], frozenInfo[2], addTimeGroups) frozenNewFishes.append(frozenInfo[0]) if frozenNewFishes: # 广播新处于冰冻状态的鱼 self.table.broadcastSkillEffect(self.player, endTime, frozenNewFishes, 5104, isSkillItem=True) self.player.end_skill_item(kindId)
def sendCommonConfig(userId): clientId = util.getClientId(userId) mo = MsgPack() mo.setCmd("fishCommonConfig") mo.setResult("gameId", FISH_GAMEID) mo.setResult("clientId", clientId) mo.setResult("userId", userId) # sendKeys = ["weChatPublicNum", "weChatTelephone", "weChatQQGroup"] sendKeys = ["publicNum", "telephone"] sendHash = {} for key_ in sendKeys: sendHash[key_] = config.getCommonValueByKey(key_, 0) # led版本限制 ledIds = config.getIgnoreConf("ledIds", clientId) if ledIds is None: ledIds = [] groups = config.getIgnoreConf("groups", clientId) if groups is None: groups = [] ignoreClient = config.isClientIgnoredConf("clientIds", clientId, clientId) sendHash["ignoreConf"] = {"ledIds": ledIds, "groups": groups, "pureClient": 1 if ignoreClient else 0} # 身份证验证版本限制 cardIdInfo = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.idCardInfo) cardIdIdentify = config.getCommonValueByKey("cardIdIdentify") sendHash["cardIdIdentify"] = 1 if clientId in cardIdIdentify and not cardIdInfo else 0 # 防沉迷配置. antiAddictionConf = config.getCommonValueByKey("antiAddiction", {}) enableAntiAddiction = antiAddictionConf.get("defaultEnable", 0) if clientId in antiAddictionConf.get("exceptionClientId", []): enableAntiAddiction = 1 - enableAntiAddiction sendHash["enableAntiAddiction"] = enableAntiAddiction # 防沉迷时间限制. sendHash["enableAAPlay"] = antiAddictionConf.get("enablePlay", 0) if enableAntiAddiction else 1 # 防沉迷充值限制. sendHash["enableAABuy"] = antiAddictionConf.get("enableBuy", 0) if enableAntiAddiction else 1 mo.setResult("commonConfig", sendHash) mo.setResult("couponDisplayRate", int(1/config.COUPON_DISPLAY_RATE)) if ftlog.is_debug(): ftlog.debug("sendCommonConfig", mo) router.sendToUser(mo, userId)
def modifyUserName(userId): """ iOS下游客登录及苹果登录用户修改昵称为g_xxxx """ clientIdNum = util.getClientIdNum(userId) if clientIdNum in config.getCommonValueByKey("randomNickNameClientIds", []): snsId = userdata.getAttr(userId, "snsId") if not snsId or str(snsId).startswith("ios"): nickName = "g_" + ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(7)) userdata.setAttr(userId, "name", nickName)
def getShareTaskInfo(userId): """ 获取分享有礼信息 """ shareGroupIds = weakdata.getDayFishData(userId, "shareGroupIds", []) shareGroupTotalCount = config.getCommonValueByKey("shareGroupTotalCount") shareGroupCurrentCount = min(len(shareGroupIds), shareGroupTotalCount) groupTask = { "taskId": 0, "progress": [shareGroupCurrentCount, shareGroupTotalCount], # 分享群数/总数 "rewards": config.getCommonValueByKey("shareGroupRewards"), "state": weakdata.getDayFishData(userId, "shareGroupReward", 0) } if groupTask["state"] == 0 or util.isVersionLimit(userId): module_tip.cancelModuleTipEvent(userId, "invite", 0) inviteTasks = [] inviteList = refreshInviteData(userId) for _, inviteData in enumerate(inviteList): name = util.getNickname(inviteData["userId"]) avatar = userdata.getAttr(inviteData["userId"], "purl") if inviteData.get("isAppUser", 0) == 1: continue if inviteData.get("isNewUser"): rewards = config.getCommonValueByKey("newUserInviteFriendRewards") else: rewards = config.getCommonValueByKey("inviteFriendRewards") task = { "taskId": inviteData["inviteId"], "name": name, "avatar": avatar, "vip": hallvip.userVipSystem.getUserVip(userId).vipLevel.level, "state": 2 if inviteData.get("receiveTime") else 1, "rewards": rewards } inviteTasks.append(task) inviteCount = weakdata.getDayFishData(userId, "inviteCount", 0) inviteTotalCount = config.getCommonValueByKey("inviteLimitCount", 99999) inviteCount = min(inviteCount, inviteTotalCount) friendTask = { "progress": [inviteCount, inviteTotalCount], "rewards": config.getCommonValueByKey("inviteFriendRewards"), "newUserRewards": config.getCommonValueByKey("newUserInviteFriendRewards"), "tasks": inviteTasks } message = MsgPack() message.setCmd("share_task_info") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) if not util.isVersionLimit(userId): message.setResult("groupTask", groupTask) message.setResult("friendTask", friendTask) router.sendToUser(message, userId)
def getCatchBufferId(self, bufferIds): """获取捕获的bufferId""" totalPlayerNum = self.table._match_table_info["playerCount"] paramK = int(config.getCommonValueByKey("createBufferParamK")) paramD = int(config.getCommonValueByKey("createBufferParamD")) k1 = 1 + (self.rank - 1) * (paramK - 1) * 1.0 / max((totalPlayerNum - 1), 1) paramL = 2 * k1 - paramK - 1 paramB = abs(paramL) + paramD probs = [] bufferNum = len(bufferIds) if ftlog.is_debug(): ftlog.debug("getCatchBufferId========>", self.rank, totalPlayerNum, paramK, paramD, paramL, paramB) probZs = [] for i in xrange(bufferNum + 1): xn = -1 + 2.0 * i / bufferNum yn = paramL * xn + paramB # sumNum += int(yn * 1000) probs.append(yn) if i > 0: zn = int((probs[i] + probs[i-1]) * bufferNum * 1000) # 结果扩大3位数 probZs.append(zn) randNum = random.randint(1, sum(probZs)) sumNum = 0 if ftlog.is_debug(): ftlog.debug("getCatchBufferId========>", randNum, sum(probZs), probZs, probs, paramB) for index, num_ in enumerate(probZs): if randNum <= sumNum + num_: if ftlog.is_debug(): ftlog.debug("getCatchBufferId========>", bufferIds[index], sumNum + num_) return bufferIds[index] sumNum += num_ if ftlog.is_debug(): ftlog.debug("getCatchBufferId========>", sumNum, probZs) return -1
def doGetInviteTasks(userId, actionType): message = MsgPack() message.setCmd("invite_task_infos") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) message.setResult("actionType", actionType) isCanInvite = config.getCommonValueByKey("canInvite") if not isCanInvite: message.setResult("code", 100) else: message.setResult("code", 0) tasksInfos, playerNums = getInviteTasks(userId, actionType) message.setResult("tasks", tasksInfos) message.setResult("playerNums", playerNums) router.sendToUser(message, userId)
def _initPlayerAchieveTasks(self, userId): taskObjects = [] if self.player.level < config.getCommonValueByKey( "achievementOpenLevel"): return taskObjects # 渔场内支持的任务类型,数据会及时刷新。 tableTypes = [ AchieveType.CatchFishNum, AchieveType.CatchBetFishNum, AchieveType.CatchBossNum ] achConfigs = config.getAchievementConf().get("tasks") for honorId, tasksConf in achConfigs.iteritems(): for _, conf in tasksConf.iteritems(): if conf["type"] in tableTypes: taskClass = FishAchievementTask(userId, conf) taskObjects.append(taskClass) return taskObjects
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)
def doGetTaskRewards(userId, taskId, actionType): message = MsgPack() message.setCmd("invite_task_receive") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) isCanInvite = config.getCommonValueByKey("canInvite") if not isCanInvite: message.setResult("code", 100) router.sendToUser(message, userId) else: code, chestId, rewards, taskState = receiveInvitTaskReward(userId, taskId, actionType) message.setResult("code", code) if code == 0: message.setResult("chestId", chestId) message.setResult("rewards", rewards) message.setResult("taskId", taskId) message.setResult("actionType", actionType) router.sendToUser(message, userId) if len(taskState) > 0 and len(taskState) % OneGroupNum == 0: doGetInviteTasks(userId, actionType)
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
def dealCatchEvent(self, event, tableMultiple, coinAddition, playersNum): """ 处理捕鱼事件 :param event: 捕获事件详情 :param tableMultiple: 房间倍率 :param coinAddition: 当处于累计捕获金币任务时的进度加成 :param playersNum: 当前桌内玩家数量 :return: """ if self.taskConfig["type"] in [TaskType.UseSkillNum, TaskType.ComboNum]: return if self.taskData["state"] != TaskState.Update: return isMe = event.userId == self.userId fishTypes = event.fishTypes # 鱼种类 wpId = event.wpId gunSkinMul = event.gunSkinMul target = self.taskConfig["target"] progress = 0 isTargetAddition = False if self.taskConfig["type"] in [TaskType.CatchFishCoin, TaskType.UseSkillCatchFishCoin]: progress = coinAddition elif self.taskConfig["type"] in [TaskType.CatchFishNum, TaskType.CatchBossNum, TaskType.FishNumCoinHigh, TaskType.BetFishNum, TaskType.CatchRainbowFishNum, TaskType.CatchRedPacketFishNum]: friendHelpPlayerMultiple = config.getCommonValueByKey("friendHelpPlayerMultiple", {}).get(str(playersNum - 1), 0) probb = (friendHelpPlayerMultiple * (self.taskData["targetNum"] + 5) / self.taskData["targetNum"]) * 10000 randInt = random.randint(1, 10000) if randInt <= probb: isTargetAddition = True if self.taskConfig["type"] == TaskType.CatchFishCoin: # 1捕获xx鱼达金币数 totalCoin, fishCoins, _ = self._getCatchFishCoin(event) if target: self._addProgress(fishCoins.get(str(target), 0), isMe, progress=progress, isTargetAddition=isTargetAddition) else: self._addProgress(totalCoin, isMe, progress=progress, isTargetAddition=isTargetAddition) elif self.taskConfig["type"] == TaskType.CatchFishNum: # 2捕获鱼个数 if target: betTarget = 14000 + int(target) % 11000 fishNum = fishTypes.count(target) + fishTypes.count(betTarget) self._addProgress(fishNum, isMe, progress=progress, isTargetAddition=isTargetAddition) else: self._addProgress(len(fishTypes), isMe, progress=progress, isTargetAddition=isTargetAddition) return elif self.taskConfig["type"] == TaskType.CatchBossNum: # 3捕获boss个数 bossNum = 0 # boss个数 for fishType in fishTypes: fishConf = config.getFishConf(fishType, self.taskSystem.table.typeName, tableMultiple) if fishConf["type"] in config.BOSS_FISH_TYPE: bossNum += 1 self._addProgress(bossNum, isMe, progress=progress, isTargetAddition=isTargetAddition) return elif self.taskConfig["type"] == TaskType.FishNumCoinHigh: # 4多少金币以上的鱼 _, _, num = self._getCatchFishCoin(event, target) self._addProgress(num, isMe, progress=progress, isTargetAddition=isTargetAddition) return elif self.taskConfig["type"] == TaskType.BetFishNum: # 5--多少只倍率鱼 betFishMap = {} for gainMap in event.gain: fishConf = config.getFishConf(gainMap["fishType"], self.taskSystem.table.typeName, tableMultiple) itemId = gainMap["itemId"] itemCount = gainMap["count"] if fishConf["type"] in config.MULTIPLE_FISH_TYPE: if itemId == config.CHIP_KINDID: # 金币 bet = itemCount / fishConf["score"] / tableMultiple / gunSkinMul betFishMap[str(bet)] = betFishMap.get(str(bet), 0) + 1 betNum = 0 for bet in betFishMap: if int(bet) >= target: betNum += betFishMap[bet] self._addProgress(betNum, isMe, progress=progress, isTargetAddition=isTargetAddition) elif self.taskConfig["type"] == TaskType.UseSkillCatchFishNum: # 8 使用技能捕获鱼数 wpType = util.getWeaponType(wpId) if wpType in [config.SKILL_WEAPON_TYPE, config.RB_FIRE_WEAPON_TYPE, config.RB_BOMB_WEAPON_TYPE]: if target: self._addProgress(fishTypes.count(target), isMe, progress=progress, isTargetAddition=isTargetAddition) else: self._addProgress(len(fishTypes), isMe, progress=progress, isTargetAddition=isTargetAddition) elif self.taskConfig["type"] == TaskType.UseSkillCatchFishCoin: # 9 使用技能捕获XX金币类型的鱼数 totalCoin, fishCoins, _ = self._getCatchFishCoin(event) # 总金币数不包括招财珠 wpType = util.getWeaponType(wpId) if wpType in [config.SKILL_WEAPON_TYPE, config.RB_FIRE_WEAPON_TYPE, config.RB_BOMB_WEAPON_TYPE]: if target: self._addProgress(fishCoins.get(str(target), 0), isMe, progress=progress, isTargetAddition=isTargetAddition) else: self._addProgress(totalCoin, isMe, progress=progress, isTargetAddition=isTargetAddition) elif self.taskConfig["type"] == TaskType.CatchFishNumByOneFire: # 10 1网捕获多少鱼 if len(fishTypes) >= target: value = 1 if not isMe: return self._addProgress(value, isMe, progress=progress, isTargetAddition=isTargetAddition) elif self.taskConfig["type"] == TaskType.CatchRainbowFishNum: # 捕获彩虹鱼 rainbowNum = 0 for fishType in fishTypes: fishConf = config.getFishConf(fishType, self.taskSystem.table.typeName, tableMultiple) if fishConf["type"] in config.RAINBOW_FISH_TYPE: rainbowNum += 1 self._addProgress(rainbowNum, isMe, progress=progress, isTargetAddition=isTargetAddition) elif self.taskConfig["type"] == TaskType.CatchRedPacketFishNum: # 捕获红包券鱼 redPacketNum = 0 for fishType in fishTypes: fishConf = config.getFishConf(fishType, self.taskSystem.table.typeName, tableMultiple) if fishConf["type"] == 4: redPacketNum += 1 self._addProgress(redPacketNum, isMe, progress=progress, isTargetAddition=isTargetAddition)
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
def triggerCatchFishEvent(self, event): """捕获鱼""" if self.table.typeName not in config.NORMAL_ROOM_TYPE: return if not self.player or self.player.userId <= 0: return if self.player.level < config.getCommonValueByKey( "achievementOpenLevel"): return if not self.achieveTasks: self.achieveTasks = self._initPlayerAchieveTasks( self.player.userId) if hasattr(event, "fpMultiple"): fpMultiple = event.fpMultiple else: fpMultiple = self.table.runConfig.multiple fishIds = event.fishTypes # 鱼种类 fTypes = [] betFishMap = {} # 计算倍率鱼 个数 bossNum = 0 # boss个数 for fishType in fishIds: fishConf = config.getFishConf(fishType, self.table.typeName, self.player.fpMultiple) if fishConf["type"] in config.BOSS_FISH_TYPE: bossNum += 1 fTypes.append(fishConf["type"]) for gainMap in event.gain: fishConf = config.getFishConf(gainMap["fishType"], self.table.typeName, self.player.fpMultiple) itemId = gainMap["itemId"] itemCount = gainMap["count"] if fishConf["type"] not in config.MULTIPLE_FISH_TYPE: continue if itemId == config.CHIP_KINDID: # 金币 bet = itemCount / fishConf["score"] / fpMultiple if str(bet) not in betFishMap: betFishMap[str(bet)] = 1 else: betFishMap[str(bet)] += 1 tipHonorIds = [] for taskClass in self.achieveTasks: hasComplete = False taskConf = taskClass.getTaskConf() if taskConf["type"] == AchieveType.CatchFishNum: # 捕获鱼多少条 count = len(fishIds) fishTypes = taskConf["target"].get("fishType") if fishTypes: count = sum([fTypes.count(type_) for type_ in fishTypes]) hasComplete = taskClass.addProgress(count, inTable=True) elif taskConf["type"] == AchieveType.CatchBetFishNum: # 捕获倍率鱼总数 betNum = 0 targetBet = taskConf["target"]["condition"] for bet in betFishMap: if int(bet) >= targetBet: betNum += betFishMap[bet] hasComplete = taskClass.addProgress(betNum, inTable=True) elif taskConf["type"] == AchieveType.CatchBossNum and ( taskConf["target"].get("condition", self.table.runConfig.multiple) == self.table.runConfig.multiple): # 捕获boss个数 hasComplete = taskClass.addProgress(bossNum, inTable=True) # 添加小红点 if hasComplete and taskClass.getHonorId() not in tipHonorIds: tipHonorIds.append(taskClass.getHonorId()) if tipHonorIds: module_tip.addModuleTipEvent(self.player.userId, "achievement", tipHonorIds)
def onCmdQuickStart(cls, msg, userId, gameId, roomId, tableId, clientId, kindId): """UT server中处理来自客户端的quick_start请求 Args: msg cmd : quick_start if roomId == 0: 表示快速开始,服务器为玩家选择房间,然后将请求转给GR if roomId > 0 and tableId == 0 : 表示玩家选择了房间,将请求转给GR if roomId > 0 and tableId == roomId * 10000 : 表示玩家在队列里断线重连,将请求转给GR if roomId > 0 and tableId > 0: if onlineSeatId > 0: 表示玩家在牌桌里断线重连,将请求转给GT else: 表示玩家选择了桌子,将请求转给GR """ assert isinstance(userId, int) and userId > 0 assert isinstance(roomId, int) and roomId >= 0 assert isinstance(tableId, int) and tableId >= 0 if ftlog.is_debug(): ftlog.debug("onCmdQuickStart->", userId, "msg =", msg, "roomId =", roomId, "tableId =", tableId, "clientId =", clientId) isRobot = userId < config.ROBOT_MAX_USER_ID if not isRobot and not util.isUsableClientVersion(userId): cls.onQuickStartFailed(cls.ENTER_ROOM_REASON_VERSION_DISABLE, userId, clientId, roomId) return # 单开, 无论何时quick_start进入都检查loc if not pokerconf.isOpenMoreTable(clientId): locList = onlinedata.getOnlineLocList(userId) if ftlog.is_debug(): ftlog.debug("onCmdQuickStart->getOnlineLocList->", userId, locList) try: for lRoomId, lTableId, lSeatId in locList: roomGameId = strutil.getGameIdFromInstanceRoomId(lRoomId) if roomGameId == FISH_GAMEID: roomId = lRoomId tableId = lTableId ftlog.info( "onCmdQuickStart->reconnect roomId, tableId->", userId, roomId, tableId) else: cls.onQuickStartFailed( cls.ENTER_ROOM_REASON_STATE_ERROR, userId, clientId, roomId) return break except: ftlog.warn("onCmdQuickStart->error", userId, roomId, tableId) redState = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.redState) if isRobot is False and redState == 0: ctrlRoomId = config.getCommonValueByKey("newbieRoomId") chosenTableId = 0 shadowRoomId = None if gdata.getBigRoomId(roomId) == gdata.getBigRoomId( ctrlRoomId) and tableId: chosenTableId = tableId shadowRoomId = tableId / 10000 TYRoomMixin.queryRoomQuickStartReq( msg, ctrlRoomId, chosenTableId, shadowRoomId=shadowRoomId) # 请求转给GR return if roomId == 0: # 玩家点击快速开始 chosenRoomId, reason = cls._chooseRoom(userId, gameId) ftlog.info("onCmdQuickStart->chosenRoomId", chosenRoomId, "userId =", userId, "reason =", reason) if reason == cls.ENTER_ROOM_REASON_OK: TYRoomMixin.queryRoomQuickStartReq(msg, chosenRoomId, 0) # 请求转给GR else: cls.onQuickStartFailed(reason, userId, clientId, roomId) return if tableId == 0: # 玩家只选择了房间 bigRoomId = gdata.getBigRoomId(roomId) if bigRoomId == 0: cls.onQuickStartFailed(cls.ENTER_ROOM_REASON_ROOM_ID_ERROR, userId, clientId, roomId) return ctrlRoomIds = gdata.bigRoomidsMap()[bigRoomId] ctrlRoomId = ctrlRoomIds[userId % len(ctrlRoomIds)] reason = cls.canQuickEnterRoom(userId, gameId, ctrlRoomId, kindId) if reason == cls.ENTER_ROOM_REASON_OK: roomConf = gdata.roomIdDefineMap()[roomId].configure fee = roomConf.get("fee_%s" % kindId, {}) or roomConf.get( "fee", {}) rewards = fee.get("rewards", []) if fee: _consume = [{"name": fee["kindId"], "count": fee["count"]}] ret = util.consumeItems(userId, _consume, "ROOM_GAME_FEE") if ret and rewards: util.addRewards(userId, rewards, "BI_NFISH_VOUCHER_REWARDS", kindId) TYRoomMixin.queryRoomQuickStartReq(msg, ctrlRoomId, 0) # 请求转给GR或GT else: cls.onQuickStartFailed(reason, userId, clientId, roomId) return if tableId == roomId * 10000: # 玩家在队列里断线重连 TYRoomMixin.queryRoomQuickStartReq(msg, roomId, tableId) # 请求转给GR return onlineSeat = onlinedata.getOnlineLocSeatId(userId, roomId, tableId) if onlineSeat: TYRoomMixin.querySitReq(userId, roomId, tableId, clientId, {"seatId": onlineSeat}) # 玩家断线重连,请求转给GT else: # 玩家选择了桌子 shadowRoomId = tableId / 10000 ctrlRoomId = gdata.roomIdDefineMap()[shadowRoomId].parentId TYRoomMixin.queryRoomQuickStartReq( msg, ctrlRoomId, tableId, shadowRoomId=shadowRoomId) # 请求转给GR
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
def isLimitLevel(userId): """荣耀等级限制""" userLevel = util.getUserLevel(userId) if userLevel < config.getCommonValueByKey("achievementOpenLevel"): return True return False