Files
Fishing/install/4_GameServer_ServerScriptService.rbxmx
T
2026-11-02 22:20:48 +05:00

1290 lines
37 KiB
Plaintext

<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 = {},
quests = {}, 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 sendQuests(player)
local data = profiles[player]
if not data then
return
end
local t = today()
remote:FireClient(player, "Quests", data.quests, {
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("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 .. "! Удача +" .. math.floor(Config.LuckPerPlayerLevel * 100) .. "%", 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 makeQuest(data, exclude)
local pool = {}
for _, q in ipairs(Config.Quests) do
if not exclude[q.kind] then
table.insert(pool, q)
end
end
if #pool == 0 then
pool = Config.Quests
end
local t = pool[rng:NextInteger(1, #pool)]
local goal = t.goals[rng:NextInteger(1, #t.goals)]
local mult = 1 + (data.level - 1) * 0.25
return {
kind = t.kind, goal = goal, progress = 0,
coins = math.max(10, math.floor(t.coins * goal * mult)),
xp = math.max(10, math.floor(t.xp * goal * mult)),
}
end
local function ensureQuests(data)
local kinds = {}
for _, q in ipairs(data.quests) do
kinds[q.kind] = true
end
while #data.quests < Config.QuestSlots do
local q = makeQuest(data, kinds)
kinds[q.kind] = true
table.insert(data.quests, q)
end
end
local function questProgress(player, kind, amount)
local data = profiles[player]
if not data then
return
end
local changed = false
for _, q in ipairs(data.quests) do
if q.kind == kind and q.progress < q.goal then
q.progress = math.min(q.goal, q.progress + amount)
changed = true
if q.progress >= q.goal then
notify(player, "📜 Задание выполнено! Забери награду (клавиша Q)", GOLD)
end
end
end
if changed then
sendQuests(player)
end
end
local function claimQuest(player, index)
local data = profiles[player]
local q = data and type(index) == "number" and data.quests[index]
if not q or q.progress < q.goal then
return
end
data.coins += q.coins
addXp(player, data, q.xp)
local kinds = {}
for i, other in ipairs(data.quests) do
if i ~= index then
kinds[other.kind] = true
end
end
kinds[q.kind] = true
data.quests[index] = makeQuest(data, kinds)
updateStats(player)
sendQuests(player)
notify(player, ("📜 Награда: +%d 💰 +%d XP"):format(q.coins, q.xp), GREEN)
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 💰 и +%d%% удачи навсегда"):format(world.name, coins, math.floor(Config.MasteryLuck * 100 + 0.5)), 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, ("📖 Коллекция «%s»: +%d 💰 +%d XP"):format(Config.Rarities[rarity].name, 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 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
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))
if a >= 1 then
break
end
RunService.Heartbeat:Wait()
end
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 = {}
-- ищем воду перед игроком по карте мира из FishConfig (не зависит от террейна)
local function findWater(hrp, world)
local look = hrp.CFrame.LookVector * Vector3.new(1, 0, 1)
if look.Magnitude < 0.01 then
look = Vector3.new(0, 0, -1)
end
look = look.Unit
for _, d in ipairs({ 14, 11, 17, 8, 20, 6, 24, 4 }) do
local p = hrp.Position + look * d
if Config.IsWater(world, p) then
return Vector3.new(p.X, world.waterY or 0, p.Z)
end
end
return nil
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
s.bobber:Destroy()
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)
local zone = Config.Zones[worldId]
if not zone then
return nil
end
local luck = totalLuck(player, data)
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)
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
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, dur = os.clock(), 0.55
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) * 6, 0)))
if a >= 1 then
break
end
RunService.Heartbeat:Wait()
end
if bobber.Parent then
splash(bobber.PrimaryPart, 18)
playSound(bobber.PrimaryPart, SPLASH_SOUND, 0.5)
end
end
local function onCast(player)
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 target = world and findWater(hrp, world)
if not target then
remote:FireClient(player, "CastFail")
notify(player, world and "Повернись лицом к воде (или к лунке)!" or "Здесь нет рыбы — иди в один из миров 🌍", 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 fish = rollFish(player, data, world.id)
if not fish then
remote:FireClient(player, "CastFail")
return
end
local s = { stage = "casting", fish = fish, tool = tool }
fishing[player] = s
remote:FireClient(player, "Cast")
task.spawn(function()
-- замах назад и бросок вперёд
local tw = tweenGrip(tool, 100, 0.25)
if tw then
tw.Completed:Wait()
end
tw = tweenGrip(tool, 8, 0.15)
if tw then
tw.Completed:Wait()
end
if fishing[player] ~= s then
return
end
flyBobber(s, tool, target + Vector3.new(0, 0.15, 0))
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)
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
if s.bobber then
s.bobber:Destroy()
end
if success ~= true or os.clock() - s.biteAt > Config.BiteTimeout + 1 then
gripSequence(tool, { { REST_ANGLE, 0.3 } })
remote:FireClient(player, "Escaped")
notify(player, "Рыба сорвалась!", RED)
return
end
gripSequence(tool, { { 85, 0.15 }, { REST_ANGLE, 0.45 } })
local fish = s.fish
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 })
local rank = Config.Rarities[fish.rarity].rank
questProgress(player, "catch", 1)
if rank >= 3 then
questProgress(player, "rare", 1)
end
if rank >= 4 then
questProgress(player, "epic", 1)
end
if fish.mutation then
questProgress(player, "mutation", 1)
end
if misses == 0 then
questProgress(player, "perfect", 1)
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 += 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, "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)
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, ("🍀 %s: удача +%d%% на %d мин"):format(potion.name, potion.bonus * 100, potion.duration / 60), GREEN)
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
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
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)
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)
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)
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 == "ClaimQuest" then
claimQuest(player, a)
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 .. " — " .. currentEvent.desc, 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 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)
ensureQuests(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)
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
end
if t % 60 == 0 then
for _, p in ipairs(Players:GetPlayers()) do
saveData(p)
end
end
end
end)
]]></ProtectedString></Properties></Item>
</roblox>