-- GameServer (Script) -> ServerScriptService -- Логика игры: данные, удача, рыбалка с анимацией, сумка, магазин, улучшения, -- коллекция с наградами, задания, ежедневная награда, события, миры, донат. local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local DataStoreService = game:GetService("DataStoreService") local ProximityPromptService = game:GetService("ProximityPromptService") local TweenService = game:GetService("TweenService") local RunService = game:GetService("RunService") local MarketplaceService = game:GetService("MarketplaceService") local Debris = game:GetService("Debris") local Config = require(ReplicatedStorage:WaitForChild("FishConfig")) local Models = require(ReplicatedStorage:WaitForChild("GameModels")) local Guild = require(script.Parent:WaitForChild("Guild")) local Progression = require(script.Parent:WaitForChild("Progression")) local Potions = require(script.Parent:WaitForChild("Potions")) local Market = require(script.Parent:WaitForChild("Market")) local Telemetry = require(script.Parent:WaitForChild("Telemetry")) local PlayerStore = require(script.Parent:WaitForChild("PlayerStore")) local E = Config.Economy local remote = ReplicatedStorage:FindFirstChild("GameEvent") or Instance.new("RemoteEvent") remote.Name = "GameEvent" remote.Parent = ReplicatedStorage ---------------------------------------------------------------- лента активности -- события для всех игроков (FishingClient показывает их в ленте и крупным баннером для редкого улова); -- самые редкие уловы уходят и на другие серверы игры через MessagingService (Config.Feed) local MessagingService = game:GetService("MessagingService") local FEED_TOPIC = "FishFeed" local function feed(kind, info) remote:FireAllClients("Feed", kind, info) end -- подписка — в фоне: SubscribeAsync ждёт ответа сервиса (в неопубликованном плейсе — долго), -- а скрипт должен сразу дойти до загрузки игроков, телепортов и остального task.spawn(function() pcall(function() MessagingService:SubscribeAsync(FEED_TOPIC, function(msg) local d = msg.Data if type(d) == "table" and d.jobId ~= game.JobId then d.remote = true -- улов на другом сервере feed("catch", d) end end) end) end) -- улов в ленту; big — крупный баннер со звуком у всех, global — ещё и на другие серверы local function feedCatch(player, fish, world) local r = Config.Rarities[fish.rarity] local F = Config.Feed local info = { name = player.DisplayName, userId = player.UserId, fish = fish.name, rarity = fish.rarity, mutation = fish.mutation, value = fish.value, world = world and (world.icon .. " " .. world.name) or nil, big = r.rank >= F.announceRank or F.announceMutations[fish.mutation or ""] == true, } feed("catch", info) if r.rank >= F.globalRank or F.globalMutations[fish.mutation or ""] then info.jobId = game.JobId task.spawn(function() pcall(function() MessagingService:PublishAsync(FEED_TOPIC, info) end) end) end end local rng = Random.new() local GOLD = Color3.fromRGB(255, 220, 80) local RED = Color3.fromRGB(255, 120, 120) local GREEN = Color3.fromRGB(120, 255, 140) local SPLASH_SOUND = "rbxasset://sounds/impact_water.mp3" ---------------------------------------------------------------- данные local store, marketStore = nil, nil pcall(function() store = DataStoreService:GetDataStore("FishingGame_v2") marketStore = DataStoreService:GetDataStore("FishMarket_v1") end) -- неопубликованный плейс / Studio без доступа к API: GetDataStore проходит, но любой запрос падает. -- Тогда сразу играем без сохранения (иначе вход ждал бы повторов загрузки и интерфейс стоял пустым) if store and RunService:IsStudio() then local ok = pcall(function() store:GetAsync("probe") end) if not ok then store, marketStore = nil, nil end end -- замок сессии: профиль открыт только на одном сервере (без этого возможен дюп между серверами и на рынке) local playerStore = store and PlayerStore.new(store, { staleAfter = 600 }) or nil local profiles = {} local loadedOk = {} local passes = {} local function defaultData() return { coins = 0, level = 1, xp = 0, rod = "Basic", rods = { Basic = true }, rodLevels = {}, bag = "Pouch", bags = { Pouch = true }, items = {}, discovered = {}, claimed = {}, chain = { index = 1, step = 1, progress = 0, tier = 0 }, daily = { last = 0, streak = 0 }, boostUntil = 0, boostBonus = 0, -- до экономики v2 (переносятся в potions миграцией) potions = { inv = {} }, market = {}, totalCaught = 0, nextUid = 1, receipts = {}, passes = {}, -- купленные пропуска (Developer Products): [key] = true coinsEarned = 0, robuxSpent = 0, -- для досок лидеров: всего выручено за рыбу и потрачено Robux settings = { music = Config.DefaultVolume.music, sfx = Config.DefaultVolume.sfx }, -- гильдия: жемчуг, печати, отдых (ранг, заказы, наживку, ловушки дополняет Guild.defaults) pearls = 0, seals = 0, rest = 0, } end -- status: "ok" (из хранилища), "offline" (хранилища нет — играем без сохранения), "locked", "error" local function loadData(player) local data = defaultData() if not playerStore then data.econ = E.version return data, "offline" end local status, saved = playerStore:load("player_" .. player.UserId) if status ~= "ok" then warn(("Не удалось загрузить данные %s: %s %s"):format(player.Name, status, tostring(saved))) data.econ = E.version return data, status end if type(saved) == "table" and next(saved) ~= nil and saved.level ~= nil then for k, v in pairs(saved) do data[k] = v end else data.econ = E.version -- новый игрок: миграция не нужна end return data, "ok" end -- ok; release = true — игрок уходит (снять замок сессии) local function saveData(player, release) local data = profiles[player] if not playerStore or not data or not loadedOk[player] then return false end local ok, status, err = playerStore:save("player_" .. player.UserId, data, release) if not ok then warn(("Не удалось сохранить данные %s: %s %s"):format(player.Name, tostring(status), tostring(err))) if status == "lost" then -- профиль уже открыт другим сервером: дальше этот сервер его не пишет loadedOk[player] = false end end return ok end ---------------------------------------------------------------- пропуска и события local function hasPass(player, key) return passes[player] ~= nil and passes[player][key] == true end -- пропуска продаются как Developer Products, поэтому владение хранится в данных игрока, а не в Roblox local function loadPasses(player, data) passes[player] = {} for _, gp in ipairs(Config.GamePasses) do if data.passes[gp.key] then passes[player][gp.key] = true end end end local currentEvent = nil local function ev(field, default) return (currentEvent and currentEvent[field]) or default end -- погода и время суток (их ведёт WeatherServer через атрибуты workspace) local function weather() return Config.WeatherById(workspace:GetAttribute("Weather")) end local function isNight() if not Config.DayNight.enabled then return false end return Config.IsNight(Config.ClockAt(workspace:GetServerTimeNow(), workspace:GetAttribute("DayStart"))) end ---------------------------------------------------------------- расчёты local function rodLevel(data, rodId) return data.rodLevels[rodId or data.rod] or 0 end -- удача от действующего зелья (донат «Супер-зелье», перенесённое старое зелье) local function boostActive(data) return Potions.effect(data).luck or 0 end local function masteryCount(data) local n = 0 for key in pairs(data.claimed) do if string.find(key, ":Master", 1, true) then n += 1 end end return n end local function totalLuck(player, data) local stats = Config.RodStats(data.rod, rodLevel(data)) local l = 1 + stats.luck + (data.level - 1) * Config.LuckPerPlayerLevel + boostActive(data) + masteryCount(data) * Config.MasteryLuck if hasPass(player, "VIP") then l += 0.25 end if hasPass(player, "LuckyCharm") then l += 0.5 end return l + ev("luck", 0) + (weather().luck or 0) + (isNight() and Config.DayNight.nightLuck or 0) end local function bagCapacity(player, data) local bag = Config.Find(Config.Bags, data.bag) or Config.Bags[1] return bag.capacity + (hasPass(player, "BigBag") and 100 or 0) end local function sellMult(player) local m = ev("sell", 1) if hasPass(player, "VIP") then m *= 1.25 end if hasPass(player, "DoubleCoins") then m *= 2 end return m end local function notify(player, text, color) remote:FireClient(player, "Notify", text, color or Color3.new(1, 1, 1)) end -- серебро: все начисления и траты — здесь (телеметрия источников и расходов) local function addCoins(player, data, amount, kind) amount = math.floor(amount) if amount <= 0 then return 0 end data.coins += amount Telemetry.silver(player, true, amount, data.coins, kind) return amount end local function spendCoins(player, data, amount, kind, sku) amount = math.floor(amount) if amount < 0 or data.coins < amount then return false end data.coins -= amount Telemetry.silver(player, false, amount, data.coins, kind, sku) return true end -- множитель серебряных наград: по самому дальнему открытому миру (1 / 2 / 4) local function tierOf(data) return Config.TierFor(data.level or 1) end local function today() return math.floor(os.time() / 86400) end local function sendInventory(player) local data = profiles[player] if data then remote:FireClient(player, "Inventory", data.items, data.discovered, data.claimed) end end ---------------------------------------------------------------- цепочки заданий local function currentChain(data) local c = data.chain local chain = Config.QuestChains[(c.index - 1) % #Config.QuestChains + 1] return chain, chain.steps[c.step] end local function stepGoal(data, step) local kind = Config.QuestKinds[step[1]] local g = step[2] * (1 + Config.QuestTierGrowth * data.chain.tier) if kind.byLevel then g *= tierOf(data) end g = math.ceil(g) return kind.max and math.min(g, kind.max) or g end -- награда шага: серебро (× tier); опыта карьеры у заданий нет (второе значение — 0 для старого клиента) local function stepReward(data, step, goal) local kind = Config.QuestKinds[step[1]] local t = tierOf(data) return math.max(Config.QuestMinCoins * t, math.floor(kind.coins * goal * t)), 0 end -- бонус цепочки: серебро; зелье — за самую первую цепочку и за каждый пройденный круг local function chainBonus(data) local b = Config.ChainBonus local c = data.chain local coins = math.floor(b.coins * tierOf(data) * (1 + Config.QuestTierGrowth * c.tier)) local potionId = nil if c.index == 1 and c.tier == 0 then potionId = b.firstPotion elseif c.index % #Config.QuestChains == 0 then potionId = b.roundPotions[(c.tier % #b.roundPotions) + 1] end return coins, 0, potionId and Potions.def(potionId) end local function sendQuests(player) local data = profiles[player] if not data then return end local chain = currentChain(data) local steps = {} for i, st in ipairs(chain.steps) do local goal = stepGoal(data, st) local coins, xp = stepReward(data, st, goal) steps[i] = { kind = st[1], goal = goal, coins = coins, xp = xp } end local bCoins, bXp, potion = chainBonus(data) local t = today() remote:FireClient(player, "Quests", { name = chain.name, round = data.chain.tier + 1, step = data.chain.step, progress = data.chain.progress, steps = steps, bonus = { coins = bCoins, xp = bXp, potion = potion and potion.name }, }, { available = data.daily.last < t, streak = data.daily.streak, nextStreak = (data.daily.last == t - 1) and (data.daily.streak % 7 + 1) or ((data.daily.last < t) and 1 or data.daily.streak), }) end local function updateStats(player) local data = profiles[player] if not data then return end local bagValue = 0 for _, item in ipairs(data.items) do bagValue += item.value end local owned, lv, bags, ps = {}, {}, {}, {} for id in pairs(data.rods) do table.insert(owned, id) table.insert(lv, id .. ":" .. rodLevel(data, id)) end for id in pairs(data.bags) do table.insert(bags, id) end for key in pairs(passes[player] or {}) do table.insert(ps, key) end player:SetAttribute("Coins", data.coins) player:SetAttribute("Level", data.level) player:SetAttribute("XP", data.xp) player:SetAttribute("XPNeed", Config.XPForLevel(data.level)) player:SetAttribute("Rod", data.rod) player:SetAttribute("RodLevel", rodLevel(data)) player:SetAttribute("RodLevels", table.concat(lv, ",")) player:SetAttribute("OwnedRods", table.concat(owned, ",")) player:SetAttribute("Bag", data.bag) player:SetAttribute("OwnedBags", table.concat(bags, ",")) player:SetAttribute("BagCount", #data.items) player:SetAttribute("BagCap", bagCapacity(player, data)) player:SetAttribute("BagValue", math.floor(bagValue * sellMult(player))) player:SetAttribute("Luck", math.floor(totalLuck(player, data) * 100 + 0.5)) -- зелья: сумка ("Focus:2,Trophy:1") и действующее (id, остаток попыток или секунд) local pDef, pAct = Potions.active(data) player:SetAttribute("PotionInv", Potions.encode(data)) player:SetAttribute("PotionActive", pDef and pDef.id or nil) player:SetAttribute("PotionLeft", pAct and math.max(0, math.floor(pAct.left)) or 0) player:SetAttribute("PotionKind", pDef and (pDef.charges and "charges" or "time") or nil) player:SetAttribute("BoostBonus", boostActive(data)) player:SetAttribute("BoostLeft", (pDef and not pDef.charges) and math.max(0, math.floor(pAct.left)) or 0) player:SetAttribute("MarketInbox", data.market and data.market.inbox and #data.market.inbox or 0) player:SetAttribute("TotalCaught", data.totalCaught) player:SetAttribute("CoinsEarned", data.coinsEarned) -- когда откроется следующая ежедневная награда (0 — уже доступна); по ней сундук в лобби прыгает только для тех, -- кому есть что забрать player:SetAttribute("DailyNextAt", data.daily.last >= today() and (data.daily.last + 1) * 86400 or 0) player:SetAttribute("RobuxSpent", data.robuxSpent) -- шаг обучения (линия-подсказка); у старых игроков без поля, уже ловивших рыбу, обучение пройдено player:SetAttribute("Tutorial", data.tutorial or (data.totalCaught > 0 and Config.TutorialDone or 0)) player:SetAttribute("Mastery", masteryCount(data)) player:SetAttribute("Passes", table.concat(ps, ",")) Guild.attrs(player, data) local ls = player:FindFirstChild("leaderstats") if ls then ls["Серебро"].Value = data.coins ls["Уровень"].Value = data.level ls["Улов"].Value = data.totalCaught end end -- опыт карьеры (единственный источник — ручная поимка; source — для телеметрии) local function addXp(player, data, amount, source) if amount <= 0 then return end Telemetry.xp(player, source or "Catch", amount) local levels = Progression.addXp(data, amount) for _, lvl in ipairs(levels) do Telemetry.level(player, lvl) end if #levels > 0 then notify(player, "⭐ Уровень " .. data.level .. "!", GOLD) feed("level", { name = player.DisplayName, userId = player.UserId, level = data.level }) for _, w in ipairs(Config.Worlds) do if not w.soon and table.find(levels, w.level) then notify(player, "🌍 Открыт: " .. w.icon .. " " .. w.name, w.color) end end if table.find(levels, Config.Market.minLevel) then notify(player, "🏪 Открыт рынок игроков: продавай ценную рыбу другим рыбакам", GOLD) end end end Guild.init({ profiles = profiles, notify = notify, updateStats = updateStats, addXp = addXp, sendInventory = sendInventory, bagCapacity = bagCapacity, isNight = isNight, weather = weather, remote = remote, addCoins = addCoins, spendCoins = spendCoins, tierOf = tierOf, }) -- зелье-награда: в сумку зелий (пить — когда игрок сам решит) local function givePotion(player, data, def) if def and Potions.add(data, def.id, 1) then Telemetry.event(player, "PotionGranted", 1, { def.id }) return true end return false end ---------------------------------------------------------------- задания: прогресс цепочки -- у старых сохранений вместо цепочки были три случайных задания local function ensureChain(data) if type(data.chain) ~= "table" then data.chain = { index = 1, step = 1, progress = 0, tier = 0 } end data.quests = nil end -- absolute = true: amount — текущее значение (серия), а не прибавка local function questProgress(player, kind, amount, absolute) local data = profiles[player] if not data then return end local chain, step = currentChain(data) if step[1] ~= kind then return end local c = data.chain c.progress = absolute and math.max(c.progress, amount) or c.progress + amount local goal = stepGoal(data, step) if c.progress >= goal then -- награда сразу, следующий шаг тоже сразу local coins = stepReward(data, step, goal) addCoins(player, data, coins, "Quest") remote:FireClient(player, "QuestDone", kind, goal, coins, 0) c.step += 1 c.progress = 0 if c.step > #chain.steps then local bCoins, _, potion = chainBonus(data) addCoins(player, data, bCoins, "Chain") if potion then givePotion(player, data, potion) end remote:FireClient(player, "ChainDone", chain.name, bCoins, 0, potion and (potion.icon .. " " .. potion.name .. " — в сумку зелий")) c.index += 1 c.step = 1 if (c.index - 1) % #Config.QuestChains == 0 then c.tier += 1 end end updateStats(player) end sendQuests(player) end local function claimDaily(player) local data = profiles[player] if not data then return end local t = today() if data.daily.last >= t then notify(player, "🎁 Приходи завтра", Color3.fromRGB(255, 200, 120)) return end local streak = (data.daily.last == t - 1) and (data.daily.streak % 7 + 1) or 1 local r = Config.DailyRewards[streak] local coins = addCoins(player, data, r.coins * tierOf(data), "Daily") local extra = "" if r.potion then local p = Potions.def(r.potion) if givePotion(player, data, p) then extra = " + " .. p.icon .. " " .. p.name end end data.daily = { last = t, streak = streak } if streak == 7 then data.pearls += Config.Pearls.daily7 extra ..= (" + %d 🦪"):format(Config.Pearls.daily7) end updateStats(player) sendQuests(player) notify(player, ("🎁 День %d: +%d ⚪%s"):format(streak, coins, extra), GOLD) end ---------------------------------------------------------------- коллекция local function claimCollection(player, worldId, rarity) local data = profiles[player] local world = data and Config.Find(Config.Worlds, worldId) local zone = world and Config.Zones[worldId] if not zone or type(rarity) ~= "string" then return end local key = worldId .. ":" .. rarity if data.claimed[key] then return end for _, f in ipairs(zone.fish) do if (rarity == "Master" or f.rarity == rarity) and not data.discovered[f.id] then notify(player, "Сначала поймай всех", RED) return end end -- коллекция — исследование: серебро (× tier мира) и мастерство, без опыта карьеры if rarity == "Master" then data.claimed[key] = true local coins = addCoins(player, data, Config.MasteryCoins * (world.tier or 1), "Collection") notify(player, ("🏆 «%s» собран! +%d ⚪ и +%d%% удачи навсегда"):format(world.name, coins, Config.MasteryLuck * 100), GOLD) else local r = Config.CollectionRewards[rarity] if not r then return end data.claimed[key] = true local coins = addCoins(player, data, r.coins * (world.tier or 1), "Collection") notify(player, ("📖 +%d ⚪"):format(coins), GREEN) end updateStats(player) sendInventory(player) end ---------------------------------------------------------------- удочка, сумка, VIP на персонаже local REST_ANGLE = 42 -- удочка в покое: рукоять под ~42° вверх-вперёд, кончик провисает до ~30° local function gripCF(angle) return (CFrame.Angles(math.rad(angle), 0, 0) * CFrame.new(0, 0, -0.3)):Inverse() end local function tweenGrip(tool, angle, t) if not tool or not tool.Parent then return nil end local tw = TweenService:Create(tool, TweenInfo.new(t, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), { Grip = gripCF(angle) }) tw:Play() return tw end local function gripSequence(tool, steps) task.spawn(function() for _, s in ipairs(steps) do local tw = tweenGrip(tool, s[1], s[2]) if not tw then return end tw.Completed:Wait() end end) end local function findRodTool(player) for _, container in ipairs({ player.Character, player:FindFirstChild("Backpack") }) do if container then for _, child in ipairs(container:GetChildren()) do if child:IsA("Tool") and child:GetAttribute("IsRod") then return child end end end end return nil end local function giveRodTool(player) local data = profiles[player] local backpack = player:FindFirstChild("Backpack") if not data or not backpack then return end local old = findRodTool(player) local wasEquipped = old ~= nil and old.Parent == player.Character if old then old:Destroy() end local rod = Config.Find(Config.Rods, data.rod) or Config.Rods[1] local lvl = rodLevel(data) local model = Models.buildRod(rod.id, lvl, false) local tool = Instance.new("Tool") tool.Name = rod.name .. (lvl > 0 and (" +" .. lvl) or "") tool.ToolTip = "Кликни у воды, чтобы закинуть" tool.TextureId = rod.icon or "" tool.CanBeDropped = false tool.Grip = gripCF(REST_ANGLE) tool:SetAttribute("IsRod", true) for _, child in ipairs(model:GetChildren()) do child.Parent = tool end model:Destroy() tool.Parent = backpack if wasEquipped then local hum = player.Character and player.Character:FindFirstChildOfClass("Humanoid") if hum then hum:EquipTool(tool) end end end local function attachBag(player) local data = profiles[player] local char = player.Character if not data or not char then return end local old = char:FindFirstChild("BackBag") if old then old:Destroy() end local torso = char:FindFirstChild("UpperTorso") or char:FindFirstChild("Torso") if not torso then return end local bag = Models.buildBag(data.bag, false) local offset = CFrame.new(0, 0.1, torso.Size.Z / 2) bag:PivotTo(torso.CFrame * offset) local w = Instance.new("Weld") w.Part0 = torso w.Part1 = bag.PrimaryPart w.C0 = offset w.Parent = bag.PrimaryPart bag.Parent = char end local function vipTag(player) local head = player.Character and player.Character:FindFirstChild("Head") if not head or not hasPass(player, "VIP") or head:FindFirstChild("VipTag") then return end local bb = Instance.new("BillboardGui") bb.Name = "VipTag" bb.Size = UDim2.fromOffset(120, 30) bb.StudsOffset = Vector3.new(0, 2.6, 0) bb.MaxDistance = 80 bb.Parent = head local t = Instance.new("TextLabel") t.Size = UDim2.fromScale(1, 1) t.BackgroundTransparency = 1 t.Font = Enum.Font.FredokaOne t.TextScaled = true t.TextColor3 = Color3.fromRGB(255, 210, 60) t.TextStrokeTransparency = 0.2 t.Text = "👑 VIP" t.Parent = bb end ---------------------------------------------------------------- эффекты local function playSound(parent, id, volume) local snd = Instance.new("Sound") snd.SoundId = id snd.Volume = volume or 0.6 snd.Parent = parent snd:Play() Debris:AddItem(snd, 3) end local function splash(part, count) local att = Instance.new("Attachment") att.Parent = part local pe = Instance.new("ParticleEmitter") pe.Color = ColorSequence.new(Color3.fromRGB(220, 240, 255)) pe.Transparency = NumberSequence.new(0.2, 1) pe.Size = NumberSequence.new(0.4, 0.1) pe.Lifetime = NumberRange.new(0.4, 0.7) pe.Speed = NumberRange.new(6, 10) pe.SpreadAngle = Vector2.new(40, 40) pe.Acceleration = Vector3.new(0, -35, 0) pe.Enabled = false pe.Parent = att pe:Emit(count or 20) Debris:AddItem(att, 2) end -- рыба вылетает из воды, летит к игроку и показывается над головой -- шлейф за летящим предметом — эффект быстрого движения (ширина — расстояние между точками крепления) local TRAIL_COLOR = Color3.fromRGB(215, 245, 255) local function addTrail(part, width) local a0 = Instance.new("Attachment") a0.Position = Vector3.new(0, width / 2, 0) a0.Parent = part local a1 = Instance.new("Attachment") a1.Position = Vector3.new(0, -width / 2, 0) a1.Parent = part local trail = Instance.new("Trail") trail.Attachment0, trail.Attachment1 = a0, a1 trail.FaceCamera = true trail.Lifetime = 0.35 trail.MinLength = 0.05 trail.LightEmission = 0.7 trail.Color = ColorSequence.new(TRAIL_COLOR) trail.Transparency = NumberSequence.new({ NumberSequenceKeypoint.new(0, 0.1), NumberSequenceKeypoint.new(1, 1) }) trail.WidthScale = NumberSequence.new({ NumberSequenceKeypoint.new(0, 1), NumberSequenceKeypoint.new(1, 0) }) trail.Parent = part return trail end local function showFishFlight(player, fish, fromPos) local head = player.Character and player.Character:FindFirstChild("Head") if not head then return end local model = Models.buildFish(fish.id, fish.mutation, 0.9, true) model:PivotTo(CFrame.new(fromPos)) model.Parent = workspace -- шлейф на отдельной невидимой детали: рыба крутится, а шлейф должен оставаться ровным local carrier = Instance.new("Part") carrier.Anchored, carrier.CanCollide, carrier.CanQuery, carrier.CanTouch = true, false, false, false carrier.Transparency = 1 carrier.Size = Vector3.new(0.2, 0.2, 0.2) carrier.CFrame = CFrame.new(fromPos) carrier.Parent = model local trail = addTrail(carrier, 1.8) task.spawn(function() local t0, dur = os.clock(), 0.55 while head.Parent do local a = math.min(1, (os.clock() - t0) / dur) local target = head.Position + Vector3.new(0, 2.8, 0) local p = fromPos:Lerp(target, a) + Vector3.new(0, math.sin(a * math.pi) * 8, 0) model:PivotTo(CFrame.new(p) * CFrame.Angles(0, 0, a * math.pi * 2)) carrier.CFrame = CFrame.new(p) if a >= 1 then break end RunService.Heartbeat:Wait() end trail.Enabled = false local t1 = os.clock() while head.Parent and os.clock() - t1 < 1.8 do model:PivotTo(CFrame.new(head.Position + Vector3.new(0, 2.8, 0)) * CFrame.Angles(0, os.clock() * 3, math.rad(-15))) RunService.Heartbeat:Wait() end model:Destroy() end) end ---------------------------------------------------------------- рыбалка local fishing = {} -- серия улова (на время игры, не сохраняется) local combo, comboUntil = {}, {} local function setCombo(player, n) combo[player] = n comboUntil[player] = n > 0 and os.time() + Config.Combo.timeout or nil player:SetAttribute("Combo", n) player:SetAttribute("ComboEnds", n > 0 and workspace:GetServerTimeNow() + Config.Combo.timeout or nil) end local function breakCombo(player) if (combo[player] or 0) >= 2 then remote:FireClient(player, "ComboLost", combo[player]) end setCombo(player, 0) end -- босс озера: { world, def, hp, max, dmg = { [player] = урон } } local boss = nil local function bossHit(player, world, dmg) if not boss or boss.hp <= 0 or not world or world.id ~= boss.world.id then return end boss.hp = math.max(0, boss.hp - dmg) boss.dmg[player] = (boss.dmg[player] or 0) + dmg workspace:SetAttribute("BossHP", boss.hp) remote:FireClient(player, "BossHit", dmg) questProgress(player, "boss", dmg) end -- ищем воду по карте мира из FishConfig (не зависит от террейна) в сторону центра ближайшего озера: -- сначала на дальности, которую задала сила заброса, потом всё дальше от неё local function findWater(hrp, world, power) local look = Config.CastDirection(world, hrp.Position) if not look then look = hrp.CFrame.LookVector * Vector3.new(1, 0, 1) look = look.Magnitude > 0.01 and look.Unit or Vector3.new(0, 0, -1) end local want = Config.CastMinDist + (Config.CastMaxDist - Config.CastMinDist) * power for off = 0, 26, 2 do for _, d in ipairs({ want - off, want + off }) do if d >= 4 and d <= Config.CastMaxDist + 2 then local p = hrp.Position + look * d if Config.IsWater(world, p) then return Vector3.new(p.X, world.waterY or 0, p.Z), d end end end end return nil end -- вытягивание пустого поплавка: быстро летит к кончику удочки со шлейфом и исчезает local function reelBobber(bobber, tool) local root = bobber and bobber.PrimaryPart local tip = tool and tool:FindFirstChild("Handle") and tool.Handle:FindFirstChild("Tip") if not root or not tip then if bobber then bobber:Destroy() end return end local trail = bobber:FindFirstChildWhichIsA("Trail", true) if trail then trail.Enabled = true else addTrail(root, 1.2) end local from = root.Position task.spawn(function() local t0, dur = os.clock(), 0.3 while bobber.Parent and tip.Parent do local a = math.min(1, (os.clock() - t0) / dur) bobber:PivotTo(CFrame.new(from:Lerp(tip.WorldPosition, a) + Vector3.new(0, math.sin(a * math.pi) * 2.5, 0))) if a >= 1 then break end RunService.Heartbeat:Wait() end bobber:Destroy() end) end local function stopFishing(player, tellClient) local s = fishing[player] if not s then return end fishing[player] = nil if s.tween then s.tween:Cancel() end if s.bobber then if s.stage == "casting" then s.bobber:Destroy() -- ещё летит: его двигает flyBobber else reelBobber(s.bobber, s.tool) end end if s.tool then tweenGrip(s.tool, REST_ANGLE, 0.3) end if tellClient then remote:FireClient(player, "Cancel") end end -- mods: { bait = наживка из Config.Baits, maxRank = потолок редкости (автоловля), potion = Potions.effect } -- Удача смягчается к потолку (Config.EffectiveLuck): лучшее снаряжение даёт больше дорогой рыбы, -- но мифическая не становится обычной, а мутации не чаще × Economy.mutationCap local function rollFish(player, data, worldId, luckMult, mods) local zone = Config.Zones[worldId] if not zone then return nil end mods = mods or {} local bait = mods.bait local pot = mods.potion or {} local base = totalLuck(player, data) + (bait and bait.luck or 0) if bait and bait.nightLuck and isNight() then base += bait.nightLuck - Config.DayNight.nightLuck -- светлячок: ночью +30% вместо обычных +10% end local luck = base * (luckMult or 1) local beff = Config.EffectiveLuck(luck) local weights, total = {}, 0 for i, f in ipairs(zone.fish) do local r = Config.Rarities[f.rarity] local w = Config.RarityWeight(f.rarity, beff) if bait and bait.rareWeight and r.rank >= 3 then w *= bait.rareWeight end if pot.newSpecies and not data.discovered[f.id] then w *= pot.newSpecies -- зелье исследователя: ещё не пойманные виды end if mods.maxRank and r.rank > mods.maxRank then w = 0 end weights[i] = w total += w end local roll = rng:NextNumber() * total local chosen = zone.fish[1] for i, f in ipairs(zone.fish) do roll -= weights[i] if roll <= 0 then chosen = f break end end local mutation = nil local mm = Config.MutationMult(beff, ev("mutation", 1) * (weather().mutation or 1) * (bait and bait.mutation or 1) * (pot.mutation or 1)) for _, m in ipairs(Config.Mutations) do if rng:NextNumber() < m.chance * mm then mutation = m break end end local wf = rng:NextNumber() ^ (pot.weightCurve or 2.2) local weight = chosen.minW + (chosen.maxW - chosen.minW) * wf return { id = chosen.id, name = chosen.name, rarity = chosen.rarity, weight = math.floor(weight * 100) / 100, value = math.floor(chosen.price * (0.75 + 0.9 * wf) * (mutation and mutation.mult or 1) + 0.5), mutation = mutation and mutation.id or nil, world = worldId, } end local function flyBobber(s, tool, target, dur, arc) local tip = tool:FindFirstChild("Handle") and tool.Handle:FindFirstChild("Tip") local start = tip and tip.WorldPosition or (target + Vector3.new(0, 6, 0)) local bobber = Models.buildBobber() bobber:PivotTo(CFrame.new(start)) bobber.Parent = workspace s.bobber = bobber local trail = addTrail(bobber.PrimaryPart, 1.2) if tip then local a1 = Instance.new("Attachment") a1.Position = Vector3.new(0, 0.9, 0) a1.Parent = bobber.PrimaryPart local line = Instance.new("Beam") line.Attachment0 = tip line.Attachment1 = a1 line.Width0 = 0.035 line.Width1 = 0.035 line.FaceCamera = true line.Color = ColorSequence.new(Color3.fromRGB(245, 245, 245)) line.Parent = bobber end local t0 = os.clock() while bobber.Parent do local a = math.min(1, (os.clock() - t0) / dur) bobber:PivotTo(CFrame.new(start:Lerp(target, a) + Vector3.new(0, math.sin(a * math.pi) * arc, 0))) if a >= 1 then break end RunService.Heartbeat:Wait() end trail.Enabled = false -- на воде поплавок качается, шлейф уже не нужен if bobber.Parent then splash(bobber.PrimaryPart, 18) playSound(bobber.PrimaryPart, SPLASH_SOUND, 0.5) end end local autoFishing = {} -- [player] = токен работающей автоловли local setAutoFish, grantFish -- объявлены ниже local function onCast(player, power) power = math.clamp(tonumber(power) or 0.6, 0, 1) local data = profiles[player] if not data then return end if autoFishing[player] then -- клик удочкой во время автоловли — выключить её setAutoFish(player, false) remote:FireClient(player, "CastFail") return end if fishing[player] then stopFishing(player, true) return end local char = player.Character local hrp = char and char:FindFirstChild("HumanoidRootPart") local tool = char and char:FindFirstChildOfClass("Tool") if not hrp or not tool or not tool:GetAttribute("IsRod") then remote:FireClient(player, "CastFail") return end local world = Config.WorldAt(hrp.Position) local can = Config.CanCastFrom(world, hrp.Position) if can ~= true then remote:FireClient(player, "CastFail") notify(player, can, Color3.fromRGB(255, 200, 120)) return end local target, dist = findWater(hrp, world, power) if not target then remote:FireClient(player, "CastFail") notify(player, "🌊 Подойди к воде", Color3.fromRGB(255, 200, 120)) return end if #data.items >= bagCapacity(player, data) then remote:FireClient(player, "CastFail") notify(player, "🎒 Сумка полна!", RED) return end local stats = Config.RodStats(data.rod, rodLevel(data)) local perfect = power >= Config.CastPerfect[1] and power <= Config.CastPerfect[2] local bait = Guild.useBait(player, data) -- 1 штука наживки на заброс -- зелье: эффект берём на момент заброса, попытку списываем при поклёвке (ниже) local potion = Potions.effect(data) local fish = rollFish(player, data, world.id, perfect and Config.CastPerfectLuck or 1, { bait = bait, potion = potion }) if not fish then remote:FireClient(player, "CastFail") return end local s = { stage = "casting", fish = fish, tool = tool, perfect = perfect, potion = potion } fishing[player] = s -- замах игрок уже сделал, пока держал кнопку (у себя на клиенте); здесь только бросок вперёд local throw = { windup = 0.15, flight = 0.35 + dist * 0.018, arc = 2 + dist * 0.3, perfect = perfect } local splashAt = target + Vector3.new(0, 0.15, 0) remote:FireClient(player, "Cast", splashAt, throw) -- клиенту для камеры task.spawn(function() local tw = tweenGrip(tool, 8, throw.windup) if tw then tw.Completed:Wait() end if fishing[player] ~= s then return end flyBobber(s, tool, splashAt, throw.flight, throw.arc) tweenGrip(tool, REST_ANGLE - 5, 0.4) if fishing[player] ~= s then if s.bobber then s.bobber:Destroy() end return end s.stage = "waiting" -- все ускорения клёва вместе — не больше чем на 25% (Economy.waitFloor), и не короче minBite секунд local waitTime = math.max(E.minBite, rng:NextNumber(Config.BiteTimeMin, Config.BiteTimeMax) * Config.WaitMult(stats.speed * ev("speed", 1) * (weather().speed or 1) * (bait and bait.speed or 1) * (potion.speed or 1))) task.wait(waitTime) if fishing[player] ~= s then return end s.stage = "bite" s.biteAt = os.clock() -- поклёвка: попытка зелья засчитана (дальше — поймал, сорвалась или ушла; отмена уже не спасает заряд) if potion.id and Potions.consumeAttempt(data, potion.id) then updateStats(player) end if s.bobber and s.bobber.PrimaryPart then local root = s.bobber.PrimaryPart splash(root, 25) playSound(root, SPLASH_SOUND, 0.35) s.tween = TweenService:Create(root, TweenInfo.new(0.18, Enum.EasingStyle.Quad, Enum.EasingDirection.Out, -1, true), { CFrame = root.CFrame - Vector3.new(0, 0.55, 0), }) s.tween:Play() end -- удочка дёргается, пока идёт вываживание task.spawn(function() local up = true while fishing[player] == s and s.stage == "bite" do tweenGrip(tool, up and 38 or 18, 0.12) up = not up task.wait(0.13) end end) local rank = Config.Rarities[fish.rarity].rank s.hits = Config.HitsNeeded(rank) remote:FireClient(player, "Bite", { speed = 0.55 + 0.22 * (rank - 1), zoneWidth = math.max(0.07, stats.zone + (potion.zone or 0) - 0.02 * (rank - 1)), hits = Config.HitsNeeded(rank), misses = Config.MaxMisses, timeout = Config.BiteTimeout, }) task.wait(Config.BiteTimeout + 0.5) if fishing[player] == s and s.stage == "bite" then stopFishing(player, false) remote:FireClient(player, "Escaped") notify(player, "🐟 Рыба ушла", RED) breakCombo(player) end end) end local function onCatch(player, success, misses) local s = fishing[player] local data = profiles[player] if not s or not data or s.stage ~= "bite" then return end local fromPos = s.bobber and s.bobber.PrimaryPart and s.bobber.PrimaryPart.Position s.stage = "done" local tool = s.tool fishing[player] = nil if s.tween then s.tween:Cancel() end -- подсечка быстрее, чем физически возможно пройти мини-игру, не засчитывается local reel = os.clock() - s.biteAt local failed = success ~= true or reel > Config.BiteTimeout + 1 or reel < E.reelPerHit * (s.hits or 1) if failed then reelBobber(s.bobber, tool) elseif s.bobber then s.bobber:Destroy() -- вместо поплавка к игроку летит рыба end if failed then gripSequence(tool, { { REST_ANGLE, 0.3 } }) remote:FireClient(player, "Escaped") notify(player, "🐟 Сорвалась!", RED) breakCombo(player) return end gripSequence(tool, { { 85, 0.15 }, { REST_ANGLE, 0.45 } }) grantFish(player, data, s.fish, { perfect = s.perfect, misses = misses, fromPos = fromPos }) end -- рыба поймана (руками или автоловлей): в сумку, опыт, коллекция, задания, гильдия, босс. -- ctx: { perfect, misses, fromPos, auto }; у автоловли нет серии и бонусов за точность grantFish = function(player, data, fish, ctx) local streak = combo[player] or 0 local comboBonus = 0 if not ctx.auto then -- серия: каждая рыба подряд чуть дороже (опыт карьеры не меняется) comboBonus = math.min(Config.Combo.max, Config.Combo.step * streak) setCombo(player, streak + 1) end -- надбавки к цене складываются и ограничены: серия + отдых ≤ valueBonusCap local restBonus = (data.rest or 0) > 0 and E.restSilver or 0 local valueMult = 1 + math.min(E.valueBonusCap, comboBonus + restBonus) if ctx.auto then valueMult = E.autoValue end fish.value = math.max(1, math.floor(fish.value * valueMult + 0.5)) -- опыт карьеры: фиксированный за ручную поимку в этом мире; автоловля — Economy.autoXP fish.xp = Progression.catchXP(fish.world, { auto = ctx.auto }) local item = { uid = data.nextUid, id = fish.id, name = fish.name, rarity = fish.rarity, weight = fish.weight, value = fish.value, mutation = fish.mutation, } Progression.stamp(item, player.UserId, player.DisplayName, fish.world, os.time()) table.insert(data.items, item) data.nextUid += 1 data.totalCaught += 1 local rec = data.discovered[fish.id] local isNew, isRecord = rec == nil, false if not rec then rec = { count = 0, best = 0 } data.discovered[fish.id] = rec end rec.count += 1 if fish.weight > rec.best then isRecord = not isNew rec.best = fish.weight end -- новый вид и рекорд радуют серебром, коллекцией и карточкой, а не скачком уровня addXp(player, data, fish.xp, ctx.auto and "Auto" or "Catch") updateStats(player) sendInventory(player) if ctx.fromPos then showFishFlight(player, fish, ctx.fromPos) end remote:FireClient(player, "Caught", fish, { new = isNew, record = isRecord, combo = 1 + comboBonus, rest = restBonus > 0, streak = ctx.auto and 0 or streak + 1, auto = ctx.auto }) do local h = player.Character and player.Character:FindFirstChild("HumanoidRootPart") feedCatch(player, fish, h and Config.WorldAt(h.Position)) end local rank = Config.Rarities[fish.rarity].rank -- задания засчитывают только ручную ловлю (автоловля — дополнительный доход, не прогресс) if not ctx.auto then questProgress(player, "catch", 1) if rank >= 2 then questProgress(player, "uncommon", 1) end if rank >= 3 then questProgress(player, "rare", 1) end end if not ctx.auto then if ctx.misses == 0 then questProgress(player, "perfect", 1) end if ctx.perfect then questProgress(player, "perfectCast", 1) end questProgress(player, "combo", streak + 1, true) end Guild.onCatch(player, data, fish, { weather = workspace:GetAttribute("Weather"), night = isNight(), perfect = ctx.perfect and not ctx.auto, streak = (not ctx.auto) and streak + 1 or 0, }) local hrp = player.Character and player.Character:FindFirstChild("HumanoidRootPart") bossHit(player, hrp and Config.WorldAt(hrp.Position), rank + (ctx.misses == 0 and 1 or 0)) end ---------------------------------------------------------------- автоловля (с ранга E) -- сервер сам забрасывает и вытаскивает: удача ×0.6, не выше «Редкой», без серии и бонуса заброса, -- каждая поимка на 50% дольше. Стоп — полная сумка, отошёл от места, сменил мир, убрал удочку local function autoFishLoop(player, token) local A = Config.AutoFish local home = nil -- где включили: отошёл дальше 10 studs или сменил мир — стоп local function stop(reason) if autoFishing[player] == token then setAutoFish(player, false, reason) end end while autoFishing[player] == token do local data = profiles[player] local char = player.Character local hrp = char and char:FindFirstChild("HumanoidRootPart") local tool = char and char:FindFirstChildOfClass("Tool") if not data or not hrp then return stop(nil) end if not tool or not tool:GetAttribute("IsRod") then return stop("🎣 Автоловля: возьми удочку в руки") end local world = Config.WorldAt(hrp.Position) if not world or Config.CanCastFrom(world, hrp.Position) ~= true then return stop("🌊 Автоловля: встань у воды") end home = home or { pos = hrp.Position, world = world.id } if world.id ~= home.world or (hrp.Position - home.pos).Magnitude > 10 then return stop("🎣 Автоловля остановлена: ты отошёл") end if #data.items >= bagCapacity(player, data) then return stop("🎒 Сумка полна — автоловля остановлена") end local target, dist = findWater(hrp, world, 0.6) if not target then return stop("🌊 Автоловля: встань у воды") end if fishing[player] then task.wait(0.5) continue end local cycleStart = os.clock() local bait = Guild.useBait(player, data) -- зелья автоловля не использует и не тратит local fish = rollFish(player, data, world.id, A.luck, { bait = bait, maxRank = (not Guild.rank(data).autoNoCap) and A.maxRarity or nil }) local s = { stage = "casting", fish = fish, tool = tool, auto = true } fishing[player] = s local splashAt = target + Vector3.new(0, 0.15, 0) local tw = tweenGrip(tool, 8, 0.15) if tw then tw.Completed:Wait() end if fishing[player] == s then flyBobber(s, tool, splashAt, 0.35 + dist * 0.018, 2 + dist * 0.3) tweenGrip(tool, REST_ANGLE - 5, 0.4) end if fishing[player] ~= s then if s.bobber then s.bobber:Destroy() end continue end s.stage = "waiting" local stats = Config.RodStats(data.rod, rodLevel(data)) local waitTime = math.max(E.minBite, rng:NextNumber(Config.BiteTimeMin, Config.BiteTimeMax) * Config.WaitMult(stats.speed * ev("speed", 1) * (weather().speed or 1) * (bait and bait.speed or 1))) * A.slower local t0, bit = os.clock(), false while fishing[player] == s and autoFishing[player] == token and os.clock() - t0 < waitTime + A.reel do local h = player.Character and player.Character:FindFirstChild("HumanoidRootPart") if not h or (h.Position - home.pos).Magnitude > 10 then break end if not bit and os.clock() - t0 >= waitTime then -- клюёт: всплеск и удочка дёргается до конца «вываживания» bit = true if s.bobber and s.bobber.PrimaryPart then splash(s.bobber.PrimaryPart, 25) playSound(s.bobber.PrimaryPart, SPLASH_SOUND, 0.35) end end if bit then tweenGrip(tool, (math.floor(os.clock() * 8) % 2 == 0) and 38 or 18, 0.12) end task.wait(0.13) end if fishing[player] ~= s or autoFishing[player] ~= token or not bit or os.clock() - t0 < waitTime + A.reel - 0.05 then if fishing[player] == s then stopFishing(player, false) end continue -- наверху цикла проверим, почему прервались (отошёл, выключил) end fishing[player] = nil local fromPos = s.bobber and s.bobber.PrimaryPart and s.bobber.PrimaryPart.Position if s.bobber then s.bobber:Destroy() end gripSequence(tool, { { 85, 0.15 }, { REST_ANGLE, 0.45 } }) grantFish(player, data, fish, { auto = true, fromPos = fromPos }) -- автоловля не быстрее одной рыбы за Economy.autoMinCycle секунд: не обгоняет ручную ловлю task.wait(math.max(1.2, E.autoMinCycle - (os.clock() - cycleStart))) end end setAutoFish = function(player, on, reason) local data = profiles[player] if on then if not data then return end if not Guild.rank(data).auto then notify(player, "🔒 Автоловля — с ранга гильдии E", RED) player:SetAttribute("AutoFish", false) return end if autoFishing[player] then return end if fishing[player] then stopFishing(player, true) end local token = {} autoFishing[player] = token player:SetAttribute("AutoFish", true) notify(player, "🎣 Автоловля включена", GREEN) task.spawn(autoFishLoop, player, token) else player:SetAttribute("AutoFish", false) if not autoFishing[player] then return end autoFishing[player] = nil local s = fishing[player] if s and s.auto then stopFishing(player, false) end notify(player, reason or "🎣 Автоловля выключена", Color3.fromRGB(255, 200, 120)) end end ---------------------------------------------------------------- скупка local sellPoints = nil local function nearSeller(player) local hrp = player.Character and player.Character:FindFirstChild("HumanoidRootPart") if not hrp then return false end if not sellPoints then sellPoints = {} local map = workspace:FindFirstChild("FishingMap") if map then for _, d in ipairs(map:GetDescendants()) do if d:IsA("ProximityPrompt") and d:GetAttribute("Action") == "Sell" then table.insert(sellPoints, d.Parent) end end end end for _, p in ipairs(sellPoints) do if (p.Position - hrp.Position).Magnitude < 28 then return true end end return false end local function sellItems(player, filterUid) local data = profiles[player] if not data then return end local mult = sellMult(player) local total, count, keep = 0, 0, {} for _, item in ipairs(data.items) do if filterUid == nil or item.uid == filterUid then -- купленная на рынке рыба — по базовой цене, без бонусов пропусков и ярмарки (нет перепродажи с наваром) total += item.bought and math.floor(item.value) or math.floor(item.value * mult) count += 1 else table.insert(keep, item) end end if count == 0 then if filterUid == nil then notify(player, "🎒 Сумка пуста", Color3.fromRGB(255, 200, 120)) end return end data.items = keep addCoins(player, data, total, "Sell") data.coinsEarned += total updateStats(player) sendInventory(player) remote:FireClient(player, "Sold", total, count) questProgress(player, "sell", count) questProgress(player, "earn", total) end ---------------------------------------------------------------- магазин local function buy(player, kind, id) local data = profiles[player] if not data or type(id) ~= "string" then return end if kind == "Upgrade" then local rod = Config.Find(Config.Rods, id) if not rod or not data.rods[id] then return end local lvl = rodLevel(data, id) if lvl >= Config.RodUpgrade.maxLevel then notify(player, "★★★★★ Максимум", GOLD) return end local cost = Guild.price(data, Config.UpgradeCost(rod, lvl)) -- скидка ранга гильдии if not spendCoins(player, data, cost, "Upgrade", id) then notify(player, "Нужно " .. cost .. " ⚪", RED) return end data.rodLevels[id] = lvl + 1 if data.rod == id then stopFishing(player, true) giveRodTool(player) end updateStats(player) notify(player, ("✨ %s улучшена до +%d!"):format(rod.name, lvl + 1), GOLD) questProgress(player, "buy", 1) return end if kind == "Potion" then -- покупка — в сумку зелий; выпить отдельно (DrinkPotion) local potion = Potions.def(id) if not potion or not potion.price or potion.paid or potion.legacy then return end if potion.level and data.level < potion.level then notify(player, "🔒 Нужен ур. " .. potion.level, RED) return end local price = Guild.price(data, potion.price) if not spendCoins(player, data, price, "Potion", id) then notify(player, "Нужно " .. price .. " ⚪", RED) return end Potions.add(data, id, 1) Telemetry.event(player, "PotionBought", 1, { id }) updateStats(player) notify(player, ("%s %s — в сумке зелий"):format(potion.icon, potion.name), GREEN) questProgress(player, "buy", 1) return end local list, owned if kind == "Rod" then list, owned = Config.Rods, data.rods elseif kind == "Bag" then list, owned = Config.Bags, data.bags else return end local item = Config.Find(list, id) if not item then return end local bought = false if not owned[id] then if data.level < item.level then notify(player, "🔒 Нужен ур. " .. item.level, RED) return end local price = Guild.price(data, item.price) if not spendCoins(player, data, price, kind, id) then notify(player, "Нужно " .. price .. " ⚪", RED) return end owned[id] = true bought = true notify(player, "✅ " .. item.name, GREEN) end if kind == "Rod" then data.rod = id stopFishing(player, true) giveRodTool(player) else data.bag = id attachBag(player) end updateStats(player) if bought then questProgress(player, "buy", 1) end end ---------------------------------------------------------------- зелья: выпить -- confirm = true — игрок подтвердил замену действующего зелья (его остаток пропадает) local function drinkPotion(player, id, confirm) local data = profiles[player] if not data then return end local ok, code, info = Potions.activate(data, id, confirm == true) local def = Potions.def(id) if ok then Telemetry.event(player, "PotionActivated", 1, { id, code }) local left = def.charges and (def.charges .. " попыток") or (math.floor((def.duration or 0) / 60) .. " мин игры") if code == "extended" then notify(player, ("%s %s продлено"):format(def.icon, def.name), GREEN) elseif code == "replaced" and info then local lost = Potions.def(info.lostId) notify(player, ("%s %s: %s. Прежнее зелье (%s) заменено"):format(def.icon, def.name, left, lost and lost.name or "?"), GOLD) else notify(player, ("%s %s: %s"):format(def.icon, def.name, left), GREEN) end updateStats(player) elseif code == "needConfirm" then -- клиент покажет окно подтверждения с остатком текущего зелья remote:FireClient(player, "PotionConfirm", id, info.activeId, info.left) elseif code == "full" then notify(player, "Больше этого зелья сейчас не выпить", RED) elseif code == "none" then notify(player, "Такого зелья нет в сумке", RED) end end ---------------------------------------------------------------- рынок игроков local marketLedger = nil if marketStore then marketLedger = Market.dataStoreLedger(marketStore) elseif RunService:IsStudio() and Config.Market.studioFakeLedger then marketLedger = Market.memoryLedger() -- в Studio без API: сделки в памяти (профили всё равно не сохраняются) end Market.init({ profiles = profiles, ledger = marketLedger, save = function(p) if not playerStore or not loadedOk[p] then -- без хранилища (Studio) сохранять нечего: считаем шаг выполненным return profiles[p] ~= nil and (not playerStore) end return saveData(p) end, notify = notify, changed = function(p) updateStats(p) sendInventory(p) end, send = function(p, payload) remote:FireClient(p, "Market", payload) end, bagCapacity = bagCapacity, telemetry = Telemetry, enabled = function() -- живой сервер без DataStore рынок не открывает (нечем гарантировать сделки) return marketStore ~= nil or RunService:IsStudio() end, }) ---------------------------------------------------------------- телепорт local TELEPORT_FADE = 0.3 -- сколько клиент затемняет экран перед переносом local teleporting = {} Players.PlayerRemoving:Connect(function(p) teleporting[p] = nil end) local function teleportTo(player, worldId) local data = profiles[player] local char = player.Character if not data or not char or type(worldId) ~= "string" then return end local markerName if worldId == "Lobby" then markerName = "LobbySpawn" else local world = Config.Find(Config.Worlds, worldId) if not world then return end if world.soon then notify(player, world.icon .. " " .. world.name .. " — скоро!", world.color) return end if data.level < world.level then notify(player, ("🔒 %s: ур. %d"):format(world.name, world.level), RED) return end local okRank, why = Guild.canEnter(data, world.id) if not okRank then notify(player, why, RED) return end markerName = world.id .. "Spawn" end local map = workspace:FindFirstChild("FishingMap") local m = map and map:FindFirstChild(markerName, true) -- маркеры могут лежать в папках уровня (World1Map) if m and not teleporting[player] then -- клиент затемняет экран, переносим уже в темноте: свет новой локации ставится до того, как её видно teleporting[player] = true stopFishing(player, true) remote:FireClient(player, "TeleportFade", worldId, TELEPORT_FADE) task.wait(TELEPORT_FADE) teleporting[player] = nil char = player.Character if char and char.Parent then char:PivotTo(m.CFrame + Vector3.new(0, 3, 0)) end end end ---------------------------------------------------------------- подсказки NPC local TIPS = { World1 = { "Рыба клюёт быстрее с хорошей удочкой. Улучшай её в магазине!", "Говорят, в этом озере живёт хрустальный осётр… Мифическая рыба!", "Собери всех рыб одной редкости — получишь награду в коллекции (клавиша C).", "Чем реже рыба, тем быстрее бегает метка. Нужна точность!", }, World2 = { "Скаты любят мелководье, а акулы — глубину за причалом.", "Солнечная медуза светится по ночам… Если поймаешь — ты легенда!", "Блестящая рыба стоит вдвое дороже, золотая — в пять раз, радужная — в десять!", }, World3 = { "Ищи лунки во льду — только там можно рыбачить.", "Ледяной левиафан… Я видел его тень подо льдом. Один раз.", "Удильщик светится в темноте. Смотри внимательно!", }, } local function talk(player) local hrp = player.Character and player.Character:FindFirstChild("HumanoidRootPart") local world = hrp and Config.WorldAt(hrp.Position) local list = TIPS[world and world.id or "World1"] or TIPS.World1 notify(player, "💬 «" .. list[rng:NextInteger(1, #list)] .. "»", Color3.fromRGB(255, 235, 190)) end ProximityPromptService.PromptTriggered:Connect(function(prompt, player) local action = prompt:GetAttribute("Action") if action == "Shop" then remote:FireClient(player, "OpenShop") elseif action == "Sell" then sellItems(player, nil) elseif action == "Portal" then teleportTo(player, prompt:GetAttribute("World")) elseif action == "Talk" then talk(player) elseif action == "Daily" then claimDaily(player) remote:FireClient(player, "OpenQuests") elseif action == "RobuxPasses" then remote:FireClient(player, "OpenRobux", "passes") elseif action == "RobuxProducts" then remote:FireClient(player, "OpenRobux", "products") elseif action == "Guild" or action == "Orders" or action == "Bait" or action == "Traps" then -- Старейшина, доска заказов, лавка наживки: окно гильдии на нужной вкладке Guild.sendState(player) remote:FireClient(player, "OpenGuild", ({ Guild = "rank", Orders = "orders", Bait = "bait", Traps = "traps" })[action]) end end) ---------------------------------------------------------------- события от клиента local potionCooldown = {} Players.PlayerRemoving:Connect(function(p) potionCooldown[p] = nil end) local function onRemote(player, action, a, b) if action == "Cast" then onCast(player, a) elseif action == "Tutorial" then -- шаги обучения идут только вперёд local data = profiles[player] local step = math.floor(tonumber(a) or 0) if data and step > (player:GetAttribute("Tutorial") or 0) and step <= Config.TutorialDone then data.tutorial = step player:SetAttribute("Tutorial", step) end elseif action == "Catch" then onCatch(player, a, b) elseif action == "Cancel" then stopFishing(player, false) elseif action == "Buy" then buy(player, a, b) elseif action == "SellOne" then if type(a) ~= "number" then return end if nearSeller(player) then sellItems(player, a) else notify(player, "⚪ Только у скупщика", Color3.fromRGB(255, 200, 120)) end elseif action == "SellAll" then if nearSeller(player) then sellItems(player, nil) else notify(player, "⚪ Только у скупщика", Color3.fromRGB(255, 200, 120)) end elseif action == "Teleport" then teleportTo(player, a) elseif action == "ClaimCollection" then claimCollection(player, a, b) elseif action == "ClaimDaily" then claimDaily(player) elseif action == "RequestInventory" then sendInventory(player) sendQuests(player) elseif action == "Settings" then -- громкость музыки и эффектов (0..1), сохраняется вместе с прогрессом local data = profiles[player] local music, sfx = tonumber(a), tonumber(b) if data and music and sfx then data.settings = { music = math.clamp(music, 0, 1), sfx = math.clamp(sfx, 0, 1) } player:SetAttribute("VolMusic", data.settings.music) player:SetAttribute("VolSfx", data.settings.sfx) end elseif action == "AutoFish" then setAutoFish(player, a == true) elseif action == "DrinkPotion" then local t = os.clock() if (potionCooldown[player] or 0) <= t then potionCooldown[player] = t + 0.4 drinkPotion(player, a, b) end elseif Market.onAction(player, action, a, b) then return else Guild.onAction(player, action, a, b) end end remote.OnServerEvent:Connect(onRemote) ---------------------------------------------------------------- донат -- все покупки — Developer Products: и наборы (Config.Products), и пропуска навсегда (Config.GamePasses) local function findProduct(productId) for _, p in ipairs(Config.Products) do if p.id == productId then return p, false end end for _, gp in ipairs(Config.GamePasses) do if gp.id == productId then return gp, true end end return nil end MarketplaceService.ProcessReceipt = function(info) local player = Players:GetPlayerByUserId(info.PlayerId) local data = player and profiles[player] if not data then return Enum.ProductPurchaseDecision.NotProcessedYet end for _, id in ipairs(data.receipts) do if id == info.PurchaseId then return Enum.ProductPurchaseDecision.PurchaseGranted end end local product, isPass = findProduct(info.ProductId) if not product then warn("ProcessReceipt: неизвестный товар " .. tostring(info.ProductId)) return Enum.ProductPurchaseDecision.NotProcessedYet end data.robuxSpent += info.CurrencySpent or product.robux or 0 feed("buy", { name = player.DisplayName, userId = player.UserId, item = product.icon .. " " .. product.name }) if isPass then data.passes[product.key] = true passes[player] = passes[player] or {} passes[player][product.key] = true notify(player, "✅ " .. product.icon .. " " .. product.name .. " — навсегда!", GOLD) if product.key == "VIP" then vipTag(player) end end if product.coins then -- как обещано в описании товара: «больше с уровнем» (формула не менялась в экономике v2) local coins = addCoins(player, data, product.coins * (1 + (data.level - 1) * 0.15), "Product") notify(player, ("Спасибо! +%d ⚪"):format(coins), GOLD) end if product.potion then local def = Potions.def(product.potion) Potions.add(data, product.potion, 1) Telemetry.event(player, "PotionGranted", 1, { product.potion, "Product" }) notify(player, ("%s %s — в сумке зелий. Выпей, когда будешь готов"):format(def.icon, def.name), GOLD) end table.insert(data.receipts, info.PurchaseId) if #data.receipts > 50 then table.remove(data.receipts, 1) end updateStats(player) saveData(player) return Enum.ProductPurchaseDecision.PurchaseGranted end ---------------------------------------------------------------- события на сервере task.spawn(function() task.wait(Config.EventFirstDelay) while true do currentEvent = Config.Events[rng:NextInteger(1, #Config.Events)] workspace:SetAttribute("Event", currentEvent.id) workspace:SetAttribute("EventEnds", workspace:GetServerTimeNow() + currentEvent.duration) for _, p in ipairs(Players:GetPlayers()) do notify(p, "🎉 " .. currentEvent.name, GOLD) updateStats(p) end task.wait(currentEvent.duration) currentEvent = nil workspace:SetAttribute("Event", nil) for _, p in ipairs(Players:GetPlayers()) do updateStats(p) end task.wait(rng:NextInteger(Config.EventGapMin, Config.EventGapMax)) end end) ---------------------------------------------------------------- босс озера local function playerWorld(p) local hrp = p.Character and p.Character:FindFirstChild("HumanoidRootPart") return hrp and Config.WorldAt(hrp.Position) end local function setBossAttrs() workspace:SetAttribute("BossWorld", boss and boss.world.id or nil) workspace:SetAttribute("BossName", boss and boss.def.name or nil) workspace:SetAttribute("BossHP", boss and boss.hp or nil) workspace:SetAttribute("BossMax", boss and boss.max or nil) workspace:SetAttribute("BossEnds", boss and boss.ends or nil) end local function finishBoss(won) local b = boss boss = nil setBossAttrs() local helpers, best, bestDmg = 0, nil, 0 for p, d in pairs(b.dmg) do if p.Parent then helpers += 1 if d > bestDmg then best, bestDmg = p, d end end end if not won then for _, p in ipairs(Players:GetPlayers()) do remote:FireClient(p, "BossDone", false, b.def.name) end return end local R = Config.Boss.reward local fair = b.max / math.max(1, helpers) -- «честная доля» урона на одного local potion = R.potion and Potions.def(R.potion) for p, d in pairs(b.dmg) do local data = p.Parent and profiles[p] if data then -- серебро × tier мира босса (без множителя уровня), опыта карьеры нет, зелье — в сумку зелий local share = 0.4 + 0.6 * math.min(1, d / fair) local coins = addCoins(p, data, R.coins * (b.world.tier or 1) * share, "Boss") local gotPotion = givePotion(p, data, potion) Guild.onBossWin(p, data) updateStats(p) remote:FireClient(p, "BossReward", coins, 0, gotPotion and (potion.icon .. " " .. potion.name) or nil) end end for _, p in ipairs(Players:GetPlayers()) do remote:FireClient(p, "BossDone", true, b.def.name, best and best.DisplayName, bestDmg) end end task.spawn(function() task.wait(Config.Boss.firstDelay) while true do -- мир, где сейчас больше всего игроков local counts = {} for _, p in ipairs(Players:GetPlayers()) do local w = playerWorld(p) if w and Config.Boss.worlds[w.id] then counts[w.id] = (counts[w.id] or 0) + 1 end end local bestId, n = nil, 0 for id, c in pairs(counts) do if c > n then bestId, n = id, c end end if not bestId then task.wait(30) -- никого нет в мирах: попробуем позже else local world = Config.Find(Config.Worlds, bestId) local max = Config.Boss.hpPerPlayer * n boss = { world = world, def = Config.Boss.worlds[bestId], hp = max, max = max, dmg = {}, ends = workspace:GetServerTimeNow() + Config.Boss.duration, } setBossAttrs() for _, p in ipairs(Players:GetPlayers()) do remote:FireClient(p, "BossStart", boss.def.name, world.icon .. " " .. world.name) end local t0 = os.clock() while boss and boss.hp > 0 and os.clock() - t0 < Config.Boss.duration do task.wait(0.25) end if boss then finishBoss(boss.hp <= 0) end task.wait(Config.Boss.interval) end end end) ---------------------------------------------------------------- игроки local function onPlayerAdded(player) -- камеру нельзя отвести так далеко, чтобы заглянуть за скалы и край карты player.CameraMinZoomDistance = Config.Camera.minZoom player.CameraMaxZoomDistance = Config.Camera.maxZoom local ls = Instance.new("Folder") ls.Name = "leaderstats" ls.Parent = player for _, name in ipairs({ "Серебро", "Уровень", "Улов" }) do local v = Instance.new("IntValue") v.Name = name v.Parent = ls end local data, status = loadData(player) if not player.Parent then -- ушёл, пока грузились: снять поставленный замок сессии if status == "ok" and playerStore then task.spawn(function() playerStore:save("player_" .. player.UserId, data, true) end) end return end if status == "locked" then player:Kick("Твой прогресс ещё сохраняется на другом сервере. Зайди снова через минуту.") return end loadPasses(player, data) ensureChain(data) Guild.defaults(data) -- экономика v2: перенос старого сохранения (уровень, доля опыта, зелье, id рыбы); повторно не выполняется if Progression.migrate(data, { now = os.time(), userId = player.UserId, name = player.DisplayName }) then Telemetry.event(player, "EconomyMigrated", 1, { tostring(data.migration and data.migration.from), tostring(data.level) }) end Potions.ensure(data) Market.ensure(data) Guild.onJoin(player, data) -- рынок: разобрать сделки, прерванные падением сервера (по журналу сделок) if Market.unresolved(data) then Market.recover(player, data) end profiles[player] = data loadedOk[player] = status == "ok" local settings = type(data.settings) == "table" and data.settings or {} player:SetAttribute("VolMusic", tonumber(settings.music) or Config.DefaultVolume.music) player:SetAttribute("VolSfx", tonumber(settings.sfx) or Config.DefaultVolume.sfx) updateStats(player) sendInventory(player) sendQuests(player) Guild.sendState(player) local function onCharacter() stopFishing(player, false) task.wait(0.3) giveRodTool(player) attachBag(player) vipTag(player) Guild.badge(player) end player.CharacterAdded:Connect(onCharacter) if player.Character then task.spawn(onCharacter) end end Players.PlayerAdded:Connect(onPlayerAdded) for _, p in ipairs(Players:GetPlayers()) do task.spawn(onPlayerAdded, p) end -- выход: дождаться сделок рынка и снять лоты, затем финальное сохранение со снятием замка сессии local leaving = {} local function finishPlayer(player) if leaving[player] then return end leaving[player] = true stopFishing(player, false) combo[player], comboUntil[player] = nil, nil autoFishing[player] = nil if profiles[player] then Market.onLeave(player, 20) Guild.onLeave(profiles[player]) Telemetry.flush(player) end saveData(player, true) profiles[player] = nil loadedOk[player] = nil passes[player] = nil leaving[player] = nil end Players.PlayerRemoving:Connect(finishPlayer) game:BindToClose(function() -- параллельно: у сервера ~30 секунд, последовательные сохранения могут не успеть local left = 0 for _, p in ipairs(Players:GetPlayers()) do left += 1 task.spawn(function() finishPlayer(p) left -= 1 end) end local t0 = os.clock() while left > 0 and os.clock() - t0 < 25 do task.wait(0.1) end end) -- погода и ночь меняют удачу: пересчитываем её у всех, когда они меняются local function refreshAllStats() for _, p in ipairs(Players:GetPlayers()) do updateStats(p) end end workspace:GetAttributeChangedSignal("Weather"):Connect(refreshAllStats) -- таймер зелий + автосохранение task.spawn(function() local t = 0 local wasNight = isNight() while true do task.wait(1) t += 1 local night = isNight() if night ~= wasNight then wasNight = night refreshAllStats() end for _, p in ipairs(Players:GetPlayers()) do local data = profiles[p] -- зелья на время тикают, пока игрок в игре local pDef = data and Potions.active(data) if pDef and not pDef.charges then if Potions.tick(data, 1) then notify(p, pDef.icon .. " " .. pDef.name .. " закончилось", Color3.fromRGB(255, 200, 120)) end updateStats(p) end -- бонус отдыха тратится, пока игрок рыбачит if data and (fishing[p] or autoFishing[p]) then Guild.spendRest(p, data, 1) end -- серия сгорает, если долго нет улова (пока рыба на крючке — ждём) if comboUntil[p] and os.time() > comboUntil[p] and not fishing[p] then breakCombo(p) end end -- рынок: снять просроченные лоты, разослать изменения if t % 5 == 0 then Market.tick() end if Market.isDirty() then Market.broadcast(Players:GetPlayers()) end if t % 60 == 0 then for _, p in ipairs(Players:GetPlayers()) do local data = profiles[p] -- сделки, которые журнал не подтвердил при входе, — ещё раз if data and not leaving[p] and Market.unresolved(data) and next(Market._inflight()) == nil then if Market.recover(p, data) then updateStats(p) sendInventory(p) end end task.spawn(saveData, p) end end end end) ---------------------------------------------------------------- проверки в Studio -- ServerStorage.EconomyDebug:Invoke("telemetry") / ("profile", player) / ("market") if RunService:IsStudio() then local f = Instance.new("BindableFunction") f.Name = "EconomyDebug" f.OnInvoke = function(op, player, a, b, c) if op == "telemetry" then return Telemetry.summary() elseif op == "profile" then return profiles[player] elseif op == "market" then return Market.snapshot(player) elseif op == "set" then -- профиль приходит через BindableFunction копией: менять поля — только так local data = profiles[player] if data then data[a] = b updateStats(player) end elseif op == "action" then onRemote(player, a, b, c) elseif op == "grant" then -- выдать рыбу как пойманную (для проверок рынка) local data = profiles[player] local f2 = Config.FindFish(a) if data and f2 then local _, zoneId = Config.FindFish(a) grantFish(player, data, { id = f2.id, name = f2.name, rarity = f2.rarity, weight = f2.minW, value = f2.price, mutation = b, world = zoneId }, { auto = true }) end end return true end f.Parent = game:GetService("ServerStorage") end