Files
Fishing/install/4_GameServer_ServerScriptService.rbxmx
T
2026-11-03 19:56:18 +03:00

1554 lines
47 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<roblox xmlns:xmime="http://www.w3.org/2005/05/xmlmime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.roblox.com/roblox.xsd" version="4">
<Item class="Script" referent="RBX1"><Properties><string name="Name">GameServer</string><ProtectedString name="Source"><![CDATA[-- 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 remote = ReplicatedStorage:FindFirstChild("GameEvent") or Instance.new("RemoteEvent")
remote.Name = "GameEvent"
remote.Parent = ReplicatedStorage
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 = nil
pcall(function()
store = DataStoreService:GetDataStore("FishingGame_v2")
end)
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,
totalCaught = 0, nextUid = 1, receipts = {},
}
end
local function loadData(player)
local data = defaultData()
if not store then
return data, false
end
local ok, saved = pcall(function()
return store:GetAsync("player_" .. player.UserId)
end)
if not ok then
warn("Не удалось загрузить данные " .. player.Name .. ": " .. tostring(saved))
return data, false
end
if type(saved) == "table" then
for k, v in pairs(saved) do
data[k] = v
end
end
return data, true
end
local function saveData(player)
local data = profiles[player]
if not store or not data or not loadedOk[player] then
return
end
local ok, err = pcall(function()
store:SetAsync("player_" .. player.UserId, data)
end)
if not ok then
warn("Не удалось сохранить данные " .. player.Name .. ": " .. tostring(err))
end
end
---------------------------------------------------------------- пропуска и события
local function hasPass(player, key)
return passes[player] ~= nil and passes[player][key] == true
end
local function loadPasses(player)
passes[player] = {}
for _, gp in ipairs(Config.GamePasses) do
if gp.id and gp.id > 0 then
local ok, owns = pcall(function()
return MarketplaceService:UserOwnsGamePassAsync(player.UserId, gp.id)
end)
if ok and owns then
passes[player][gp.key] = true
end
end
end
end
local currentEvent = nil
local function ev(field, default)
return (currentEvent and currentEvent[field]) or default
end
---------------------------------------------------------------- расчёты
local function rodLevel(data, rodId)
return data.rodLevels[rodId or data.rod] or 0
end
local function boostActive(data)
return data.boostUntil > os.time() and data.boostBonus 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)
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 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 levelMult(data)
return 1 + (data.level - 1) * 0.25
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 *= levelMult(data)
end
g = math.ceil(g)
return kind.max and math.min(g, kind.max) or g
end
local function stepReward(data, step, goal)
local kind = Config.QuestKinds[step[1]]
local m = levelMult(data)
return math.max(10, math.floor(kind.coins * goal * m)), math.max(10, math.floor(kind.xp * goal * m))
end
local function chainBonus(data)
local b = Config.ChainBonus
local m = levelMult(data) * (1 + Config.QuestTierGrowth * data.chain.tier)
return math.floor(b.coins * m), math.floor(b.xp * m), b.potion and Config.Find(Config.Potions, b.potion)
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))
player:SetAttribute("BoostBonus", boostActive(data))
player:SetAttribute("BoostLeft", math.max(0, data.boostUntil - os.time()))
player:SetAttribute("TotalCaught", data.totalCaught)
-- шаг обучения (линия-подсказка); у старых игроков без поля, уже ловивших рыбу, обучение пройдено
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, ","))
local ls = player:FindFirstChild("leaderstats")
if ls then
ls["Монеты"].Value = data.coins
ls["Уровень"].Value = data.level
ls["Улов"].Value = data.totalCaught
end
end
local function addXp(player, data, amount)
data.xp += amount
local leveled = false
while data.xp >= Config.XPForLevel(data.level) do
data.xp -= Config.XPForLevel(data.level)
data.level += 1
leveled = true
end
if leveled then
notify(player, "⭐ Уровень " .. data.level .. "!", GOLD)
for _, w in ipairs(Config.Worlds) do
if w.level == data.level and not w.soon then
notify(player, "🌍 Открыт: " .. w.icon .. " " .. w.name, w.color)
end
end
end
end
local function applyPotion(data, bonus, duration)
data.boostBonus = math.max(boostActive(data), bonus)
data.boostUntil = math.max(os.time(), data.boostUntil) + duration
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, xp = stepReward(data, step, goal)
data.coins += coins
addXp(player, data, xp)
remote:FireClient(player, "QuestDone", kind, goal, coins, xp)
c.step += 1
c.progress = 0
if c.step > #chain.steps then
local bCoins, bXp, potion = chainBonus(data)
data.coins += bCoins
addXp(player, data, bXp)
if potion then
applyPotion(data, potion.bonus, potion.duration)
end
remote:FireClient(player, "ChainDone", chain.name, bCoins, bXp, potion and 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 = math.floor(r.coins * (1 + (data.level - 1) * 0.2))
data.coins += coins
local extra = ""
if r.potion then
local p = Config.Find(Config.Potions, r.potion)
if p then
applyPotion(data, p.bonus, p.duration)
extra = " + " .. p.name
end
end
data.daily = { last = t, streak = streak }
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
data.claimed[key] = true
if rarity == "Master" then
local coins = Config.MasteryCoins * world.mult
data.coins += coins
notify(player, ("🏆 «%s» собран! +%d 💰"):format(world.name, coins), GOLD)
else
local r = Config.CollectionRewards[rarity]
if not r then
return
end
data.coins += r.coins * world.mult
addXp(player, data, r.xp * world.mult)
notify(player, ("📖 +%d 💰 +%d XP"):format(r.coins * world.mult, r.xp * world.mult), GREEN)
end
updateStats(player)
sendInventory(player)
end
---------------------------------------------------------------- удочка, сумка, VIP на персонаже
local REST_ANGLE = 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.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
local function rollFish(player, data, worldId, luckMult)
local zone = Config.Zones[worldId]
if not zone then
return nil
end
local luck = totalLuck(player, data) * (luckMult or 1)
local bonus = luck - 1
local weights, total = {}, 0
for i, f in ipairs(zone.fish) do
local r = Config.Rarities[f.rarity]
local w = r.weight * math.max(0.2, 1 + bonus * (r.rank - 1))
if r.rank == 1 then
w = r.weight / math.max(1, luck)
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
for _, m in ipairs(Config.Mutations) do
if rng:NextNumber() < m.chance * luck * ev("mutation", 1) then
mutation = m
break
end
end
local wf = rng:NextNumber() ^ 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),
xp = chosen.xp * (mutation and 2 or 1),
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 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 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 fish = rollFish(player, data, world.id, perfect and Config.CastPerfectLuck or 1)
if not fish then
remote:FireClient(player, "CastFail")
return
end
local s = { stage = "casting", fish = fish, tool = tool, perfect = perfect }
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"
local waitTime = rng:NextNumber(Config.BiteTimeMin, Config.BiteTimeMax) * stats.speed * ev("speed", 1)
task.wait(waitTime)
if fishing[player] ~= s then
return
end
s.stage = "bite"
s.biteAt = os.clock()
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
remote:FireClient(player, "Bite", {
speed = 0.55 + 0.22 * (rank - 1),
zoneWidth = math.max(0.07, stats.zone - 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 failed = success ~= true or os.clock() - s.biteAt > Config.BiteTimeout + 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 } })
-- серия: каждая рыба подряд дороже и даёт больше опыта
local fish = s.fish
local streak = combo[player] or 0
local comboMult = math.min(Config.Combo.max, 1 + Config.Combo.step * streak)
fish.value = math.floor(fish.value * comboMult + 0.5)
fish.xp = math.floor(fish.xp * comboMult + 0.5)
setCombo(player, streak + 1)
table.insert(data.items, {
uid = data.nextUid, id = fish.id, name = fish.name, rarity = fish.rarity,
weight = fish.weight, value = fish.value, mutation = fish.mutation,
})
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 * (isNew and 2 or 1))
updateStats(player)
sendInventory(player)
if fromPos then
showFishFlight(player, fish, fromPos)
end
remote:FireClient(player, "Caught", fish, { new = isNew, record = isRecord, combo = comboMult, streak = streak + 1 })
local rank = Config.Rarities[fish.rarity].rank
questProgress(player, "catch", 1)
if rank >= 2 then
questProgress(player, "uncommon", 1)
end
if rank >= 3 then
questProgress(player, "rare", 1)
end
if misses == 0 then
questProgress(player, "perfect", 1)
end
if s.perfect then
questProgress(player, "perfectCast", 1)
end
questProgress(player, "combo", streak + 1, true)
local hrp = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
bossHit(player, hrp and Config.WorldAt(hrp.Position), rank + (misses == 0 and 1 or 0))
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 += 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
data.coins += 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 = Config.UpgradeCost(rod, lvl)
if data.coins < cost then
notify(player, "Нужно " .. cost .. " 💰", RED)
return
end
data.coins -= cost
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
local potion = Config.Find(Config.Potions, id)
if not potion then
return
end
if potion.level and data.level < potion.level then
notify(player, "🔒 Нужен ур. " .. potion.level, RED)
return
end
if data.coins < potion.price then
notify(player, "Нужно " .. potion.price .. " 💰", RED)
return
end
data.coins -= potion.price
applyPotion(data, potion.bonus, potion.duration)
updateStats(player)
notify(player, ("🍀 +%d%% удачи, %d мин"):format(potion.bonus * 100, potion.duration / 60), 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
if data.coins < item.price then
notify(player, "Нужно " .. item.price .. " 💰", RED)
return
end
data.coins -= item.price
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
---------------------------------------------------------------- телепорт
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
markerName = world.id .. "Spawn"
end
local map = workspace:FindFirstChild("FishingMap")
local m = map and map:FindFirstChild(markerName, true) -- маркеры могут лежать в папках уровня (World1Map)
if m then
stopFishing(player, true)
char:PivotTo(m.CFrame + Vector3.new(0, 3, 0))
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")
end
end)
---------------------------------------------------------------- события от клиента
remote.OnServerEvent:Connect(function(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)
end
end)
---------------------------------------------------------------- донат
MarketplaceService.PromptGamePassPurchaseFinished:Connect(function(player, passId, purchased)
if not purchased then
return
end
for _, gp in ipairs(Config.GamePasses) do
if gp.id == passId then
passes[player] = passes[player] or {}
passes[player][gp.key] = true
notify(player, "✅ " .. gp.icon .. " " .. gp.name, GOLD)
if gp.key == "VIP" then
vipTag(player)
end
updateStats(player)
end
end
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
for _, p in ipairs(Config.Products) do
if p.id == info.ProductId then
product = p
end
end
if not product then
return Enum.ProductPurchaseDecision.NotProcessedYet
end
if product.coins then
local coins = math.floor(product.coins * (1 + (data.level - 1) * 0.15))
data.coins += coins
notify(player, ("Спасибо! +%d 💰"):format(coins), GOLD)
end
if product.boost then
applyPotion(data, product.boost, product.duration)
notify(player, ("🍀 +%d%% удачи, %d мин"):format(product.boost * 100, product.duration / 60), 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 Config.Find(Config.Potions, R.potion)
for p, d in pairs(b.dmg) do
local data = p.Parent and profiles[p]
if data then
local share = 0.4 + 0.6 * math.min(1, d / fair)
local coins = math.floor(R.coins * b.world.mult * share * levelMult(data))
local xp = math.floor(R.xp * b.world.mult * share)
data.coins += coins
addXp(p, data, xp)
if potion then
applyPotion(data, potion.bonus, potion.duration)
end
updateStats(p)
remote:FireClient(p, "BossReward", coins, xp, potion and potion.name)
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)
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, ok = loadData(player)
if not player.Parent then
return
end
loadPasses(player)
ensureChain(data)
profiles[player] = data
loadedOk[player] = ok
updateStats(player)
sendInventory(player)
sendQuests(player)
local function onCharacter()
stopFishing(player, false)
task.wait(0.3)
giveRodTool(player)
attachBag(player)
vipTag(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
Players.PlayerRemoving:Connect(function(player)
stopFishing(player, false)
combo[player], comboUntil[player] = nil, nil
saveData(player)
profiles[player] = nil
loadedOk[player] = nil
passes[player] = nil
end)
game:BindToClose(function()
for _, p in ipairs(Players:GetPlayers()) do
saveData(p)
end
end)
-- таймер зелий + автосохранение
task.spawn(function()
local t = 0
while true do
task.wait(1)
t += 1
for _, p in ipairs(Players:GetPlayers()) do
local data = profiles[p]
if data and data.boostUntil > os.time() - 2 then
updateStats(p)
end
-- серия сгорает, если долго нет улова (пока рыба на крючке — ждём)
if comboUntil[p] and os.time() > comboUntil[p] and not fishing[p] then
breakCombo(p)
end
end
if t % 60 == 0 then
for _, p in ipairs(Players:GetPlayers()) do
saveData(p)
end
end
end
end)
]]></ProtectedString></Properties></Item>
</roblox>