diff --git a/docs/economy-v3-retention.md b/docs/economy-v3-retention.md new file mode 100644 index 0000000..b4a3f7a --- /dev/null +++ b/docs/economy-v3-retention.md @@ -0,0 +1,54 @@ +# Экономика v3: удержание игроков и дома + +Дата: 2026-11-13. Основа — экономика v2 ([economy-v2.md](economy-v2.md)), которую команда уже реализовала. +v3 её не переписывает: карьера по-прежнему растёт только от ручной ловли, доход 60 / 120 / 240 ⚪ в минуту. +Цифры ниже — расчёт по формулам, не замер игроков. + +## 1. Что найдено + +| Проблема | Где | Почему плохо | +|---|---|---| +| Дома дорожали ×10 за уровень: 5 000 → 50 000 → … → 5 000 000 000 000 | `HouseConfig.cost` | при доходе 240 ⚪/мин 3-й уровень — 35 ч, 4-й — 350 ч; дальше недостижимо | +| Крутка украшения стоила 1 000–10 000 ⚪, мифика 0,5% | `HouseCosmetics` | золотая крыша в среднем ≈ 2 млн ⚪; ни гарантии, ни смысла крутить | +| Дом ничего не давал | `Houses` | нет причины возвращаться на остров после постройки | +| Новый уровень — только цифра | `addXp` | уровни стали длинными (Мир 2 ≈ 2 ч), а награды за них нет | +| Пропуск дня сбрасывал ежедневку на 1-й день | `claimDaily` | противоречит задумке v2 «пропуск не наказывает»; бьёт по возвращающимся | +| Нет наград за длинную сессию | — | у популярных игр Roblox это базовый крючок удержания | +| Жемчугу почти некуда тратиться | наживка, переброс заказа | валюта копится без смысла (см. «Что осталось») | + +## 2. Что изменено + +### Дома (`HouseConfig.lua`, `HouseCosmetics.lua`, `Houses.lua`) +* **Цены уровней**: 1 500 / 3 500 / 7 000 / 12 000 / 20 000 / 32 000 / 50 000 / 75 000 / 110 000 / 160 000 (всего ≈ 470 000). + Первый дом — ~25 минут игры в Мире 1, дворец — долгая цель Мира 3. +* **Аренда**: дом приносит 40 ⚪ × уровень в час, копится и офлайн до 12 часов, забирается автоматически при входе + на свой участок. Дворец — до 4 800 ⚪ в день. Повод заглядывать домой каждый день, окупаемость уровней — дни, а не часы. +* **Крутки**: кусты 150, двери/окна 350, пол 500, крыша 900 ⚪. Повтор возвращает 35% (было 20%). +* **Гарантия**: 10 круток подряд без «Эпического» в категории — следующая не ниже «Эпического». + +### Карьера и ежедневное (`FishConfig.lua`, `GameServer.server.lua`) +* **Награда за уровень**: серебро = 20 × уровень; каждые 5 уровней +5 🦪 и зелье; рубежи: + ур. 3 — червь и «Исследователь»; ур. 8 (Мир 2) — 500 ⚪, мотыль, «Трофей»; ур. 13 — 1 000 ⚪, светлячок; + ур. 18 (Мир 3) — 2 000 ⚪, кровавая приманка, «Мутации»; ур. 25 — 5 000 ⚪, 20 🦪, «Мутации». + Опыта награды не дают — темп уровней тот же. +* **Подарки за время в игре** (`Config.PlaytimeGifts`): 5 / 15 / 30 / 45 / 60 / 90 / 120 минут — серебро, наживка, + зелья, жемчуг. Приходят сами, без кнопки; атрибут игрока `GiftNextAt` — время следующего подарка. +* **Ежедневка без сброса**: пропуск дня продолжает круг со следующего дня. + +## 3. Почему так (что взято у популярных игр Roblox) + +* Fisch: прогресс медленный, но каждая новая удочка — заметный рубеж; деньги — в основном продажа рыбы, долгосрочный + доход — мутации. У нас то же, плюс рубежи уровней теперь тоже ощущаются. +* Pet Simulator, Bee Swarm и др.: подарки за время в сессии и ежедневка без жёсткого штрафа — главные крючки возврата. +* Gacha-украшения с гарантией: случайность остаётся, но неудача не бесконечна — меньше раздражения, больше круток. +* Пассивный доход «пока тебя нет» (аренда) — причина зайти завтра, ограниченная потолком, чтобы не заменять игру. + +## 4. Что осталось и рекомендации + +1. **Таймер подарка в интерфейсе** — сервер выставляет `GiftNextAt`, нужна маленькая плашка «🎁 через 3:12» в HUD. +2. **Аренда в окне дома** — показать «копится X ⚪ / ч, накоплено Y». +3. **Жемчуг** — добавить траты: крутка украшений за жемчуг, редкие украшения/витрины только за жемчуг. +4. **Витрина коллекции в доме** — трофеи пойманных видов на стенах (задумка «показывать свою коллекцию»). +5. **Еженедельные задания** и временные события с особой рыбой — среднесрочные цели между ежедневкой и уровнями. +6. **Замер темпа** (рыб/мин) по телеметрии до любых правок кривой опыта — v2 рассчитана на 4 рыбы/мин. +7. Наборы серебра за Robux растут с уровнем (см. economy-v2 §10) — решение за вами. diff --git a/src/ReplicatedFirst/Loading.client.lua b/src/ReplicatedFirst/Loading.client.lua index acca78f..be1225a 100644 --- a/src/ReplicatedFirst/Loading.client.lua +++ b/src/ReplicatedFirst/Loading.client.lua @@ -45,7 +45,7 @@ local gui = new("ScreenGui", { -- фон: заставка «Рыболовная лихорадка»; пока картинка грузится, виден голубой градиент. -- Градиент — на отдельной подложке: UIGradient на самой CanvasGroup тонирует всё содержимое и затемнял картинку. -- Свет и цветокоррекция сцены на экранный интерфейс не действуют, их не трогаем. -local BG_IMAGE = "rbxassetid://82266337853896" -- осветлённая и более насыщенная версия заставки +local BG_IMAGE = "" -- картинки — в ReplicatedStorage.UiImages (loading_common, loading_tropics), ставятся ниже -- обычный Frame, а не CanvasGroup: CanvasGroup рендерит содержимое в текстуру пониженного разрешения — картинка мылится. -- Плавное появление/исчезновение делаем сами (setFade ниже). local root = new("Frame", { Size = UDim2.fromScale(1, 1), BackgroundTransparency = 1, BorderSizePixel = 0, Parent = gui }) @@ -59,8 +59,28 @@ local bg = new("ImageLabel", { Size = UDim2.fromScale(1, 1), BackgroundTransparency = 1, Image = BG_IMAGE, ScaleType = Enum.ScaleType.Crop, Parent = root, }) +-- затемнение снизу: плашка читается на любой картинке +local shade = new("Frame", { Size = UDim2.fromScale(1, 0.45), AnchorPoint = Vector2.new(0, 1), Position = UDim2.fromScale(0, 1), + BackgroundColor3 = Color3.new(0, 0, 0), BorderSizePixel = 0, Parent = root }) +new("UIGradient", { Rotation = 90, Transparency = NumberSequence.new(1, 0.35), Parent = shade }) +-- картинка по месту назначения: тропики — своя, остальное (лобби, миры, «Мой дом») — общая заставка +local IMAGES = {} +local function pickImage() + local t = gui:GetAttribute("Target") + local id = (t == "World2" and IMAGES.tropics) or IMAGES.common + if id and bg.Image ~= id then + bg.Image = id + task.spawn(function() + pcall(function() game:GetService("ContentProvider"):PreloadAsync({ bg }) end) + end) + end +end task.spawn(function() - pcall(function() game:GetService("ContentProvider"):PreloadAsync({ bg }) end) + local ok, UI = pcall(function() return require(ReplicatedStorage:WaitForChild("UiImages", 30)) end) + if ok and UI then + IMAGES.common, IMAGES.tropics = UI.get("loading_common"), UI.get("loading_tropics") + pickImage() + end end) -- плашка снизу: куда идём, полоска загрузки, совет @@ -100,6 +120,31 @@ local tip = new("TextLabel", { Font = Enum.Font.GothamMedium, Parent = panel, }) +-- оформление ui3 (резная рамка, кованая полоса, шрифты с кириллицей): картинки ставятся, когда загрузится UiImages +local panelSkin = new("ImageLabel", { Size = UDim2.new(1, 16, 1, 16), Position = UDim2.fromOffset(-8, -8), BackgroundTransparency = 1, + ScaleType = Enum.ScaleType.Slice, SliceCenter = Rect.new(64, 64, 192, 192), SliceScale = 0.45, ZIndex = 0, Parent = panel }) +local barSkin = new("ImageLabel", { Size = UDim2.new(1, 14, 1, 14), Position = UDim2.fromOffset(-7, -7), BackgroundTransparency = 1, + ScaleType = Enum.ScaleType.Slice, SliceCenter = Rect.new(52, 24, 332, 40), SliceScale = 0.35, ZIndex = 2, Parent = barBack }) +title.FontFace = Font.new("rbxasset://fonts/families/Merriweather.json", Enum.FontWeight.Heavy) +tip.FontFace = Font.new("rbxasset://fonts/families/Nunito.json", Enum.FontWeight.Bold) +task.spawn(function() + local ok, UI = pcall(function() return require(ReplicatedStorage:WaitForChild("UiImages", 30)) end) + if not (ok and UI and UI.get("frame_small")) then + return + end + panelSkin.Image = UI.get("frame_small") + barSkin.Image = UI.get("bar_frame") + bar.ZIndex = 3 -- заливка поверх кованой рамки (у рамки непрозрачный жёлоб) + panel.BackgroundTransparency = 1 + panel:SetAttribute("NoFade", true) -- фон плашки теперь — картинка + for _, c in ipairs(panel:GetChildren()) do + if c:IsA("UIStroke") or c:IsA("UIGradient") then + c.Enabled = false + end + end + barBack.BackgroundTransparency = 0.3 +end) + local rng = Random.new() local function showTip() tip.Text = "💡 " .. TIPS[rng:NextInteger(1, #TIPS)] @@ -124,7 +169,9 @@ local fadeValue = Instance.new("NumberValue") -- 0 — экран виден, 1 local function setFade(a) for o, orig in pairs(fadeItems) do for prop, v in pairs(orig) do - o[prop] = v + (1 - v) * a + if not (prop == "BackgroundTransparency" and o:GetAttribute("NoFade")) then + o[prop] = v + (1 - v) * a + end end end end @@ -208,6 +255,7 @@ gui:GetAttributeChangedSignal("Visible"):Connect(function() fadeTo(0, 0.25) end end) +gui:GetAttributeChangedSignal("Target"):Connect(pickImage) gui:GetAttributeChangedSignal("Title"):Connect(function() title.Text = gui:GetAttribute("Title") or "" end) diff --git a/src/ReplicatedStorage/FishConfig.lua b/src/ReplicatedStorage/FishConfig.lua index 7f4263d..0485c5c 100644 --- a/src/ReplicatedStorage/FishConfig.lua +++ b/src/ReplicatedStorage/FishConfig.lua @@ -523,7 +523,8 @@ Config.Boss = { }, } --- ежедневная награда (7 дней по кругу): серебро × tier мира, зелья — в сумку зелий; пропуск дня не наказывает +-- ежедневная награда (7 дней по кругу): серебро × tier мира, зелья — в сумку зелий; пропуск дня не наказывает: +-- круг продолжается с того дня, на котором игрок остановился (не сбрасывается на 1-й) Config.DailyRewards = { { coins = 60 }, { coins = 90 }, @@ -534,6 +535,36 @@ Config.DailyRewards = { { coins = 400, potion = "Mutation" }, } +---------------------------------------------------------------- награды за уровень +-- опыт по-прежнему даёт только ручная поимка (уровни стали длинными: Мир 2 ≈ 2 ч), поэтому каждый новый уровень +-- что-то приносит, а не только цифру: серебро, каждые 5 уровней — жемчуг и зелье, на рубежах — наживка и крупный бонус. +-- Сумма за ур. 2…25 ≈ 25 минут обычного дохода — ускоряет покупки, но не уровни. Опыта награды не дают. +Config.LevelRewards = { + coinsPerLevel = 20, -- серебро = уровень × это + every = 5, everyPearls = 5, everyPotion = "Focus", + milestones = { + [3] = { bait = "Worm", potion = "Research" }, + [8] = { coins = 500, bait = "Larva", potion = "Trophy" }, -- открыт Мир 2 + [13] = { coins = 1000, bait = "Firefly" }, + [18] = { coins = 2000, bait = "Blood", potion = "Mutation" }, -- открыт Мир 3 + [25] = { coins = 5000, pearls = 20, potion = "Mutation" }, + }, +} + +---------------------------------------------------------------- подарки за время в игре +-- за непрерывную игру в этот заход (минуты): маленькие подарки, которые растут к концу. Счётчик начинается +-- заново при каждом входе. Подарок приходит сам (без кнопки), атрибут GiftNextAt — для таймера в интерфейсе. +-- coins × tier мира; bait — пачка наживки; potion — в сумку зелий +Config.PlaytimeGifts = { + { minutes = 5, coins = 40 }, + { minutes = 15, bait = "Worm" }, + { minutes = 30, potion = "Focus" }, + { minutes = 45, coins = 150 }, + { minutes = 60, pearls = 3 }, + { minutes = 90, bait = "Larva", coins = 200 }, + { minutes = 120, potion = "Trophy", pearls = 3 }, +} + ---------------------------------------------------------------- события на сервере Config.Events = { { id = "Bite", name = "⚡ Клёвый час", desc = "Рыба клюёт на 15% быстрее", duration = 180, speed = 0.85 }, diff --git a/src/ReplicatedStorage/HouseConfig.lua b/src/ReplicatedStorage/HouseConfig.lua index 6b2c2c8..3bd3e88 100644 --- a/src/ReplicatedStorage/HouseConfig.lua +++ b/src/ReplicatedStorage/HouseConfig.lua @@ -5,8 +5,13 @@ local H = {} H.MaxLevel = 10 -H.BaseCost = 5000 -- цена 1-го уровня -H.Mult = 10 -- каждый следующий уровень дороже предыдущего в 10 раз +-- цены уровней под доход 60 / 120 / 240 ⚪ в минуту (экономика v2): первый дом — ~25 минут игры в Мире 1, +-- дворец — долгая цель Мира 3. Раньше было ×10 за уровень (5 000 … 5 трлн): выше 3-го уровня не доходил никто +H.Costs = { 1500, 3500, 7000, 12000, 20000, 32000, 50000, 75000, 110000, 160000 } + +-- аренда: дом приносит серебро, пока хозяина нет (копится и офлайн), забирается при входе на свой участок. +-- perHour × уровень дома в час, не больше maxHours часов — повод заглядывать домой раз в день +H.Rent = { perHour = 40, maxHours = 12 } H.Names = { "Хижина", @@ -21,9 +26,14 @@ H.Names = { "Дворец", } --- цена покупки уровня level (1..MaxLevel): 5 000, 50 000, 500 000 … +-- цена покупки уровня level (1..MaxLevel) function H.cost(level) - return H.BaseCost * H.Mult ^ (level - 1) + return H.Costs[level] or H.Costs[#H.Costs] +end + +-- серебра в час аренды для дома уровня level +function H.rentPerHour(level) + return (level or 0) * H.Rent.perHour end function H.name(level) diff --git a/src/ReplicatedStorage/HouseCosmetics.lua b/src/ReplicatedStorage/HouseCosmetics.lua index f5af1e3..9a62394 100644 --- a/src/ReplicatedStorage/HouseCosmetics.lua +++ b/src/ReplicatedStorage/HouseCosmetics.lua @@ -19,13 +19,17 @@ M.Rarities = { } -- доля цены крутки, которая возвращается за повторный предмет -M.DuplicateRefund = 0.2 +M.DuplicateRefund = 0.35 +-- гарантия: если в категории pity.every круток подряд не выпало ничего «Эпического» или реже, +-- следующая крутка — не ниже pity.minRank (неудача не тянется бесконечно) +M.Pity = { every = 10, minRank = 4 } -- сколько круток можно сделать одной кнопкой M.SpinCounts = { 1, 3, 10 } +-- цена одной крутки — под доход 60…240 ⚪/мин (было 1 000…10 000: мифическая крыша в среднем ~2 млн ⚪) M.Categories = { { - id = "bush", name = "Кусты", icon = "🌳", cost = 1000, + id = "bush", name = "Кусты", icon = "🌳", cost = 150, items = { { id = "green", name = "Зелёный куст", rarity = "Common", chance = 45, color = RGB(70, 150, 70), material = Mat.Grass, shape = "Ball", size = 4 }, { id = "cube", name = "Стриженый куб", rarity = "Uncommon", chance = 30, color = RGB(56, 128, 60), material = Mat.Grass, shape = "Block", size = 3.6 }, @@ -36,7 +40,7 @@ M.Categories = { }, }, { - id = "door", name = "Двери", icon = "🚪", cost = 2500, + id = "door", name = "Двери", icon = "🚪", cost = 350, items = { { id = "oak", name = "Дубовая дверь", rarity = "Common", chance = 45, color = RGB(110, 66, 38), material = Mat.WoodPlanks }, { id = "red", name = "Красная дверь", rarity = "Uncommon", chance = 30, color = RGB(170, 40, 40), material = Mat.SmoothPlastic }, @@ -47,7 +51,7 @@ M.Categories = { }, }, { - id = "window", name = "Окна", icon = "🖼", cost = 2500, + id = "window", name = "Окна", icon = "🖼", cost = 350, items = { { id = "clear", name = "Прозрачное стекло", rarity = "Common", chance = 45, color = RGB(170, 215, 240), material = Mat.Glass, transparency = 0.65 }, { id = "tinted", name = "Тонировка", rarity = "Uncommon", chance = 30, color = RGB(50, 66, 84), material = Mat.Glass, transparency = 0.4 }, @@ -58,7 +62,7 @@ M.Categories = { }, }, { - id = "roof", name = "Крыша", icon = "🏠", cost = 10000, + id = "roof", name = "Крыша", icon = "🏠", cost = 900, items = { { id = "straw", name = "Солома", rarity = "Common", chance = 45, color = RGB(196, 164, 92), material = Mat.Fabric }, { id = "tile", name = "Красная черепица", rarity = "Uncommon", chance = 30, color = RGB(170, 70, 52), material = Mat.Slate }, @@ -69,7 +73,7 @@ M.Categories = { }, }, { - id = "floor", name = "Пол", icon = "🟫", cost = 5000, + id = "floor", name = "Пол", icon = "🟫", cost = 500, items = { { id = "planks", name = "Доски", rarity = "Common", chance = 45, color = RGB(150, 104, 62), material = Mat.WoodPlanks }, { id = "stone", name = "Каменная плитка", rarity = "Uncommon", chance = 30, color = RGB(130, 128, 124), material = Mat.Cobblestone }, @@ -99,21 +103,25 @@ function M.item(catId, itemId) return cat and itemId and cat.byId[itemId] or nil end --- случайный предмет по шансам (rng — Random) -function M.roll(catId, rng) +-- случайный предмет по шансам (rng — Random); minRank — только предметы не ниже этой редкости (гарантия) +function M.roll(catId, rng, minRank) local cat = M.ById[catId] + local pool = {} local total = 0 for _, it in ipairs(cat.items) do - total += it.chance + if not minRank or M.Rarities[it.rarity].rank >= minRank then + table.insert(pool, it) + total += it.chance + end end local r = rng:NextNumber() * total - for _, it in ipairs(cat.items) do + for _, it in ipairs(pool) do r -= it.chance if r <= 0 then return it end end - return cat.items[#cat.items] + return pool[#pool] end -- число для подписи: 45 -> "45%", 2.5 -> "2.5%" diff --git a/src/ReplicatedStorage/UiImages.lua b/src/ReplicatedStorage/UiImages.lua index 317db16..a214e3f 100644 --- a/src/ReplicatedStorage/UiImages.lua +++ b/src/ReplicatedStorage/UiImages.lua @@ -15,7 +15,9 @@ UiImages.IDS = { frame_small = 128753562500086, diamond = 125386825460398, chip = 72800269450328, roller = 75796379613455, menu_btn = 113300211302539, menu_btn_down = 90370634217744, gold_dot = 119904739243675, -- из прошлого набора (assets/ui) - planks_dark = 84008321934239, card_frame = 119987262904306, empty_basket = 91278106715680, + planks_dark = 84008321934239, + -- экран загрузки (RobloxPageRenders): общая заставка с порталом и тропики + loading_common = 116236606416697, loading_tropics = 95232987992846, card_frame = 119987262904306, empty_basket = 91278106715680, } -- старые имена ведут на новые картинки UiImages.ALIAS = { panel_wood = "frame_window", ribbon = "banner" } diff --git a/src/ServerScriptService/GameServer.server.lua b/src/ServerScriptService/GameServer.server.lua index 1e177e3..0f2c6a0 100644 --- a/src/ServerScriptService/GameServer.server.lua +++ b/src/ServerScriptService/GameServer.server.lua @@ -340,7 +340,7 @@ local function sendQuests(player) }, { 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), + nextStreak = (data.daily.last < t) and (data.daily.streak % 7 + 1) or data.daily.streak, }) end @@ -409,6 +409,8 @@ local function updateStats(player) end end +local grantLevelRewards -- награды за новый уровень (ниже, после givePotion) + -- опыт карьеры (единственный источник — ручная поимка; source — для телеметрии) local function addXp(player, data, amount, source) if amount <= 0 then @@ -430,6 +432,10 @@ local function addXp(player, data, amount, source) if table.find(levels, Config.Market.minLevel) then notify(player, "🏪 Открыт рынок игроков: продавай ценную рыбу другим рыбакам", GOLD) end + for _, lvl in ipairs(levels) do + grantLevelRewards(player, data, lvl) + end + updateStats(player) end end @@ -450,6 +456,88 @@ local function givePotion(player, data, def) return false end +-- пачка наживки в запас (как при покупке у торговца) +local function giveBait(data, baitId) + local b = baitId and Config.Find(Config.Baits, baitId) + if not b or type(data.bait) ~= "table" then + return nil + end + data.bait.counts[b.id] = (data.bait.counts[b.id] or 0) + b.pack + return b +end + +-- одна награда: { coins (× tier), pearls, potion, bait }; возвращает текст «+40 ⚪ + 🎯 …» для уведомления +local function giveReward(player, data, r, kind, coinsAlreadyScaled) + local parts = {} + if r.coins then + local c = addCoins(player, data, coinsAlreadyScaled and r.coins or r.coins * tierOf(data), kind) + table.insert(parts, ("+%d ⚪"):format(c)) + end + if r.pearls then + data.pearls += r.pearls + table.insert(parts, ("+%d 🦪"):format(r.pearls)) + end + if r.potion then + local p = Potions.def(r.potion) + if givePotion(player, data, p) then + table.insert(parts, p.icon .. " " .. p.name) + end + end + if r.bait then + local b = giveBait(data, r.bait) + if b then + table.insert(parts, ("%s %s ×%d"):format(b.icon, b.name, b.pack)) + Guild.sendState(player) + end + end + return table.concat(parts, " + ") +end + +grantLevelRewards = function(player, data, lvl) + local L = Config.LevelRewards + local r = { coins = lvl * L.coinsPerLevel } + local m = L.milestones[lvl] + if m then + r.coins += m.coins or 0 + r.pearls, r.potion, r.bait = m.pearls, m.potion, m.bait + end + if lvl % L.every == 0 then + r.pearls = (r.pearls or 0) + L.everyPearls + r.potion = r.potion or L.everyPotion + end + local text = giveReward(player, data, r, "LevelReward", true) + Telemetry.event(player, "LevelReward", lvl) + if text ~= "" then + notify(player, ("⭐ Награда за уровень %d: %s"):format(lvl, text), GOLD) + end +end + +-- подарки за время в игре в этот заход (Config.PlaytimeGifts) +local sessionStart = {} +local giftIndex = {} +local function setGiftAttr(player) + local g = Config.PlaytimeGifts[(giftIndex[player] or 0) + 1] + player:SetAttribute("GiftNextAt", g and math.floor((sessionStart[player] or os.time()) + g.minutes * 60) or 0) +end +task.spawn(function() + while true do + task.wait(5) + local now = os.time() + for player, data in pairs(profiles) do + local start = sessionStart[player] + local g = start and Config.PlaytimeGifts[(giftIndex[player] or 0) + 1] + if g and now - start >= g.minutes * 60 then + giftIndex[player] = (giftIndex[player] or 0) + 1 + local text = giveReward(player, data, g, "PlaytimeGift") + Telemetry.event(player, "PlaytimeGift", g.minutes) + updateStats(player) + notify(player, ("🎁 Подарок за %d мин в игре: %s"):format(g.minutes, text), GOLD) + setGiftAttr(player) + end + end + end +end) + ---------------------------------------------------------------- задания: прогресс цепочки -- у старых сохранений вместо цепочки были три случайных задания @@ -508,7 +596,8 @@ local function claimDaily(player) notify(player, "🎁 Приходи завтра", Color3.fromRGB(255, 200, 120)) return end - local streak = (data.daily.last == t - 1) and (data.daily.streak % 7 + 1) or 1 + -- пропуск дня не сбрасывает круг: продолжается со следующего дня (Config.DailyRewards) + local streak = data.daily.streak % 7 + 1 local r = Config.DailyRewards[streak] local coins = addCoins(player, data, r.coins * tierOf(data), "Daily") local extra = "" @@ -2013,6 +2102,8 @@ local function onPlayerAdded(player) end profiles[player] = data loadedOk[player] = status == "ok" + sessionStart[player], giftIndex[player] = os.time(), 0 + setGiftAttr(player) 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) @@ -2059,6 +2150,7 @@ local function finishPlayer(player) profiles[player] = nil loadedOk[player] = nil passes[player] = nil + sessionStart[player], giftIndex[player] = nil, nil leaving[player] = nil end Players.PlayerRemoving:Connect(finishPlayer) diff --git a/src/ServerScriptService/Houses.lua b/src/ServerScriptService/Houses.lua index 517cfb0..13d4d8b 100644 --- a/src/ServerScriptService/Houses.lua +++ b/src/ServerScriptService/Houses.lua @@ -809,6 +809,9 @@ local function assign(player) local lvl = data and data.houseLevel or 0 deps.notify(player, lvl > 0 and ("🏠 Твой дом — участок " .. i .. ". Заходи: внутри компьютер с улучшениями!") or ("🏠 Твой участок — №" .. i .. ". Построй дом у таблички!"), GREEN) + if data then + Houses.collectRent(player, data) + end return true end end @@ -886,6 +889,9 @@ function Houses.defaults(data) local cos = data.houseCos cos.owned = type(cos.owned) == "table" and cos.owned or {} cos.equip = type(cos.equip) == "table" and cos.equip or {} + cos.pity = type(cos.pity) == "table" and cos.pity or {} + -- аренда считается от этого момента; у старых сохранений — от первого входа после обновления + data.houseRentAt = tonumber(data.houseRentAt) or os.time() for _, cat in ipairs(COS.Categories) do local set = type(cos.owned[cat.id]) == "table" and cos.owned[cat.id] or {} for id in pairs(set) do @@ -926,6 +932,21 @@ function Houses.onComputer(player, prompt) end end +-- аренда: серебро за время с прошлого сбора (не больше HC.Rent.maxHours), забирается при входе на участок. +-- Пустой участок аренды не даёт, но отсчёт сбрасывается — нельзя «накопить» до постройки дома +function Houses.collectRent(player, data) + local now = os.time() + local hours = math.min(HC.Rent.maxHours, math.max(0, now - (data.houseRentAt or now)) / 3600) + data.houseRentAt = now + local amount = math.floor(HC.rentPerHour(data.houseLevel or 0) * hours) + if amount > 0 then + deps.addCoins(player, data, amount, "HouseRent") + deps.updateStats(player) + deps.notify(player, ("🏠 Аренда дома: +%d ⚪ (копится до %d ч, пока тебя нет)"):format(amount, HC.Rent.maxHours), GOLD) + end + return amount +end + -- покупка следующего уровня function Houses.upgrade(player) local data = deps.profiles[player] @@ -947,6 +968,8 @@ function Houses.upgrade(player) deps.notify(player, "Не хватает серебра", RED) return end + -- накопленное по старой ставке — забрать до повышения (новая ставка не действует задним числом) + Houses.collectRent(player, data) data.houseLevel = nextLv deps.updateStats(player) rebuild(i) @@ -978,10 +1001,18 @@ function Houses.spin(player, catId, count) return end local owned = data.houseCos.owned[cat.id] + local pity = data.houseCos.pity local results, newOnes, refund = {}, 0, 0 local best = nil for _ = 1, count do - local it = COS.roll(cat.id, rng) + -- гарантия: после COS.Pity.every круток без «Эпического» — следующая не ниже него + local guaranteed = (pity[cat.id] or 0) >= COS.Pity.every - 1 + local it = COS.roll(cat.id, rng, guaranteed and COS.Pity.minRank or nil) + if COS.Rarities[it.rarity].rank >= COS.Pity.minRank then + pity[cat.id] = 0 + else + pity[cat.id] = (pity[cat.id] or 0) + 1 + end local isNew = not owned[it.id] if isNew then owned[it.id] = true diff --git a/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua b/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua index eaf67cd..8f4bb99 100644 --- a/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua +++ b/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua @@ -2552,6 +2552,7 @@ local function teleportLoading(targetId, delay) loadingGui:SetAttribute("Ready", false) loadingGui:SetAttribute("StartAt", now) loadingGui:SetAttribute("MinUntil", now + Config.Loading.teleport) + loadingGui:SetAttribute("Target", targetId) -- по нему экран загрузки выбирает картинку loadingGui:SetAttribute("Title", targetId == "Home" and "🏠 Мой дом" or placeTitle(target)) loadingGui:SetAttribute("Visible", true) end @@ -2806,7 +2807,12 @@ end -- скупка «Тихого озера»: ведём к прилавку с подсказкой «Продать» внутри лавки (GuideTarget = "Sell"), -- поэтому стрелка идёт за лавкой, куда бы её ни переставили; маркер GuideSell — запасной вариант local function sellTargetW1() + -- точка перед прилавком на земле (маркер GuideSell): к ней можно проложить путь, к крышке прилавка — нет + local marker = guideMarker("GuideSell") local shop = guideObject("Sell") + if marker and shop and ((shop:IsA("Model") and shop:GetPivot().Position or shop.Position) - marker).Magnitude < 14 then + return marker + end if shop then for _, d in ipairs(shop:GetDescendants()) do if d:IsA("ProximityPrompt") and d:GetAttribute("Action") == "Sell" then @@ -2822,6 +2828,50 @@ local function sellTargetW1() return guideMarker("GuideSell") end +-- путь к цели по земле: считается в фоне (раз в 2.5 с или когда игрок ушёл от начала пути), до готовности — nil. +-- false — путь не найден. Возвращает точки после игрока +H.path = { at = -math.huge, busy = false } +function H.routeTo(pos, goal) + local P = H.path + local now = os.clock() + if not P.busy and (not P.goal or (P.goal - goal).Magnitude > 3 or (P.from - pos).Magnitude > 10 or now - P.at > 2.5) then + P.busy = true + local from = pos + task.spawn(function() + local path = game:GetService("PathfindingService"):CreatePath({ + AgentRadius = 2, AgentHeight = 5, AgentCanJump = true, WaypointSpacing = 4, Costs = { Water = math.huge }, + }) + local ok = pcall(function() + path:ComputeAsync(from - Vector3.new(0, 2.5, 0), goal) + end) + local pts = false + if ok and (path.Status == Enum.PathStatus.Success or path.Status == Enum.PathStatus.ClosestNoPath) then + local wps = path:GetWaypoints() + -- «ближайший путь» годится, только если он подводит к цели вплотную + if #wps > 0 and (wps[#wps].Position - goal).Magnitude < 7 then + pts = {} + for i = 2, #wps do + table.insert(pts, wps[i].Position) + end + end + end + P.pts, P.from, P.goal, P.at, P.busy = pts, from, goal, os.clock(), false + end) + end + if not P.pts or (P.goal - goal).Magnitude > 3 then + return P.goal and (P.goal - goal).Magnitude <= 3 and P.pts or nil + end + -- пройденные точки отбрасываем: начинаем с ближайшей к игроку + local best, bd = 1, math.huge + for i, p in ipairs(P.pts) do + local d = ((p - pos) * Vector3.new(1, 0, 1)).Magnitude + if d < bd then + best, bd = i, d + end + end + return table.move(P.pts, best, #P.pts, 1, {}) +end + -- маршрут для текущего шага: точки ломаной (без игрока), подсказка и что подсветить; nil — линию не показываем local function guideRoute(step, pos, world) local inW1 = world and world.id == "World1" @@ -2924,10 +2974,13 @@ RunService.RenderStepped:Connect(function() guideHighlight.FillTransparency = 0.86 + 0.1 * pulse -- лёгкое «дыхание», цвет объекта виден guideHighlight.OutlineTransparency = 0.1 + 0.45 * pulse end - -- линия идёт напрямую к цели и сквозь всё на пути: в здании Гильдии и в саду за ней стрелки не показываем - -- (остаётся надпись-подсказка), иначе они тянутся через пруд, холм и мостик - local behindPlaza = not world and (pos.Z < -52 or (pos.Z < -48 and math.abs(pos.X) < 18)) - if not route or #route == 0 or state ~= "idle" or behindPlaza then + if not route or #route == 0 or state ~= "idle" then + hideChevrons(1) + return + end + -- стрелки идут по земле в обход скал, воды и построек (PathfindingService); пути нет — стрелок нет + route = H.routeTo(pos, route[#route]) + if not route or #route == 0 then hideChevrons(1) return end