экономика

This commit is contained in:
listik committed 2026-11-11 15:53:07 +03:00
1 parent 296988b199
commit 58ae93f9e6
28 files changed
+6503 -299

No files matched your search

+395 -136
View File
@@ -14,6 +14,12 @@ 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"
@@ -72,10 +78,13 @@ local SPLASH_SOUND = "rbxasset://sounds/impact_water.mp3"
---------------------------------------------------------------- данные
local store = nil
local store, marketStore = nil, nil
pcall(function()
store = DataStoreService:GetDataStore("FishingGame_v2")
marketStore = DataStoreService:GetDataStore("FishMarket_v1")
end)
-- замок сессии: профиль открыт только на одном сервере (без этого возможен дюп между серверами и на рынке)
local playerStore = store and PlayerStore.new(store, { staleAfter = 600 }) or nil
local profiles = {}
local loadedOk = {}
@@ -88,7 +97,8 @@ local function defaultData()
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,
boostUntil = 0, boostBonus = 0, -- до экономики v2 (переносятся в potions миграцией)
potions = { inv = {} }, market = {},
totalCaught = 0, nextUid = 1, receipts = {},
passes = {}, -- купленные пропуска (Developer Products): [key] = true
coinsEarned = 0, robuxSpent = 0, -- для досок лидеров: всего выручено за рыбу и потрачено Robux
@@ -98,37 +108,44 @@ local function defaultData()
}
end
-- status: "ok" (из хранилища), "offline" (хранилища нет — играем без сохранения), "locked", "error"
local function loadData(player)
local data = defaultData()
if not store then
return data, false
if not playerStore then
data.econ = E.version
return data, "offline"
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
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" then
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, true
return data, "ok"
end
local function saveData(player)
-- ok; release = true — игрок уходит (снять замок сессии)
local function saveData(player, release)
local data = profiles[player]
if not store or not data or not loadedOk[player] then
return
if not playerStore or not data or not loadedOk[player] then
return false
end
local ok, err = pcall(function()
store:SetAsync("player_" .. player.UserId, data)
end)
local ok, status, err = playerStore:save("player_" .. player.UserId, data, release)
if not ok then
warn("Не удалось сохранить данные " .. player.Name .. ": " .. tostring(err))
warn(("Не удалось сохранить данные %s: %s %s"):format(player.Name, tostring(status), tostring(err)))
if status == "lost" then
-- профиль уже открыт другим сервером: дальше этот сервер его не пишет
loadedOk[player] = false
end
end
return ok
end
---------------------------------------------------------------- пропуска и события
@@ -169,8 +186,9 @@ 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
return Potions.effect(data).luck or 0
end
local function masteryCount(data)
@@ -215,6 +233,31 @@ 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
@@ -228,10 +271,6 @@ 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]
@@ -242,22 +281,31 @@ 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)
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 m = levelMult(data)
return math.max(10, math.floor(kind.coins * goal * m)), math.max(10, math.floor(kind.xp * goal * m))
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 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)
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)
@@ -319,8 +367,15 @@ local function updateStats(player)
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", math.max(0, data.boostUntil - os.time()))
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 — уже доступна); по ней сундук в лобби прыгает только для тех,
@@ -341,33 +396,43 @@ local function updateStats(player)
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
-- опыт карьеры (единственный источник — ручная поимка; source — для телеметрии)
local function addXp(player, data, amount, source)
if amount <= 0 then
return
end
if leveled then
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 w.level == data.level and not w.soon then
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 applyPotion(data, bonus, duration)
data.boostBonus = math.max(boostActive(data), bonus)
data.boostUntil = math.max(os.time(), data.boostUntil) + duration
-- зелье-награда: в сумку зелий (пить — когда игрок сам решит)
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
---------------------------------------------------------------- задания: прогресс цепочки
@@ -395,20 +460,18 @@ local function questProgress(player, kind, amount, absolute)
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)
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, bXp, potion = chainBonus(data)
data.coins += bCoins
addXp(player, data, bXp)
local bCoins, _, potion = chainBonus(data)
addCoins(player, data, bCoins, "Chain")
if potion then
applyPotion(data, potion.bonus, potion.duration)
givePotion(player, data, potion)
end
remote:FireClient(player, "ChainDone", chain.name, bCoins, bXp, potion and potion.name)
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
@@ -432,14 +495,12 @@ local function claimDaily(player)
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 coins = addCoins(player, data, r.coins * tierOf(data), "Daily")
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
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 }
@@ -471,19 +532,19 @@ local function claimCollection(player, worldId, rarity)
return
end
end
data.claimed[key] = true
-- коллекция — исследование: серебро (× tier мира) и мастерство, без опыта карьеры
if rarity == "Master" then
local coins = Config.MasteryCoins * world.mult
data.coins += coins
notify(player, ("🏆 «%s» собран! +%d ⚪"):format(world.name, coins), GOLD)
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.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)
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)
@@ -808,7 +869,9 @@ local function stopFishing(player, tellClient)
end
end
-- mods: { bait = наживка из Config.Baits, maxRank = потолок редкости (автоловля) }
-- 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
@@ -816,22 +879,23 @@ local function rollFish(player, data, worldId, luckMult, mods)
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 bonus = luck - 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 = r.weight * math.max(0.2, 1 + bonus * (r.rank - 1))
if r.rank == 1 then
w = r.weight / math.max(1, luck)
end
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
@@ -848,13 +912,14 @@ local function rollFish(player, data, worldId, luckMult, mods)
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 * luck * ev("mutation", 1) * (weather().mutation or 1) * (bait and bait.mutation or 1) then
if rng:NextNumber() < m.chance * mm then
mutation = m
break
end
end
local wf = rng:NextNumber() ^ 2.2
local wf = rng:NextNumber() ^ (pot.weightCurve or 2.2)
local weight = chosen.minW + (chosen.maxW - chosen.minW) * wf
return {
id = chosen.id,
@@ -862,7 +927,6 @@ local function rollFish(player, data, worldId, luckMult, mods)
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,
}
@@ -953,12 +1017,14 @@ local function onCast(player, power)
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 fish = rollFish(player, data, world.id, perfect and Config.CastPerfectLuck or 1, { bait = bait })
-- зелье: эффект берём на момент заброса, попытку списываем при поклёвке (ниже)
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 }
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 }
@@ -983,13 +1049,19 @@ local function onCast(player, power)
end
s.stage = "waiting"
local waitTime = rng:NextNumber(Config.BiteTimeMin, Config.BiteTimeMax) * stats.speed * ev("speed", 1) * (weather().speed or 1) * (bait and bait.speed or 1)
-- все ускорения клёва вместе — не больше чем на 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)
@@ -1009,9 +1081,10 @@ local function onCast(player, power)
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 - 0.02 * (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,
@@ -1039,7 +1112,9 @@ local function onCatch(player, success, misses)
if s.tween then
s.tween:Cancel()
end
local failed = success ~= true or os.clock() - s.biteAt > Config.BiteTimeout + 1
-- подсечка быстрее, чем физически возможно пройти мини-игру, не засчитывается
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
@@ -1061,19 +1136,27 @@ end
-- ctx: { perfect, misses, fromPos, auto }; у автоловли нет серии и бонусов за точность
grantFish = function(player, data, fish, ctx)
local streak = combo[player] or 0
local comboMult = 1
local comboBonus = 0
if not ctx.auto then
-- серия: каждая рыба подряд дороже и даёт больше опыта
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)
-- серия: каждая рыба подряд чуть дороже (опыт карьеры не меняется)
comboBonus = math.min(Config.Combo.max, Config.Combo.step * streak)
setCombo(player, streak + 1)
end
fish.xp = math.floor(fish.xp * Guild.xpMult(data)) -- бонус отдыха: двойной опыт
table.insert(data.items, {
-- надбавки к цене складываются и ограничены: серия + отдых ≤ 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
@@ -1089,25 +1172,29 @@ grantFish = function(player, data, fish, ctx)
rec.best = fish.weight
end
addXp(player, data, fish.xp * (isNew and 2 or 1))
-- новый вид и рекорд радуют серебром, коллекцией и карточкой, а не скачком уровня
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 = comboMult, streak = ctx.auto and 0 or streak + 1, auto = ctx.auto })
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
questProgress(player, "catch", 1)
if rank >= 2 then
questProgress(player, "uncommon", 1)
end
if rank >= 3 then
questProgress(player, "rare", 1)
-- задания засчитывают только ручную ловлю (автоловля — дополнительный доход, не прогресс)
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
@@ -1170,7 +1257,9 @@ local function autoFishLoop(player, token)
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
@@ -1191,8 +1280,8 @@ local function autoFishLoop(player, token)
end
s.stage = "waiting"
local stats = Config.RodStats(data.rod, rodLevel(data))
local waitTime = rng:NextNumber(Config.BiteTimeMin, Config.BiteTimeMax) * stats.speed * ev("speed", 1)
* (weather().speed or 1) * (bait and bait.speed or 1) * A.slower
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")
@@ -1225,7 +1314,8 @@ local function autoFishLoop(player, token)
end
gripSequence(tool, { { 85, 0.15 }, { REST_ANGLE, 0.45 } })
grantFish(player, data, fish, { auto = true, fromPos = fromPos })
task.wait(1.2)
-- автоловля не быстрее одной рыбы за Economy.autoMinCycle секунд: не обгоняет ручную ловлю
task.wait(math.max(1.2, E.autoMinCycle - (os.clock() - cycleStart)))
end
end
@@ -1301,7 +1391,8 @@ local function sellItems(player, filterUid)
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)
-- купленная на рынке рыба — по базовой цене, без бонусов пропусков и ярмарки (нет перепродажи с наваром)
total += item.bought and math.floor(item.value) or math.floor(item.value * mult)
count += 1
else
table.insert(keep, item)
@@ -1314,7 +1405,7 @@ local function sellItems(player, filterUid)
return
end
data.items = keep
data.coins += total
addCoins(player, data, total, "Sell")
data.coinsEarned += total
updateStats(player)
sendInventory(player)
@@ -1341,11 +1432,10 @@ local function buy(player, kind, id)
return
end
local cost = Guild.price(data, Config.UpgradeCost(rod, lvl)) -- скидка ранга гильдии
if data.coins < cost then
if not spendCoins(player, data, cost, "Upgrade", id) then
notify(player, "Нужно " .. cost .. " ⚪", RED)
return
end
data.coins -= cost
data.rodLevels[id] = lvl + 1
if data.rod == id then
stopFishing(player, true)
@@ -1357,8 +1447,9 @@ local function buy(player, kind, id)
return
end
if kind == "Potion" then
local potion = Config.Find(Config.Potions, id)
if not 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
@@ -1366,14 +1457,14 @@ local function buy(player, kind, id)
return
end
local price = Guild.price(data, potion.price)
if data.coins < price then
if not spendCoins(player, data, price, "Potion", id) then
notify(player, "Нужно " .. price .. " ⚪", RED)
return
end
data.coins -= price
applyPotion(data, potion.bonus, potion.duration)
Potions.add(data, id, 1)
Telemetry.event(player, "PotionBought", 1, { id })
updateStats(player)
notify(player, ("🍀 +%d%% удачи, %d мин"):format(potion.bonus * 100, potion.duration / 60), GREEN)
notify(player, ("%s %s — в сумке зелий"):format(potion.icon, potion.name), GREEN)
questProgress(player, "buy", 1)
return
end
@@ -1396,11 +1487,10 @@ local function buy(player, kind, id)
return
end
local price = Guild.price(data, item.price)
if data.coins < price then
if not spendCoins(player, data, price, kind, id) then
notify(player, "Нужно " .. price .. " ⚪", RED)
return
end
data.coins -= price
owned[id] = true
bought = true
notify(player, "✅ " .. item.name, GREEN)
@@ -1419,6 +1509,71 @@ local function buy(player, kind, id)
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 -- сколько клиент затемняет экран перед переносом
@@ -1526,7 +1681,12 @@ end)
---------------------------------------------------------------- события от клиента
remote.OnServerEvent:Connect(function(player, action, a, b)
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
@@ -1578,10 +1738,19 @@ remote.OnServerEvent:Connect(function(player, action, a, b)
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)
end
remote.OnServerEvent:Connect(onRemote)
---------------------------------------------------------------- донат
@@ -1628,13 +1797,15 @@ MarketplaceService.ProcessReceipt = function(info)
end
end
if product.coins then
local coins = math.floor(product.coins * (1 + (data.level - 1) * 0.15))
data.coins += coins
-- как обещано в описании товара: «больше с уровнем» (формула не менялась в экономике v2)
local coins = addCoins(player, data, product.coins * (1 + (data.level - 1) * 0.15), "Product")
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)
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
@@ -1703,21 +1874,17 @@ local function finishBoss(won)
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)
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 = 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
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, xp, potion and potion.name)
remote:FireClient(p, "BossReward", coins, 0, gotPotion and (potion.icon .. " " .. potion.name) or nil)
end
end
for _, p in ipairs(Players:GetPlayers()) do
@@ -1782,16 +1949,36 @@ local function onPlayerAdded(player)
v.Parent = ls
end
local data, ok = loadData(player)
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] = ok
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)
@@ -1819,25 +2006,42 @@ for _, p in ipairs(Players:GetPlayers()) do
task.spawn(onPlayerAdded, p)
end
Players.PlayerRemoving:Connect(function(player)
-- выход: дождаться сделок рынка и снять лоты, затем финальное сохранение со снятием замка сессии
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)
saveData(player, true)
profiles[player] = nil
loadedOk[player] = nil
passes[player] = nil
end)
leaving[player] = nil
end
Players.PlayerRemoving:Connect(finishPlayer)
game:BindToClose(function()
-- параллельно: у сервера ~30 секунд, последовательные сохранения могут не успеть
local left = 0
for _, p in ipairs(Players:GetPlayers()) do
if profiles[p] then
Guild.onLeave(profiles[p])
end
saveData(p)
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)
@@ -1863,7 +2067,12 @@ task.spawn(function()
end
for _, p in ipairs(Players:GetPlayers()) do
local data = profiles[p]
if data and data.boostUntil > os.time() - 2 then
-- зелья на время тикают, пока игрок в игре
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
-- бонус отдыха тратится, пока игрок рыбачит
@@ -1875,10 +2084,60 @@ task.spawn(function()
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
saveData(p)
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
+9 -10
View File
@@ -322,7 +322,7 @@ local function takeTrial(player, data)
-- сдать рыбу из сумки сразу, если она есть
local have, keep = 0, {}
for _, item in ipairs(data.items) do
if item.id == t.fish and have < t.count then
if item.id == t.fish and not item.bought and have < t.count then -- испытание — только своим уловом
have += 1
else
table.insert(keep, item)
@@ -439,7 +439,7 @@ local function makeOrder(data, rng)
end
local s = O.kinds[kind].seals
o.seals = math.floor(s[1] + (s[2] - s[1]) * hard + 0.5) + (r - 1) * 2
o.coins = math.floor(o.seals * O.coinsPerSeal * (1 + 0.5 * (r - 1)))
o.coins = math.floor(o.seals * O.coinsPerSeal * (api.tierOf and api.tierOf(data) or 1))
o.pearls = rng:NextNumber() < O.pearlChance and rng:NextInteger(O.pearlsMin, O.pearlsMax) or 0
return o
end
@@ -488,7 +488,7 @@ end
local function finishOrder(player, data, o)
o.done = true
data.seals += o.seals
data.coins += o.coins
api.addCoins(player, data, o.coins, "Order")
data.pearls += o.pearls
api.notify(player, ("📜 Заказ выполнен! +%d печатей +%d ⚪%s"):format(o.seals, o.coins, o.pearls > 0 and (" +" .. o.pearls .. " 🦪") or ""), GOLD)
api.remote:FireClient(player, "OrderDone")
@@ -515,7 +515,8 @@ local function deliverOrder(player, data, i)
-- сдаём сначала самую дешёвую подходящую рыбу
local fit = {}
for _, item in ipairs(data.items) do
if item.id == o.fish and (not o.minW or item.weight >= o.minW) then
-- купленная на рынке рыба в заказы не идёт: заказ — про свой улов
if item.id == o.fish and not item.bought and (not o.minW or item.weight >= o.minW) then
table.insert(fit, item)
end
end
@@ -693,11 +694,10 @@ local function buyBait(player, data, id)
data.pearls -= b.price
else
local price = Guild.price(data, b.price)
if data.coins < price then
if not api.spendCoins(player, data, price, "Bait", b.id) then
api.notify(player, ("Нужно %d ⚪"):format(price), RED)
return
end
data.coins -= price
end
data.bait.counts[b.id] = (data.bait.counts[b.id] or 0) + b.pack
if not Guild.bait(data) then
@@ -752,6 +752,8 @@ local function collectTraps(player, data)
for _ = 1, take do
local f = rollTrapFish(rng)
f.uid = data.nextUid
f.gid = ("%d-%d"):format(player.UserId, f.uid)
f.origin = { by = player.UserId, name = player.DisplayName, world = T.world, t = now, trap = true }
data.nextUid += 1
table.insert(data.items, f)
local rec = data.discovered[f.id]
@@ -795,10 +797,7 @@ function Guild.onLeave(data)
data.lastOnline = os.time()
end
-- множитель опыта: двойной, пока есть отдых
function Guild.xpMult(data)
return (data.rest or 0) > 0 and Config.Rest.mult or 1
end
-- экономика v2: отдых даёт +25% серебра за пойманную рыбу (GameServer.grantFish), а не опыт
-- отдых тратится секундами, пока игрок рыбачит
function Guild.spendRest(player, data, seconds)
+692
View File
@@ -0,0 +1,692 @@
-- Market (ModuleScript) -> ServerScriptService
-- Рынок игроков: продажа ценной рыбы по фиксированной цене игрокам этого же сервера за серебро.
--
-- Почему так сложно. В Roblox нет атомарной транзакции сразу по двум профилям, поэтому сделка — это
-- восстанавливаемая последовательность шагов с единственной точкой фиксации в журнале сделок (ledger):
-- 1. Выставить лот: рыба переезжает из сумки продавца в его «залог» (data.market.escrow[lid]) и профиль
-- продавца СОХРАНЯЕТСЯ. Только после успешного сохранения лот виден покупателям. Не сохранилось — откат.
-- 2. Купить: лот блокируется в памяти (вторая покупка невозможна), серебро списывается у покупателя и
-- запись data.market.pending[lid] СОХРАНЯЕТСЯ. Не сохранилось — откат.
-- 3. Фиксация: ledger:cas(lid, { s = "sold", buyer, seller, price, fee }) — запись появляется, только если
-- ключа ещё нет (UpdateAsync). Кто первым записал lid — «sold» или «cancelled» — тот и решил судьбу лота.
-- 4. Применение (идемпотентно): у продавца залог → выручка, у покупателя pending → рыба в «посылках».
-- Оба профиля сохраняются; если сервер упадёт раньше — шаг 4 повторит восстановление (recover) при
-- следующем входе каждого игрока, сверившись с журналом.
-- Ошибка или неясный ответ журнала на шаге 3 — не откатываем вслепую: лот «завис», повторяем cas с
-- предложением «cancelled», пока журнал не ответит; итог применяем как есть.
-- Снять лот (вручную, по таймеру, при выходе продавца) — сначала cas «cancelled», потом рыба обратно.
-- Профили защищены замком сессии (PlayerStore): один профиль не может быть открыт на двух серверах,
-- поэтому восстановление не гонится с живой сделкой.
--
-- Купленная рыба: не открывает вид в коллекции, не даёт опыт, рекорды, заказы, испытания, задания;
-- скупщик платит за неё базовую цену без бонусов; минимальная цена лота — выше цены скупщика.
-- Купить можно рыбу только из уже открытых миров.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Config = require(ReplicatedStorage:WaitForChild("FishConfig"))
local Market = {}
local d -- зависимости (Market.init)
local listings = {} -- [lid] = лот в памяти
local inflight = {} -- [player] = число незавершённых операций с его профилем
local lastAction = {}
local dirty = false
local RED = Color3.fromRGB(255, 120, 120)
local GREEN = Color3.fromRGB(120, 255, 140)
local GOLD = Color3.fromRGB(255, 220, 80)
---------------------------------------------------------------- журналы сделок
-- журнал в DataStore: ключ на лот, запись пишется только один раз
function Market.dataStoreLedger(ds)
return {
cas = function(lid, proposal)
local final
local ok, err = pcall(function()
ds:UpdateAsync("L_" .. lid, function(old)
if old ~= nil then
final = old
return nil
end
final = proposal
return proposal
end)
end)
if not ok then
return false, nil, err
end
return final ~= nil, final
end,
}
end
-- журнал в памяти (Studio без доступа к API и тесты); fault = { failBefore = n, failAfter = n } —
-- столько следующих вызовов падают до записи / после записи (неясный ответ)
function Market.memoryLedger()
local rows = {}
local L = { rows = rows, fault = { failBefore = 0, failAfter = 0 }, calls = 0 }
function L.cas(lid, proposal)
L.calls += 1
if L.fault.failBefore > 0 then
L.fault.failBefore -= 1
return false, nil, "fault: before write"
end
if rows[lid] == nil then
rows[lid] = table.clone(proposal)
end
if L.fault.failAfter > 0 then
L.fault.failAfter -= 1
return false, nil, "fault: after write"
end
return true, table.clone(rows[lid])
end
return L
end
---------------------------------------------------------------- настройка
-- deps: profiles, ledger, save(player) -> ok, notify, changed(player), send(player, payload),
-- bagCapacity(player, data), telemetry?, now?, wait?, guid?, enabled? (fn)
function Market.init(deps)
d = deps
d.now = d.now or os.time
d.wait = d.wait or task.wait
d.guid = d.guid or function()
return game:GetService("HttpService"):GenerateGUID(false)
end
d.telemetry = d.telemetry or { silver = function() end, event = function() end }
listings, inflight, lastAction = {}, {}, {}
end
function Market.enabled()
return d ~= nil and d.ledger ~= nil and Config.Market.enabled and (d.enabled == nil or d.enabled())
end
function Market.ensure(data)
if type(data.market) ~= "table" then
data.market = {}
end
local m = data.market
m.escrow = type(m.escrow) == "table" and m.escrow or {}
m.pending = type(m.pending) == "table" and m.pending or {}
m.inbox = type(m.inbox) == "table" and m.inbox or {}
return m
end
local function busy(player, delta)
inflight[player] = math.max(0, (inflight[player] or 0) + delta)
if inflight[player] == 0 then
inflight[player] = nil
end
end
local function fail(player, text)
if player and d.notify then
d.notify(player, text, RED)
end
return false, text
end
local function changed(player)
dirty = true
if player and d.changed then
d.changed(player)
end
end
local function saveAsync(player)
if player and d.profiles[player] then
task.spawn(function()
d.save(player)
end)
end
end
---------------------------------------------------------------- правила
function Market.access(data)
return (data.level or 1) >= Config.Market.minLevel
end
function Market.eligible(item)
if type(item) ~= "table" or type(item.id) ~= "string" then
return false, "Эту рыбу нельзя выставить"
end
local r = Config.Rarities[item.rarity]
if r and r.rank >= Config.Market.minRank then
return true
end
if item.mutation and Config.Market.mutations[item.mutation] then
return true
end
return false, "На рынок — «Эпическая» и реже или рыба с золотой/радужной мутацией"
end
function Market.bounds(item)
local v = math.max(1, math.floor(tonumber(item.value) or 1))
return math.ceil(v * Config.Market.minPriceMult), math.floor(v * Config.Market.maxPriceMult)
end
function Market.fee(price)
return math.max(1, math.floor(price * Config.Market.fee + 0.5))
end
-- уровень, с которого открыт мир этой рыбы
local function fishWorldLevel(fishId)
local _, zoneId = Config.FindFish(fishId)
local w = zoneId and Config.Find(Config.Worlds, zoneId)
return w and w.level or math.huge
end
local function validPrice(price)
price = tonumber(price)
return price ~= nil and price == price and price > 0 and price < 1e9 and price % 1 == 0 and price or nil
end
local function cooldown(player)
local t = os.clock()
if lastAction[player] and t - lastAction[player] < Config.Market.actionCooldown then
return true
end
lastAction[player] = t
return false
end
-- рыба игроку: в сумку, если есть место, иначе в «посылки» (никогда не теряется)
local function deliver(player, data, item)
local cap = (player and d.bagCapacity) and d.bagCapacity(player, data) or 0
if #data.items < cap then
table.insert(data.items, item)
return "bag"
end
table.insert(Market.ensure(data).inbox, item)
return "inbox"
end
local function soldItem(item, rec, buyerId, sellerId, sellerName, now)
local it = table.clone(item)
it.bought = { from = sellerId, fromName = sellerName, price = rec.price, t = now }
local hist = type(it.history) == "table" and table.clone(it.history) or {}
table.insert(hist, { from = sellerId, to = buyerId, price = rec.price, t = now })
while #hist > 5 do
table.remove(hist, 1)
end
it.history = hist
return it
end
local function myListingCount(player)
local n = 0
for _, L in pairs(listings) do
if L.seller == player then
n += 1
end
end
return n
end
---------------------------------------------------------------- применение итога (идемпотентно)
-- продавец: залог → выручка
local function applySale(sellerData, lid, rec, seller)
local m = Market.ensure(sellerData)
if not m.escrow[lid] then
return false
end
m.escrow[lid] = nil
local proceeds = rec.price - rec.fee
sellerData.coins += proceeds
if seller then
d.telemetry.silver(seller, true, proceeds, sellerData.coins, "MarketSale")
d.telemetry.event(seller, "MarketFee", rec.fee)
end
return true, proceeds
end
-- покупатель: pending → рыба в посылки
local function applyPurchase(buyer, buyerData, lid, rec)
local m = Market.ensure(buyerData)
local p = m.pending[lid]
if not p then
return false
end
m.pending[lid] = nil
local it = soldItem(p.item, rec, rec.buyer, p.sellerId, p.sellerName, d.now())
table.insert(m.inbox, it)
return true, it
end
-- покупатель: отмена → серебро назад
local function refund(buyerData, lid)
local m = Market.ensure(buyerData)
local p = m.pending[lid]
if not p then
return false
end
m.pending[lid] = nil
buyerData.coins += p.price
return true, p.price
end
-- продавец: отмена → рыба назад
local function returnEscrow(seller, sellerData, lid)
local m = Market.ensure(sellerData)
local e = m.escrow[lid]
if not e then
return false
end
m.escrow[lid] = nil
return true, deliver(seller, sellerData, e.item)
end
-- журнал ответил: применяем итог к тем, кто на сервере
local function settle(L, rec)
local sellerData = L.seller and d.profiles[L.seller]
local buyerData = L.buyer and d.profiles[L.buyer]
if rec.s == "sold" then
if sellerData then
local ok, proceeds = applySale(sellerData, L.id, rec, L.seller)
if ok then
d.notify(L.seller, ("🏪 %s продана за %s ⚪ (вам %s ⚪ после комиссии)"):format(L.item.name, rec.price, proceeds), GOLD)
changed(L.seller)
saveAsync(L.seller)
end
end
if buyerData and L.buyer and L.buyer.UserId == rec.buyer then
local ok, it = applyPurchase(L.buyer, buyerData, L.id, rec)
if ok then
d.telemetry.event(L.buyer, "MarketBuy", rec.price, { it.id, it.rarity })
d.notify(L.buyer, ("📦 %s куплена — забери в «Посылках» рынка"):format(it.name), GREEN)
changed(L.buyer)
saveAsync(L.buyer)
end
end
else
if buyerData then
local ok, amount = refund(buyerData, L.id)
if ok then
d.notify(L.buyer, ("Покупка не состоялась — %s ⚪ возвращены"):format(amount), RED)
changed(L.buyer)
saveAsync(L.buyer)
end
end
if sellerData then
if returnEscrow(L.seller, sellerData, L.id) then
changed(L.seller)
saveAsync(L.seller)
end
end
end
listings[L.id] = nil
dirty = true
end
-- неясный ответ журнала: повторяем, пока не узнаем итог (с паузами); всё это время лот заблокирован
local function resolveLater(L)
task.spawn(function()
local pause = 1
for _ = 1, 12 do
local ok, rec = d.ledger.cas(L.id, { s = "cancelled", t = d.now() })
if ok and rec then
settle(L, rec)
break
end
d.wait(pause)
pause = math.min(30, pause * 2)
end
-- не дождались: залог и pending остаются в сохранениях, их разберёт recover при следующем входе
if listings[L.id] == L then
listings[L.id] = nil
dirty = true
end
busy(L.seller, -1)
if L.buyer then
busy(L.buyer, -1)
end
end)
end
---------------------------------------------------------------- действия игроков
function Market.list(player, uid, price)
local data = d.profiles[player]
if not data then
return false, "no data"
end
if not Market.enabled() then
return fail(player, "🏪 Рынок сейчас закрыт")
end
if not Market.access(data) then
return fail(player, ("🔒 Рынок — с %d уровня"):format(Config.Market.minLevel))
end
local m = Market.ensure(data)
if myListingCount(player) >= Config.Market.maxListings then
return fail(player, ("Не больше %d лотов"):format(Config.Market.maxListings))
end
price = validPrice(price)
if not price or type(uid) ~= "number" then
return fail(player, "Неверная цена")
end
local idx, item
for i, it in ipairs(data.items) do
if it.uid == uid then
idx, item = i, it
break
end
end
if not item then
return fail(player, "Рыбы нет в сумке")
end
local ok, why = Market.eligible(item)
if not ok then
return fail(player, why)
end
local lo, hi = Market.bounds(item)
if price < lo or price > hi then
return fail(player, ("Цена — от %d до %d ⚪"):format(lo, hi))
end
local lid = d.guid()
local fee = Market.fee(price)
table.remove(data.items, idx)
m.escrow[lid] = { item = item, price = price, fee = fee, created = d.now() }
busy(player, 1)
local saved = d.save(player)
busy(player, -1)
if not saved or not player.Parent then
-- лот ещё никому не показан, в журнале его нет — просто возвращаем рыбу
m.escrow[lid] = nil
table.insert(data.items, item)
changed(player)
if player.Parent then
return fail(player, "Не удалось сохранить — попробуй ещё раз")
end
return false, "left"
end
local now = d.now()
listings[lid] = {
id = lid, seller = player, sellerId = player.UserId, sellerName = player.DisplayName,
item = item, price = price, fee = fee, proceeds = price - fee,
created = now, expires = now + Config.Market.duration, state = "open",
}
d.telemetry.event(player, "MarketListed", price, { item.id, item.rarity })
d.notify(player, ("🏪 %s выставлена за %d ⚪"):format(item.name, price), GREEN)
changed(player)
return true, lid
end
function Market.buy(buyer, lid, expected)
local data = d.profiles[buyer]
local L = type(lid) == "string" and listings[lid]
if not data then
return false, "no data"
end
if not Market.enabled() then
return fail(buyer, "🏪 Рынок сейчас закрыт")
end
if not L or L.state ~= "open" then
return fail(buyer, "Лот уже продан или снят")
end
if L.seller == buyer then
return fail(buyer, "Это твой лот")
end
if not L.seller.Parent or not d.profiles[L.seller] then
return fail(buyer, "Продавец ушёл с сервера")
end
if not Market.access(data) then
return fail(buyer, ("🔒 Рынок — с %d уровня"):format(Config.Market.minLevel))
end
if fishWorldLevel(L.item.id) > (data.level or 1) then
return fail(buyer, "🔒 Эта рыба из мира, который тебе ещё не открыт")
end
if validPrice(expected) ~= L.price then
return fail(buyer, "Цена изменилась — открой рынок заново")
end
if data.coins < L.price then
return fail(buyer, ("Нужно %d ⚪"):format(L.price))
end
local m = Market.ensure(data)
-- 1) блокировка и списание (durable)
L.state, L.buyer = "locked", buyer
busy(buyer, 1)
busy(L.seller, 1)
data.coins -= L.price
m.pending[lid] = { price = L.price, sellerId = L.sellerId, sellerName = L.sellerName, item = table.clone(L.item), t = d.now() }
if not d.save(buyer) then
data.coins += L.price
m.pending[lid] = nil
L.state, L.buyer = "open", nil
busy(buyer, -1)
busy(L.seller, -1)
changed(buyer)
return fail(buyer, "Не удалось сохранить — серебро не списано, попробуй ещё раз")
end
d.telemetry.silver(buyer, false, L.price, data.coins, "MarketBuy", L.item.id)
-- 2) фиксация в журнале
local ok, rec = d.ledger.cas(lid, {
s = "sold", buyer = buyer.UserId, seller = L.sellerId, price = L.price, fee = L.fee, t = d.now(),
})
if not ok or not rec then
L.state = "pending"
dirty = true
d.notify(buyer, "⏳ Сделка подтверждается… серебро вернётся, если она не пройдёт", GOLD)
resolveLater(L) -- снимет busy сам
return false, "pending"
end
settle(L, rec)
busy(buyer, -1)
busy(L.seller, -1)
return rec.s == "sold" and rec.buyer == buyer.UserId, rec.s
end
-- reason: "manual" | "expired" | "leave"
function Market.cancel(player, lid, reason)
local L = type(lid) == "string" and listings[lid]
if not L or L.seller ~= player then
return false, "no listing"
end
if L.state ~= "open" then
if reason == "manual" then
fail(player, "Лот сейчас покупают — подожди")
end
return false, "busy"
end
L.state = "cancelling"
busy(player, 1)
local ok, rec = d.ledger.cas(lid, { s = "cancelled", t = d.now() })
busy(player, -1)
if not ok or not rec then
if reason == "leave" then
-- залог останется в сохранении — его разберёт recover при следующем входе
listings[lid] = nil
dirty = true
return false, "deferred"
end
L.state = "open"
if reason == "manual" then
fail(player, "Не удалось снять лот — попробуй ещё раз")
end
return false, "error"
end
settle(L, rec)
if rec.s == "cancelled" and reason == "expired" then
d.notify(player, ("🏪 Лот «%s» снят по времени, рыба вернулась"):format(L.item.name), Color3.fromRGB(255, 200, 120))
end
return true, rec.s
end
function Market.claim(player)
local data = d.profiles[player]
if not data then
return 0
end
local m = Market.ensure(data)
local cap = d.bagCapacity(player, data)
local moved = 0
while #m.inbox > 0 and #data.items < cap do
table.insert(data.items, table.remove(m.inbox, 1))
moved += 1
end
if moved == 0 then
fail(player, #m.inbox > 0 and "🎒 Сумка полна" or "Посылок нет")
else
d.notify(player, ("📦 В сумку: %d"):format(moved), GREEN)
changed(player)
end
return moved
end
---------------------------------------------------------------- вход, выход, таймер
-- при входе (до того, как профиль станет живым): разобрать незавершённые сделки по журналу.
-- Возвращает true, если что-то изменилось; незавершённое (журнал не ответил) остаётся до следующего раза
function Market.recover(player, data)
local m = Market.ensure(data)
if not d or not d.ledger then
return false
end
local changedAny = false
for lid, e in pairs(table.clone(m.escrow)) do
local ok, rec = d.ledger.cas(lid, { s = "cancelled", t = d.now() })
if ok and rec then
if rec.s == "sold" then
applySale(data, lid, rec, player)
else
m.escrow[lid] = nil
deliver(player, data, e.item)
end
changedAny = true
end
end
for lid, p in pairs(table.clone(m.pending)) do
local ok, rec = d.ledger.cas(lid, { s = "cancelled", t = d.now() })
if ok and rec then
if rec.s == "sold" and rec.buyer == player.UserId then
applyPurchase(player, data, lid, rec)
else
refund(data, lid)
end
changedAny = true
end
end
return changedAny
end
-- есть ли неразобранные сделки (повторить recover позже)
function Market.unresolved(data)
local m = Market.ensure(data)
return next(m.escrow) ~= nil or next(m.pending) ~= nil
end
-- выход игрока: дождаться незавершённых операций (до timeout сек), снять его лоты. Вызывать ДО сохранения
function Market.onLeave(player, timeout)
local t0 = os.clock()
while inflight[player] and os.clock() - t0 < (timeout or 20) do
d.wait(0.1)
end
for lid, L in pairs(table.clone(listings)) do
if L.seller == player then
Market.cancel(player, lid, "leave")
end
end
lastAction[player] = nil
dirty = true
end
function Market.tick()
local now = d.now()
for lid, L in pairs(table.clone(listings)) do
if L.state == "open" and now >= L.expires then
task.spawn(Market.cancel, L.seller, lid, "expired")
end
end
end
---------------------------------------------------------------- для клиента
local function itemView(it)
return {
uid = it.uid, id = it.id, name = it.name, rarity = it.rarity, weight = it.weight, value = it.value, mutation = it.mutation,
caughtBy = it.origin and it.origin.name, bought = it.bought and { fromName = it.bought.fromName, price = it.bought.price } or nil,
}
end
function Market.snapshot(player)
local data = d.profiles[player]
local list = {}
for _, L in pairs(listings) do
if L.state == "open" or L.seller == player then
table.insert(list, {
id = L.id, sellerName = L.sellerName, mine = L.seller == player, price = L.price, fee = L.fee,
proceeds = L.proceeds, expires = L.expires, state = L.state, item = itemView(L.item),
worldLevel = fishWorldLevel(L.item.id),
})
end
end
table.sort(list, function(a, b)
return a.price > b.price
end)
local inbox = {}
local pending = 0
if data then
local m = Market.ensure(data)
for i, it in ipairs(m.inbox) do
inbox[i] = itemView(it)
end
for _ in pairs(m.pending) do
pending += 1
end
end
return {
enabled = Market.enabled(), access = data and Market.access(data) or false, level = data and data.level or 1,
listings = list, inbox = inbox, pending = pending, now = d.now(),
}
end
function Market.broadcast(players)
dirty = false
for _, p in ipairs(players) do
if d.profiles[p] then
d.send(p, Market.snapshot(p))
end
end
end
function Market.isDirty()
return dirty
end
-- действия от клиента (с ограничением частоты)
function Market.onAction(player, action, a, b)
if action == "MarketState" then
d.send(player, Market.snapshot(player))
return true
end
if action ~= "MarketList" and action ~= "MarketBuy" and action ~= "MarketCancel" and action ~= "MarketClaim" then
return false
end
if cooldown(player) then
return true
end
if action == "MarketList" then
Market.list(player, a, b)
elseif action == "MarketBuy" then
Market.buy(player, a, b)
elseif action == "MarketCancel" then
Market.cancel(player, a, "manual")
elseif action == "MarketClaim" then
Market.claim(player)
end
d.send(player, Market.snapshot(player))
return true
end
-- для тестов
function Market._listings()
return listings
end
function Market._inflight()
return inflight
end
return Market
+94
View File
@@ -0,0 +1,94 @@
-- PlayerStore (ModuleScript) -> ServerScriptService
-- Сохранение профилей с замком сессии (нужен для рынка и вообще против дюпа между серверами).
-- load: UpdateAsync ставит в сохранение _lock = { job, t }. Если замок чужой и свежий (другой сервер ещё
-- держит игрока) — ждём и пробуем снова; не дождались — "locked" (игрока не пускаем, данные не трогаем).
-- save: UpdateAsync пишет данные, только если замок наш (или устарел); иначе "lost" — профиль уже
-- загружен другим сервером, писать поверх нельзя. release = true снимает замок (выход игрока).
-- Сохранения одного ключа идут строго по очереди (автосейв и выход не перегоняют друг друга).
-- Хранилище передаётся снаружи (DataStore или подделка в тестах): нужен только :UpdateAsync(key, fn).
local PlayerStore = {}
PlayerStore.__index = PlayerStore
-- opts: { jobId, staleAfter (сек), now = fn, wait = fn(sec), loadTries }
function PlayerStore.new(store, opts)
opts = opts or {}
return setmetatable({
store = store,
jobId = opts.jobId or game.JobId,
staleAfter = opts.staleAfter or 600,
now = opts.now or os.time,
wait = opts.wait or task.wait,
loadTries = opts.loadTries or 6,
busy = {},
}, PlayerStore)
end
function PlayerStore:foreignLock(saved)
local lock = type(saved) == "table" and saved._lock
return type(lock) == "table" and lock.job ~= self.jobId and self.now() - (tonumber(lock.t) or 0) < self.staleAfter
end
-- status: "ok" | "locked" | "error"; value — таблица сохранения (или nil у нового игрока)
function PlayerStore:load(key)
local lastErr
for attempt = 1, self.loadTries do
local value, locked = nil, false
local ok, err = pcall(function()
self.store:UpdateAsync(key, function(saved)
if self:foreignLock(saved) then
locked = true
return nil -- не трогаем: данные ещё у другого сервера
end
locked = false
if type(saved) ~= "table" then
saved = {}
end
saved._lock = { job = self.jobId, t = self.now() }
value = saved
return saved
end)
end)
if ok and not locked then
return "ok", value
end
lastErr = err
if attempt < self.loadTries then
self.wait(locked and 5 or 2)
end
if attempt == self.loadTries and locked then
return "locked", nil
end
end
return "error", lastErr
end
-- ok, status ("ok" | "lost" | "error")
function PlayerStore:save(key, data, release)
while self.busy[key] do
self.wait(0.1)
end
self.busy[key] = true
local lost = false
local ok, err = pcall(function()
self.store:UpdateAsync(key, function(saved)
if self:foreignLock(saved) then
lost = true
return nil
end
lost = false
data._lock = (not release) and { job = self.jobId, t = self.now() } or nil
return data
end)
end)
self.busy[key] = nil
if not ok then
return false, "error", err
end
if lost then
return false, "lost"
end
return true, "ok"
end
return PlayerStore
+179
View File
@@ -0,0 +1,179 @@
-- Potions (ModuleScript) -> ServerScriptService
-- Сумка зелий и действующее зелье (экономика v2). Чистая логика над данными игрока, без Roblox-сервисов:
-- GameServer вызывает отсюда покупку, питьё, трату попытки и тиканье времени; тесты — tests/potions.spec.lua.
--
-- data.potions = { inv = { [id] = штук }, active = { id, left, luck? } | nil }
-- left — оставшиеся попытки (charges) или секунды (duration). luck у активного — только у перенесённого
-- старого зелья (его сила хранится в данных, а не в Config).
-- Правила:
-- * одно действующее зелье; другое можно выпить только с явным подтверждением замены — остаток прежнего
-- пропадает (клиент показывает, сколько именно);
-- * то же зелье поверх — добавляет попытки (не больше Config.PotionMaxCharges) или время;
-- * слабое никогда не продлевает сильное: продлевает только то же самое зелье;
-- * попытка тратится при поклёвке (consumeAttempt), а не при забросе: отмена до поклёвки бесплатна,
-- а узнать редкость по поклёвке и отменить без траты нельзя.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Config = require(ReplicatedStorage:WaitForChild("FishConfig"))
local Potions = {}
function Potions.def(id)
if type(id) ~= "string" then
return nil
end
return Config.Find(Config.Potions, id)
end
function Potions.ensure(data)
if type(data.potions) ~= "table" then
data.potions = {}
end
local p = data.potions
if type(p.inv) ~= "table" then
p.inv = {}
end
if p.active ~= nil and (type(p.active) ~= "table" or not Potions.def(p.active.id) or (tonumber(p.active.left) or 0) <= 0) then
p.active = nil
end
return p
end
-- в сумку зелий (покупка, награда, донат); пить — отдельно
function Potions.add(data, id, count)
local def = Potions.def(id)
count = math.floor(tonumber(count) or 1)
if not def or def.legacy or count <= 0 then
return false
end
local p = Potions.ensure(data)
p.inv[id] = (p.inv[id] or 0) + count
return true
end
function Potions.count(data, id)
local p = Potions.ensure(data)
return p.inv[id] or 0
end
-- действующее зелье: def, active (или nil)
function Potions.active(data)
local p = Potions.ensure(data)
local a = p.active
if not a then
return nil, nil
end
return Potions.def(a.id), a
end
-- что сейчас даёт зелье (пустая таблица — ничего)
function Potions.effect(data)
local def, a = Potions.active(data)
if not def then
return {}
end
return {
id = def.id,
zone = def.zone or 0,
weightCurve = def.weightCurve,
newSpecies = def.newSpecies,
mutation = def.mutation or 1,
speed = def.speed or 1,
luck = a.luck or def.luck or 0,
}
end
-- выпить: ok, code, info
-- code: "unknown" | "none" (нет в сумке) | "needConfirm" (действует другое — нужен confirmReplace) |
-- "started" | "extended" | "replaced"
-- info: { lostId, lostLeft } — что пропало при замене
function Potions.activate(data, id, confirmReplace)
local def = Potions.def(id)
if not def or def.legacy then
return false, "unknown"
end
local p = Potions.ensure(data)
if (p.inv[id] or 0) <= 0 then
return false, "none"
end
local amount = def.charges or def.duration or 0
local cur = p.active
if cur and cur.id == id then
local cap = def.charges and Config.PotionMaxCharges or math.huge
if cur.left >= cap then
return false, "full"
end
cur.left = math.min(cap, cur.left + amount)
p.inv[id] -= 1
if p.inv[id] <= 0 then
p.inv[id] = nil
end
return true, "extended"
end
local info = nil
if cur then
if confirmReplace ~= true then
return false, "needConfirm", { activeId = cur.id, left = cur.left }
end
info = { lostId = cur.id, lostLeft = cur.left }
end
p.inv[id] -= 1
if p.inv[id] <= 0 then
p.inv[id] = nil
end
p.active = { id = id, left = amount }
return true, info and "replaced" or "started", info
end
-- поклёвка: тратим 1 попытку, если действует то же зелье, что было при забросе (id из снимка при забросе)
function Potions.consumeAttempt(data, idAtCast)
local def, a = Potions.active(data)
if not def or not def.charges or a.id ~= idAtCast then
return false
end
a.left -= 1
if a.left <= 0 then
data.potions.active = nil
end
return true
end
-- секунды игры для зелий на время (донат и перенесённые)
function Potions.tick(data, seconds)
local def, a = Potions.active(data)
if not def or def.charges then
return false
end
a.left -= seconds
if a.left <= 0 then
data.potions.active = nil
return true -- закончилось
end
return false
end
-- перенос старого зелья удачи (boostUntil / boostBonus — настенное время до v2): остаток секунд как есть,
-- теперь тикает только в игре — игрок ничего не теряет
function Potions.migrateLegacy(data, now)
local p = Potions.ensure(data)
local untilT, bonus = tonumber(data.boostUntil) or 0, tonumber(data.boostBonus) or 0
if untilT > now and bonus > 0 and not p.active then
p.active = { id = "Legacy", left = math.floor(untilT - now), luck = bonus }
end
data.boostUntil, data.boostBonus = 0, 0
end
-- для атрибутов клиента: "Focus:2,Trophy:1"
function Potions.encode(data)
local p = Potions.ensure(data)
local parts = {}
for _, def in ipairs(Config.Potions) do
local n = p.inv[def.id]
if n and n > 0 then
table.insert(parts, def.id .. ":" .. n)
end
end
return table.concat(parts, ",")
end
return Potions
+82
View File
@@ -0,0 +1,82 @@
-- Progression (ModuleScript) -> ServerScriptService
-- Опыт карьеры и миграция сохранений на экономику v2. Чистая логика над данными игрока (тесты — tests/*.spec.lua).
--
-- Источник опыта карьеры один: успешная ручная поимка — Config.CareerXP(мир). Всё остальное (задания, босс,
-- коллекция, первая поимка, серия, отдых, мутации, автоловля, ловушки, рынок) опыта карьеры не даёт.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Config = require(ReplicatedStorage:WaitForChild("FishConfig"))
local Potions = require(script.Parent:WaitForChild("Potions"))
local Progression = {}
-- опыт за поимку: ctx = { auto = bool, bought = bool }
function Progression.catchXP(worldId, ctx)
if ctx and (ctx.auto or ctx.bought) then
return ctx.auto and Config.Economy.autoXP or 0
end
return Config.CareerXP(worldId)
end
-- добавить опыт; возвращает список новых уровней (обычно пустой или из одного)
function Progression.addXp(data, amount)
amount = math.max(0, math.floor(tonumber(amount) or 0))
data.xp = (tonumber(data.xp) or 0) + amount
local levels = {}
-- предохранитель: даже ошибочная большая награда поднимет не больше 3 уровней за раз,
-- остальное копится внутри уровня
while data.xp >= Config.XPForLevel(data.level) and #levels < 3 do
data.xp -= Config.XPForLevel(data.level)
data.level += 1
table.insert(levels, data.level)
end
return levels
end
-- уникальный id рыбы и происхождение (кто поймал, где, когда) — для рынка и истории
function Progression.stamp(item, userId, name, worldId, now)
if type(item) ~= "table" then
return
end
if type(item.gid) ~= "string" then
item.gid = ("%d-%d"):format(userId, tonumber(item.uid) or 0)
end
if type(item.origin) ~= "table" then
local _, zoneId = Config.FindFish(item.id)
item.origin = { by = userId, name = name, world = worldId or zoneId, t = now }
end
end
-- миграция сохранения на экономику v2. Идемпотентна: повторный вызов ничего не меняет.
-- Сохраняет уровень, снасти, валюты, пропуска, коллекцию; не удаляет и не изымает ничего.
-- ctx = { now, userId, name }; возвращает true, если что-то перенесено
function Progression.migrate(data, ctx)
local ver = tonumber(data.econ) or 1
if ver >= Config.Economy.version then
Potions.ensure(data)
return false
end
local now = ctx.now or os.time()
-- 1) опыт: уровень тот же, доля заполнения текущего уровня переносится в новый порог
local lvl = math.max(1, math.floor(tonumber(data.level) or 1))
local oldXp = math.max(0, tonumber(data.xp) or 0)
local frac = math.clamp(oldXp / math.max(1, Config.Economy.legacyXP(lvl)), 0, 0.999)
data.level = lvl
data.xp = math.floor(frac * Config.XPForLevel(lvl))
-- 2) зелье удачи по настенному времени → действующее зелье с тем же остатком секунд
Potions.migrateLegacy(data, now)
-- 3) рыба в сумке: id и происхождение (цены пойманной рыбы не меняем — продаётся как была поймана)
if type(data.items) == "table" then
for _, it in ipairs(data.items) do
Progression.stamp(it, ctx.userId or 0, ctx.name, nil, nil)
it.origin.legacy = true
end
end
-- 4) отдых теперь +25% серебра вместо ×2 опыта: секунды сохраняются
data.rest = math.max(0, tonumber(data.rest) or 0)
data.econ = Config.Economy.version
data.migration = { from = ver, at = now, xpBefore = oldXp, xpAfter = data.xp, level = lvl }
return true
end
return Progression
+112
View File
@@ -0,0 +1,112 @@
-- Telemetry (ModuleScript) -> ServerScriptService
-- Серверная телеметрия экономики (Roblox Analytics): источники и траты серебра, опыт карьеры по источникам,
-- уровни, зелья, рынок. Без событий на каждый кадр и без лишних личных данных (только то, что требует
-- AnalyticsService: игрок, сумма, баланс, тип).
-- * серебро — LogEconomyEvent на каждую операцию (продажа, награда, покупка) — их немного;
-- * опыт — копится по источникам и уходит одним событием на источник раз в FLUSH секунд и при выходе;
-- * уровни — LogProgressionCompleteEvent; зелья и рынок — LogCustomEvent.
-- Итоги сервера доступны в Studio: ServerStorage.EconomyDebug:Invoke("telemetry")
local AnalyticsService = game:GetService("AnalyticsService")
local RunService = game:GetService("RunService")
local Telemetry = {}
local FLUSH = 300
local CURRENCY = "Silver"
local xpBuf = {} -- [player] = { [source] = amount }
local totals = { silverIn = {}, silverOut = {}, xp = {}, custom = {} }
local function bump(t, k, v)
t[k] = (t[k] or 0) + v
end
local function fields(f)
if not f then
return nil
end
local keys = { Enum.AnalyticsCustomFieldKeys.CustomField01.Name, Enum.AnalyticsCustomFieldKeys.CustomField02.Name, Enum.AnalyticsCustomFieldKeys.CustomField03.Name }
local out = {}
for i, v in ipairs(f) do
if keys[i] then
out[keys[i]] = tostring(v)
end
end
return out
end
-- source: "Sell", "Quest", "Chain", "Boss", "Daily", "Order", "Collection", "Product", "MarketSale", "MarketRefund"
-- sink: "Rod", "Bag", "Upgrade", "Potion", "Bait", "MarketBuy"
function Telemetry.silver(player, isSource, amount, balance, kind, sku)
amount = math.floor(tonumber(amount) or 0)
if amount <= 0 or not player then
return
end
bump(isSource and totals.silverIn or totals.silverOut, kind, amount)
local tType = (kind == "Product") and Enum.AnalyticsEconomyTransactionType.IAP.Name
or (isSource and (kind == "Daily" and Enum.AnalyticsEconomyTransactionType.TimedReward.Name or Enum.AnalyticsEconomyTransactionType.Gameplay.Name))
or Enum.AnalyticsEconomyTransactionType.Shop.Name
pcall(function()
AnalyticsService:LogEconomyEvent(player, isSource and Enum.AnalyticsEconomyFlowType.Source or Enum.AnalyticsEconomyFlowType.Sink,
CURRENCY, amount, math.max(0, math.floor(balance or 0)), tType, sku or kind)
end)
end
function Telemetry.xp(player, source, amount)
if not player or (amount or 0) <= 0 then
return
end
bump(totals.xp, source, amount)
xpBuf[player] = xpBuf[player] or {}
bump(xpBuf[player], source, amount)
end
function Telemetry.level(player, level)
bump(totals.custom, "LevelUp", 1)
pcall(function()
AnalyticsService:LogProgressionCompleteEvent(player, "Career", level)
end)
end
function Telemetry.event(player, name, value, f)
bump(totals.custom, name, value or 1)
pcall(function()
AnalyticsService:LogCustomEvent(player, name, value or 1, fields(f))
end)
end
function Telemetry.flush(player)
local buf = xpBuf[player]
xpBuf[player] = nil
if not buf then
return
end
for source, amount in pairs(buf) do
pcall(function()
AnalyticsService:LogCustomEvent(player, "CareerXP", amount, fields({ source }))
end)
end
end
function Telemetry.summary()
return totals
end
task.spawn(function()
while true do
task.wait(FLUSH)
for p in pairs(xpBuf) do
if p.Parent then
Telemetry.flush(p)
else
xpBuf[p] = nil
end
end
end
end)
if RunService:IsStudio() then
Telemetry.studio = true
end
return Telemetry