From 58ae93f9e66e739be11f2bf44fbc228b48bdecaa Mon Sep 17 00:00:00 2001 From: listik Date: Wed, 11 Nov 2026 15:53:07 +0300 Subject: [PATCH] =?UTF-8?q?=D1=8D=D0=BA=D0=BE=D0=BD=D0=BE=D0=BC=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + README.md | 5 + docs/economy-balance.md | 85 ++ docs/economy-model-results.json | 1333 +++++++++++++++++ docs/economy-v2.md | 183 +++ docs/measured-progression-proposal.md | 86 ++ docs/progression-budget-results.json | 339 +++++ docs/progression-level-table.md | 30 + src/ReplicatedStorage/FishConfig.lua | 381 +++-- src/ServerScriptService/GameServer.server.lua | 531 +++++-- src/ServerScriptService/Guild.lua | 19 +- src/ServerScriptService/Market.lua | 692 +++++++++ src/ServerScriptService/PlayerStore.lua | 94 ++ src/ServerScriptService/Potions.lua | 179 +++ src/ServerScriptService/Progression.lua | 82 + src/ServerScriptService/Telemetry.lua | 112 ++ .../FishingClient.client.lua | 208 ++- .../GuildClient.client.lua | 4 +- .../MarketClient.client.lua | 313 ++++ tests/lib.lua | 69 + tests/market.spec.lua | 393 +++++ tests/playerstore.spec.lua | 127 ++ tests/potions.spec.lua | 137 ++ tests/progression.spec.lua | 110 ++ tools/baseline/FishConfig_v1.lua | 722 +++++++++ tools/economy_model.py | 463 ++++++ tools/progression_budget.py | 76 + tools/run-tests.js | 28 + 28 files changed, 6503 insertions(+), 299 deletions(-) create mode 100644 docs/economy-balance.md create mode 100644 docs/economy-model-results.json create mode 100644 docs/economy-v2.md create mode 100644 docs/measured-progression-proposal.md create mode 100644 docs/progression-budget-results.json create mode 100644 docs/progression-level-table.md create mode 100644 src/ServerScriptService/Market.lua create mode 100644 src/ServerScriptService/PlayerStore.lua create mode 100644 src/ServerScriptService/Potions.lua create mode 100644 src/ServerScriptService/Progression.lua create mode 100644 src/ServerScriptService/Telemetry.lua create mode 100644 src/StarterPlayer/StarterPlayerScripts/MarketClient.client.lua create mode 100644 tests/lib.lua create mode 100644 tests/market.spec.lua create mode 100644 tests/playerstore.spec.lua create mode 100644 tests/potions.spec.lua create mode 100644 tests/progression.spec.lua create mode 100644 tools/baseline/FishConfig_v1.lua create mode 100644 tools/economy_model.py create mode 100644 tools/progression_budget.py create mode 100644 tools/run-tests.js diff --git a/.gitignore b/.gitignore index c46b77d..06a43a3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ sourcemap.json rojo.exe backups/ +tests/.out/ diff --git a/README.md b/README.md index e4ca5c4..1738ea5 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,11 @@ NPC в редакторе показаны полупрозрачными фиг - **События на сервере** каждые 7–12 минут: Клёвый час, Удачный ветер, Звездопад, Рыбная ярмарка. - **Донат (💎):** 4 пропуска и 4 набора. +## Экономика v2, зелья и рынок + +Баланс, зелья, рынок игроков и миграция сохранений — [docs/economy-v2.md](docs/economy-v2.md). +Расчёт баланса: `py -3 tools/economy_model.py` (пишет docs/economy-balance.md). Тесты в открытом Studio: `node tools/run-tests.js`. + ## Настройка доната (Robux) 1. Опубликуйте игру: **File → Publish to Roblox**. diff --git a/docs/economy-balance.md b/docs/economy-balance.md new file mode 100644 index 0000000..67440f1 --- /dev/null +++ b/docs/economy-balance.md @@ -0,0 +1,85 @@ +# Экономика v2 — расчёт баланса + +Сгенерировано `py -3 tools/economy_model.py`. Это математическая модель ожиданий по формулам сервера и допущениям ниже, **не замер игроков**. Цели по времени считаются подтверждёнными только после телеметрии (события CareerXP, LevelUp, economy events) и плейтестов. + +## Время до уровней (эффективная игра, без AFK) + +| Сценарий | ур. 3 | ур. 5 | ур. 8 (Мир 2) | ур. 10 | ур. 13 | ур. 18 (Мир 3) | ур. 25 | +|---|---:|---:|---:|---:|---:|---:|---:| +| Новичок / телефон — 3 рыб/мин | 17 мин | 53 мин | 2 ч 40 мин | 4 ч 20 мин | 7 ч 26 мин | 14 ч 40 мин | 28 ч 53 мин | +| Обычный активный — 4 рыб/мин | 13 мин | 40 мин | 2 ч 00 мин | 3 ч 15 мин | 5 ч 35 мин | 11 ч 00 мин | 21 ч 40 мин | +| Опытный — 5 рыб/мин | 10 мин | 32 мин | 1 ч 36 мин | 2 ч 36 мин | 4 ч 28 мин | 8 ч 48 мин | 17 ч 20 мин | +| Оптимизированный (снасти + зелья) — 6 рыб/мин | 9 мин | 27 мин | 1 ч 20 мин | 2 ч 10 мин | 3 ч 43 мин | 7 ч 20 мин | 14 ч 26 мин | +| Предел механики — 7.5 рыб/мин | 7 мин | 21 мин | 1 ч 04 мин | 1 ч 44 мин | 2 ч 58 мин | 5 ч 52 мин | 11 ч 33 мин | + +До v2 (та же модель, опыт с серией ×2, первой поимкой, мутациями, заданиями и боссом): + +| Темп | ур. 3 | ур. 5 | ур. 8 | ур. 10 | ур. 13 | ур. 18 | ур. 25 | +|---|---:|---:|---:|---:|---:|---:|---:| +| 3 рыб/мин | 2 мин | 5 мин | 16 мин | 22 мин | 33 мин | 1 ч 01 мин | 1 ч 32 мин | +| 4 рыб/мин | 1 мин | 4 мин | 12 мин | 17 мин | 25 мин | 47 мин | 1 ч 11 мин | +| 5 рыб/мин | 1 мин | 4 мин | 10 мин | 14 мин | 21 мин | 38 мин | 57 мин | + +Опыт карьеры зависит только от темпа ручной ловли: снасти, удача, редкость, зелья и пропуска его не ускоряют. Разброс между игроками — это разброс темпа (3–6 рыб/мин), а не случайные скачки. + +Ускорение клёва: лучшая снасть со всеми бонусами раньше давала множитель ожидания ×0.131, теперь не меньше ×0.75. + +## Доход серебра, ⚪ в минуту (обычный игрок, 4 рыбы/мин) + +| Мир | рыба | задания | босс | заказы | ежедневка | расходники | итого | цель | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| World1 | 50.8 | 8.6 | 2.6 | 1.6 | 2.0 | −2.0 | **63.6** | 60 | +| World2 | 97.4 | 17.9 | 5.2 | 3.2 | 3.9 | −6.0 | **121.7** | 120 | +| World3 | 187.8 | 37.6 | 10.3 | 6.5 | 7.9 | −12.0 | **238.1** | 240 | + +До v2, та же модель (4 рыбы/мин): World1: 434.2 ⚪/мин, World2: 1593.6 ⚪/мин, World3: 9736.1 ⚪/мин + +## Серебро за одну поимку по снаряжению + +| Мир | Удочка | Удача | ⚪ за рыбу | Эпическая+ % | Мифическая % | +|---|---|---:|---:|---:|---:| +| World1 | Basic | 1.13 | 9.8 | 4.58 | 0.12 | +| World1 | Bamboo | 1.23 | 10.4 | 4.94 | 0.134 | +| World1 | Fiberglass | 1.33 | 10.9 | 5.29 | 0.147 | +| World2 | Carbon | 1.51 | 19.3 | 5.86 | 0.168 | +| World2 | Coral | 1.66 | 20.3 | 6.3 | 0.184 | +| World2 | Golden | 1.81 | 21.3 | 6.69 | 0.199 | +| World3 | Frost | 2.11 | 40.3 | 7.4 | 0.226 | +| World3 | Legend | 2.31 | 42.1 | 7.8 | 0.241 | + +## Маршрут покупок (жадный, модель) + +| Сценарий | первая покупка | Bamboo | Fiberglass | Carbon | Coral | Golden | Frost | Legend | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| Новичок 3/мин | 18 мин | 18 мин | 1 ч 00 мин | 2 ч 40 мин | 4 ч 20 мин | 8 ч 58 мин | 15 ч 38 мин | — | +| Обычный 4/мин | 13 мин | 13 мин | 46 мин | 2 ч 00 мин | 3 ч 15 мин | 6 ч 41 мин | 11 ч 46 мин | 21 ч 56 мин | +| Опытный 5/мин | 11 мин | 11 мин | 36 мин | 1 ч 37 мин | 2 ч 36 мин | 5 ч 24 мин | 9 ч 28 мин | 17 ч 41 мин | +| Платные пропуска 4/мин | 9 мин | 13 мин | 40 мин | 2 ч 00 мин | 3 ч 15 мин | 5 ч 35 мин | 11 ч 00 мин | 21 ч 40 мин | +| До v2, 4/мин | — | 1 мин | 4 мин | 12 мин | 17 мин | 25 мин | 48 мин | 1 ч 11 мин | + +Удочку можно купить не раньше её уровня; задержка после уровня — время накопить. Платные пропуска (VIP + x2 серебро + талисман) ускоряют покупки, но не уровни. + +## Автоловля против ручной ловли + +| Мир | ручная: ⚪/мин (рыба) | авто: ⚪/мин | авто: рыб/мин | опыт/мин ручная | опыт/мин авто | +|---|---:|---:|---:|---:|---:| +| World1 | 44.0 | 10.1 | 3.33 | 20 | 0 | +| World2 | 85.9 | 19.8 | 3.33 | 28 | 0 | +| World3 | 169.5 | 36.1 | 3.33 | 36 | 0 | + +## Допущения + +- `fail_rate` = 0.12 +- `perfect_cast_share` = 0.45 +- `night_share` = 0.35 +- `weather_luck` = 0.0325 +- `event_share_each` = 0.06 +- `boss_win_rate` = 0.7 +- `boss_share` = 0.8 +- `orders_per_hour` = 1.5 +- `order_seals_avg` = 13 +- `daily_session_min` = 90 +- `consumables_per_min` = {'World1': 2, 'World2': 6, 'World3': 12} +- `quest_rates` = {'perfect': 0.6, 'perfectCast': 0.45, 'buy_min': 2.0, 'boss_min': 6.0} + +Ограничения: модель не воспроизводит случайные хвосты (мифическая рыба, серия удачных мутаций), поведение реальных игроков, очереди к скупщику, рынок игроков и пропуски заданий. Темп в рыбах/мин — главная неизвестная: замерить его до выводов о времени прохождения. diff --git a/docs/economy-model-results.json b/docs/economy-model-results.json new file mode 100644 index 0000000..751d8d7 --- /dev/null +++ b/docs/economy-model-results.json @@ -0,0 +1,1333 @@ +{ + "assumptions": { + "fail_rate": 0.12, + "perfect_cast_share": 0.45, + "night_share": 0.35, + "weather_luck": 0.0325, + "event_share_each": 0.06, + "boss_win_rate": 0.7, + "boss_share": 0.8, + "orders_per_hour": 1.5, + "order_seals_avg": 13, + "daily_session_min": 90, + "consumables_per_min": { + "World1": 2, + "World2": 6, + "World3": 12 + }, + "quest_rates": { + "perfect": 0.6, + "perfectCast": 0.45, + "buy_min": 2.0, + "boss_min": 6.0 + } + }, + "levels": { + "Новичок / телефон": { + "3": 17.3, + "5": 53.3, + "8": 160.0, + "10": 260.0, + "13": 446.7, + "18": 880.0, + "25": 1733.3 + }, + "Обычный активный": { + "3": 13.0, + "5": 40.0, + "8": 120.0, + "10": 195.0, + "13": 335.0, + "18": 660.0, + "25": 1300.0 + }, + "Опытный": { + "3": 10.4, + "5": 32.0, + "8": 96.0, + "10": 156.0, + "13": 268.0, + "18": 528.0, + "25": 1040.0 + }, + "Оптимизированный (снасти + зелья)": { + "3": 8.7, + "5": 26.7, + "8": 80.0, + "10": 130.0, + "13": 223.3, + "18": 440.0, + "25": 866.7 + }, + "Предел механики": { + "3": 6.9, + "5": 21.3, + "8": 64.0, + "10": 104.0, + "13": 178.7, + "18": 352.0, + "25": 693.3 + } + }, + "levels_before": { + "3": { + "3": 2, + "5": 5, + "8": 16, + "10": 22, + "13": 33, + "18": 61, + "25": 92 + }, + "4": { + "3": 1, + "5": 4, + "8": 12, + "10": 17, + "13": 25, + "18": 47, + "25": 71 + }, + "5": { + "3": 1, + "5": 4, + "8": 10, + "10": 14, + "13": 21, + "18": 38, + "25": 57 + } + }, + "simulations": { + "Новичок 3/мин": { + "purchases": [ + [ + 1, + "upgrade", + "Basic+1" + ], + [ + 3, + "upgrade", + "Basic+2" + ], + [ + 5, + "upgrade", + "Basic+3" + ], + [ + 18, + "rod", + "Bamboo" + ], + [ + 18, + "upgrade", + "Bamboo+1" + ], + [ + 20, + "upgrade", + "Bamboo+2" + ], + [ + 25, + "upgrade", + "Bamboo+3" + ], + [ + 30, + "bag", + "Satchel" + ], + [ + 60, + "rod", + "Fiberglass" + ], + [ + 62, + "upgrade", + "Fiberglass+1" + ], + [ + 67, + "upgrade", + "Fiberglass+2" + ], + [ + 74, + "upgrade", + "Fiberglass+3" + ], + [ + 85, + "upgrade", + "Fiberglass+4" + ], + [ + 97, + "bag", + "Backpack" + ], + [ + 160, + "rod", + "Carbon" + ], + [ + 161, + "upgrade", + "Carbon+1" + ], + [ + 166, + "upgrade", + "Carbon+2" + ], + [ + 175, + "upgrade", + "Carbon+3" + ], + [ + 187, + "upgrade", + "Carbon+4" + ], + [ + 204, + "upgrade", + "Carbon+5" + ], + [ + 260, + "rod", + "Coral" + ], + [ + 264, + "upgrade", + "Coral+1" + ], + [ + 274, + "upgrade", + "Coral+2" + ], + [ + 291, + "upgrade", + "Coral+3" + ], + [ + 315, + "upgrade", + "Coral+4" + ], + [ + 346, + "upgrade", + "Coral+5" + ], + [ + 376, + "bag", + "BigNet" + ], + [ + 538, + "rod", + "Golden" + ], + [ + 548, + "upgrade", + "Golden+1" + ], + [ + 571, + "upgrade", + "Golden+2" + ], + [ + 607, + "upgrade", + "Golden+3" + ], + [ + 658, + "upgrade", + "Golden+4" + ], + [ + 726, + "upgrade", + "Golden+5" + ], + [ + 938, + "rod", + "Frost" + ], + [ + 948, + "upgrade", + "Frost+1" + ], + [ + 972, + "upgrade", + "Frost+2" + ], + [ + 1010, + "upgrade", + "Frost+3" + ], + [ + 1065, + "upgrade", + "Frost+4" + ], + [ + 1108, + "bag", + "Chest" + ], + [ + 1219, + "upgrade", + "Frost+5" + ], + [ + 1328, + "bag", + "Magic" + ] + ], + "first_purchase": 18, + "rods": { + "Bamboo": 18, + "Fiberglass": 60, + "Carbon": 160, + "Coral": 260, + "Golden": 538, + "Frost": 938, + "Legend": null + }, + "income": { + "World1": { + "fish": 38.1, + "quests": 6.4, + "cons": 2.0, + "boss": 2.6, + "orders": 1.6, + "daily": 2.0, + "net": 48.8, + "minutes": 160 + }, + "World2": { + "fish": 73.1, + "quests": 13.5, + "cons": 6.0, + "boss": 5.2, + "orders": 3.2, + "daily": 3.9, + "net": 92.9, + "minutes": 720 + }, + "World3": { + "fish": 139.3, + "quests": 28.1, + "cons": 12.0, + "boss": 10.3, + "orders": 6.5, + "daily": 7.9, + "net": 180.1, + "minutes": 520 + } + }, + "coins_left": 13203 + }, + "Обычный 4/мин": { + "purchases": [ + [ + 1, + "upgrade", + "Basic+1" + ], + [ + 2, + "upgrade", + "Basic+2" + ], + [ + 4, + "upgrade", + "Basic+3" + ], + [ + 13, + "rod", + "Bamboo" + ], + [ + 14, + "upgrade", + "Bamboo+1" + ], + [ + 16, + "upgrade", + "Bamboo+2" + ], + [ + 19, + "upgrade", + "Bamboo+3" + ], + [ + 23, + "bag", + "Satchel" + ], + [ + 46, + "rod", + "Fiberglass" + ], + [ + 48, + "upgrade", + "Fiberglass+1" + ], + [ + 51, + "upgrade", + "Fiberglass+2" + ], + [ + 57, + "upgrade", + "Fiberglass+3" + ], + [ + 66, + "upgrade", + "Fiberglass+4" + ], + [ + 75, + "bag", + "Backpack" + ], + [ + 120, + "rod", + "Carbon" + ], + [ + 122, + "upgrade", + "Carbon+1" + ], + [ + 126, + "upgrade", + "Carbon+2" + ], + [ + 133, + "upgrade", + "Carbon+3" + ], + [ + 143, + "upgrade", + "Carbon+4" + ], + [ + 195, + "rod", + "Coral" + ], + [ + 195, + "upgrade", + "Coral+1" + ], + [ + 200, + "upgrade", + "Coral+2" + ], + [ + 213, + "upgrade", + "Coral+3" + ], + [ + 231, + "upgrade", + "Coral+4" + ], + [ + 255, + "upgrade", + "Coral+5" + ], + [ + 278, + "bag", + "BigNet" + ], + [ + 401, + "rod", + "Golden" + ], + [ + 409, + "upgrade", + "Golden+1" + ], + [ + 426, + "upgrade", + "Golden+2" + ], + [ + 454, + "upgrade", + "Golden+3" + ], + [ + 493, + "upgrade", + "Golden+4" + ], + [ + 545, + "upgrade", + "Golden+5" + ], + [ + 706, + "rod", + "Frost" + ], + [ + 713, + "upgrade", + "Frost+1" + ], + [ + 732, + "upgrade", + "Frost+2" + ], + [ + 761, + "upgrade", + "Frost+3" + ], + [ + 802, + "upgrade", + "Frost+4" + ], + [ + 835, + "bag", + "Chest" + ], + [ + 920, + "upgrade", + "Frost+5" + ], + [ + 1003, + "bag", + "Magic" + ], + [ + 1316, + "rod", + "Legend" + ], + [ + 1334, + "upgrade", + "Legend+1" + ], + [ + 1376, + "upgrade", + "Legend+2" + ] + ], + "first_purchase": 13, + "rods": { + "Bamboo": 13, + "Fiberglass": 46, + "Carbon": 120, + "Coral": 195, + "Golden": 401, + "Frost": 706, + "Legend": 1316 + }, + "income": { + "World1": { + "fish": 50.8, + "quests": 8.6, + "cons": 2.0, + "boss": 2.6, + "orders": 1.6, + "daily": 2.0, + "net": 63.6, + "minutes": 120 + }, + "World2": { + "fish": 97.4, + "quests": 17.9, + "cons": 6.0, + "boss": 5.2, + "orders": 3.2, + "daily": 3.9, + "net": 121.7, + "minutes": 540 + }, + "World3": { + "fish": 187.8, + "quests": 37.6, + "cons": 12.0, + "boss": 10.3, + "orders": 6.5, + "daily": 7.9, + "net": 238.1, + "minutes": 740 + } + }, + "coins_left": 12083 + }, + "Опытный 5/мин": { + "purchases": [ + [ + 1, + "upgrade", + "Basic+1" + ], + [ + 2, + "upgrade", + "Basic+2" + ], + [ + 11, + "rod", + "Bamboo" + ], + [ + 11, + "upgrade", + "Bamboo+1" + ], + [ + 12, + "upgrade", + "Bamboo+2" + ], + [ + 15, + "upgrade", + "Bamboo+3" + ], + [ + 18, + "bag", + "Satchel" + ], + [ + 36, + "rod", + "Fiberglass" + ], + [ + 38, + "upgrade", + "Fiberglass+1" + ], + [ + 41, + "upgrade", + "Fiberglass+2" + ], + [ + 46, + "upgrade", + "Fiberglass+3" + ], + [ + 52, + "upgrade", + "Fiberglass+4" + ], + [ + 60, + "bag", + "Backpack" + ], + [ + 97, + "rod", + "Carbon" + ], + [ + 98, + "upgrade", + "Carbon+1" + ], + [ + 101, + "upgrade", + "Carbon+2" + ], + [ + 107, + "upgrade", + "Carbon+3" + ], + [ + 115, + "upgrade", + "Carbon+4" + ], + [ + 156, + "rod", + "Coral" + ], + [ + 156, + "upgrade", + "Coral+1" + ], + [ + 161, + "upgrade", + "Coral+2" + ], + [ + 171, + "upgrade", + "Coral+3" + ], + [ + 186, + "upgrade", + "Coral+4" + ], + [ + 205, + "upgrade", + "Coral+5" + ], + [ + 224, + "bag", + "BigNet" + ], + [ + 324, + "rod", + "Golden" + ], + [ + 330, + "upgrade", + "Golden+1" + ], + [ + 344, + "upgrade", + "Golden+2" + ], + [ + 366, + "upgrade", + "Golden+3" + ], + [ + 398, + "upgrade", + "Golden+4" + ], + [ + 440, + "upgrade", + "Golden+5" + ], + [ + 568, + "rod", + "Frost" + ], + [ + 574, + "upgrade", + "Frost+1" + ], + [ + 589, + "upgrade", + "Frost+2" + ], + [ + 612, + "upgrade", + "Frost+3" + ], + [ + 646, + "upgrade", + "Frost+4" + ], + [ + 672, + "bag", + "Chest" + ], + [ + 741, + "upgrade", + "Frost+5" + ], + [ + 808, + "bag", + "Magic" + ], + [ + 1061, + "rod", + "Legend" + ], + [ + 1076, + "upgrade", + "Legend+1" + ], + [ + 1110, + "upgrade", + "Legend+2" + ], + [ + 1165, + "upgrade", + "Legend+3" + ], + [ + 1243, + "upgrade", + "Legend+4" + ], + [ + 1346, + "upgrade", + "Legend+5" + ] + ], + "first_purchase": 11, + "rods": { + "Bamboo": 11, + "Fiberglass": 36, + "Carbon": 97, + "Coral": 156, + "Golden": 324, + "Frost": 568, + "Legend": 1061 + }, + "income": { + "World1": { + "fish": 63.4, + "quests": 10.7, + "cons": 2.0, + "boss": 2.6, + "orders": 1.6, + "daily": 2.0, + "net": 78.3, + "minutes": 96 + }, + "World2": { + "fish": 121.7, + "quests": 22.4, + "cons": 6.0, + "boss": 5.2, + "orders": 3.2, + "daily": 3.9, + "net": 150.5, + "minutes": 432 + }, + "World3": { + "fish": 238.0, + "quests": 47.2, + "cons": 12.0, + "boss": 10.3, + "orders": 6.5, + "daily": 7.9, + "net": 297.9, + "minutes": 872 + } + }, + "coins_left": 41290 + }, + "Платные пропуска 4/мин": { + "purchases": [ + [ + 1, + "upgrade", + "Basic+1" + ], + [ + 1, + "upgrade", + "Basic+2" + ], + [ + 2, + "upgrade", + "Basic+3" + ], + [ + 3, + "upgrade", + "Basic+4" + ], + [ + 4, + "upgrade", + "Basic+5" + ], + [ + 9, + "bag", + "Satchel" + ], + [ + 13, + "rod", + "Bamboo" + ], + [ + 13, + "upgrade", + "Bamboo+1" + ], + [ + 13, + "upgrade", + "Bamboo+2" + ], + [ + 13, + "upgrade", + "Bamboo+3" + ], + [ + 13, + "upgrade", + "Bamboo+4" + ], + [ + 15, + "upgrade", + "Bamboo+5" + ], + [ + 27, + "bag", + "Backpack" + ], + [ + 40, + "rod", + "Fiberglass" + ], + [ + 40, + "upgrade", + "Fiberglass+1" + ], + [ + 40, + "upgrade", + "Fiberglass+2" + ], + [ + 40, + "upgrade", + "Fiberglass+3" + ], + [ + 40, + "upgrade", + "Fiberglass+4" + ], + [ + 40, + "upgrade", + "Fiberglass+5" + ], + [ + 120, + "rod", + "Carbon" + ], + [ + 120, + "upgrade", + "Carbon+1" + ], + [ + 120, + "upgrade", + "Carbon+2" + ], + [ + 120, + "upgrade", + "Carbon+3" + ], + [ + 120, + "upgrade", + "Carbon+4" + ], + [ + 120, + "upgrade", + "Carbon+5" + ], + [ + 195, + "rod", + "Coral" + ], + [ + 195, + "bag", + "BigNet" + ], + [ + 195, + "upgrade", + "Coral+1" + ], + [ + 195, + "upgrade", + "Coral+2" + ], + [ + 195, + "upgrade", + "Coral+3" + ], + [ + 195, + "upgrade", + "Coral+4" + ], + [ + 195, + "upgrade", + "Coral+5" + ], + [ + 335, + "rod", + "Golden" + ], + [ + 335, + "upgrade", + "Golden+1" + ], + [ + 335, + "upgrade", + "Golden+2" + ], + [ + 335, + "upgrade", + "Golden+3" + ], + [ + 335, + "upgrade", + "Golden+4" + ], + [ + 335, + "upgrade", + "Golden+5" + ], + [ + 660, + "rod", + "Frost" + ], + [ + 660, + "bag", + "Chest" + ], + [ + 660, + "upgrade", + "Frost+1" + ], + [ + 660, + "upgrade", + "Frost+2" + ], + [ + 660, + "upgrade", + "Frost+3" + ], + [ + 660, + "upgrade", + "Frost+4" + ], + [ + 660, + "upgrade", + "Frost+5" + ], + [ + 900, + "bag", + "Magic" + ], + [ + 1300, + "rod", + "Legend" + ], + [ + 1300, + "upgrade", + "Legend+1" + ], + [ + 1300, + "upgrade", + "Legend+2" + ], + [ + 1300, + "upgrade", + "Legend+3" + ], + [ + 1300, + "upgrade", + "Legend+4" + ], + [ + 1300, + "upgrade", + "Legend+5" + ] + ], + "first_purchase": 9, + "rods": { + "Bamboo": 13, + "Fiberglass": 40, + "Carbon": 120, + "Coral": 195, + "Golden": 335, + "Frost": 660, + "Legend": 1300 + }, + "income": { + "World1": { + "fish": 164.1, + "quests": 9.1, + "cons": 2.0, + "boss": 2.6, + "orders": 1.6, + "daily": 2.0, + "net": 177.4, + "minutes": 120 + }, + "World2": { + "fish": 288.1, + "quests": 18.7, + "cons": 6.0, + "boss": 5.2, + "orders": 3.2, + "daily": 3.9, + "net": 313.2, + "minutes": 540 + }, + "World3": { + "fish": 536.0, + "quests": 38.7, + "cons": 12.0, + "boss": 10.3, + "orders": 6.5, + "daily": 7.9, + "net": 587.4, + "minutes": 740 + } + }, + "coins_left": 331573 + } + }, + "income_before_4cpm": { + "World1": { + "fish": 302.9, + "quests": 88.8, + "cons": 0.0, + "boss": 25.8, + "orders": 5.4, + "daily": 11.3, + "net": 434.2, + "minutes": 12 + }, + "World2": { + "fish": 1152.6, + "quests": 199.1, + "cons": 0.0, + "boss": 210.5, + "orders": 9.8, + "daily": 21.7, + "net": 1593.6, + "minutes": 35 + }, + "World3": { + "fish": 5263.8, + "quests": 1275.9, + "cons": 0.0, + "boss": 3079.9, + "orders": 15.6, + "daily": 100.9, + "net": 9736.1, + "minutes": 1253 + } + }, + "rods_before_4cpm": { + "Bamboo": 1, + "Fiberglass": 4, + "Carbon": 12, + "Coral": 17, + "Golden": 25, + "Frost": 48, + "Legend": 71 + }, + "per_catch": [ + { + "world": "World1", + "rod": "Basic", + "luck": 1.13, + "silver_per_catch": 9.8, + "epic_plus": 4.58, + "mythic": 0.12 + }, + { + "world": "World1", + "rod": "Bamboo", + "luck": 1.23, + "silver_per_catch": 10.4, + "epic_plus": 4.94, + "mythic": 0.134 + }, + { + "world": "World1", + "rod": "Fiberglass", + "luck": 1.33, + "silver_per_catch": 10.9, + "epic_plus": 5.29, + "mythic": 0.147 + }, + { + "world": "World2", + "rod": "Carbon", + "luck": 1.51, + "silver_per_catch": 19.3, + "epic_plus": 5.86, + "mythic": 0.168 + }, + { + "world": "World2", + "rod": "Coral", + "luck": 1.66, + "silver_per_catch": 20.3, + "epic_plus": 6.3, + "mythic": 0.184 + }, + { + "world": "World2", + "rod": "Golden", + "luck": 1.81, + "silver_per_catch": 21.3, + "epic_plus": 6.69, + "mythic": 0.199 + }, + { + "world": "World3", + "rod": "Frost", + "luck": 2.11, + "silver_per_catch": 40.3, + "epic_plus": 7.4, + "mythic": 0.226 + }, + { + "world": "World3", + "rod": "Legend", + "luck": 2.31, + "silver_per_catch": 42.1, + "epic_plus": 7.8, + "mythic": 0.241 + } + ], + "wait_mult": { + "before": 0.131, + "after": 0.75 + }, + "auto": [ + { + "world": "World1", + "manual_fish_silver_min": 44.0, + "auto_silver_min": 10.1, + "auto_catches_min": 3.33, + "auto_xp_min": 0, + "manual_xp_min": 20 + }, + { + "world": "World2", + "manual_fish_silver_min": 85.9, + "auto_silver_min": 19.8, + "auto_catches_min": 3.33, + "auto_xp_min": 0, + "manual_xp_min": 28 + }, + { + "world": "World3", + "manual_fish_silver_min": 169.5, + "auto_silver_min": 36.1, + "auto_catches_min": 3.33, + "auto_xp_min": 0, + "manual_xp_min": 36 + } + ] +} diff --git a/docs/economy-v2.md b/docs/economy-v2.md new file mode 100644 index 0000000..bf72d6e --- /dev/null +++ b/docs/economy-v2.md @@ -0,0 +1,183 @@ +# Экономика v2: размеренное развитие, зелья, рынок игроков + +Дата: 2026-11-11. Реализовано в коде (Studio-тесты проходят). Расчёты баланса — [economy-balance.md](economy-balance.md) +(генерирует `py -3 tools/economy_model.py`). Это модель ожиданий; **время прохождения не подтверждено замерами**. + +## 1. Что было не так (аудит кода до v2) + +| Проблема | Где | Что происходило | +|---|---|---| +| Множители опыта складывались | `grantFish`, `Guild.xpMult` | серия до ×2, отдых ×2, первая поимка ×2, мутация ×2 — мифическая рыба давала до 14 400 XP за раз | +| Редкий улов и коллекция перепрыгивали уровни | `claimCollection`, `finishBoss`, цепочки | коллекция мира 1 — 6 490 XP, мира 3 — 77 880; босс до 3 000 XP; награды заданий × (1 + 0.25·(ур−1)) | +| Удача ускоряла всё сразу | `rollFish` | удача поднимала и цену, и опыт; при удаче ~8 мифическая весила больше обычной рыбы, шанс мутаций × удачу (×36 со всеми бонусами) | +| Слабое зелье продлевало сильное | `applyPotion` | `boostBonus = max(...)`, а время складывалось — дешёвое зелье продлевало эффект дорогого | +| Награды-зелья включались сами | цепочки, ежедневка, босс | зелье сгорало, даже если игрок не рыбачил | +| Клёв почти мгновенный | `onCast` | лучшая удочка ×0.342, с событием, дождём и червём — ×0.131 (0,65 с вместо 5 с) | +| Мир зависел от погоды и бестиария | `Guild.canEnter`, ранги D и B | Мир 2 требовал печатей (заказы раз в 3 ч ≈ 9 ч реального времени) и «Редкую» рыбу в дождь; Мир 3 — полной коллекции мира 1 вместе с мифической | +| Автоловля давала опыт | `autoFishLoop` | тот же опыт, что ручная ловля, без игрока у экрана | +| Мини-игре верили на слово | `onCatch` | клиент мог прислать «поймал» сразу после поклёвки | +| Сохранения без замка сессии | `saveData` | `SetAsync` поверх: при быстром переходе между серверами старый сервер мог перезаписать новый профиль | + +Модель (та же формула, 4 рыбы/мин): до v2 мир 2 открывался через ~12 минут, уровень 25 — через ~1 ч 11 мин; +доход в мире 1 ≈ 430 ⚪/мин против цены удочки «Легенда» 75 000. + +## 2. Решение: карьера отдельно от исследования + +* **Опыт карьеры** — только успешная **ручная** поимка: 5 / 7 / 9 XP в мирах 1 / 2 / 3 (`Config.Economy.careerXP`). + Редкость, вес, мутации, серия, первая поимка вида, отдых, зелья и пропуска его не меняют. Задания, босс, + коллекция, ежедневка, заказы, автоловля, ловушки и рынок опыта не дают. +* **Таблица уровней** `Config.LevelXP` (из предложения, допущения проверены по коду): при 4 рыбах/мин ур. 5 — 40 мин, + мир 2 (ур. 8) — 2 ч, мир 3 (ур. 18) — 11 ч, ур. 25 — 21 ч 40 мин. После 25 — +5 минут на уровень. +* **Редкое остаётся ярким** через серебро, коллекцию (+серебро и +10% удачи навсегда за мир), рекорды, + ленту улова, жемчуг за мутации и рынок. +* **Миры открывает только уровень**: `Config.Guild.worldRank = {}`. Ранг гильдии — параллельные возможности + (автоловля, ловушки, скидки). Вернуть требование ранга — одна строка конфига. +* **Скорость**: все ускорения клёва вместе не больше чем на 25% (`waitFloor`), минимум 2 с ожидания; + сервер не засчитывает подсечку быстрее 0,35 с на попадание. +* **Удача смягчена** (`Config.EffectiveLuck`): бонус растёт к потолку 3; мифическая даже при +1000% удачи < 1%; + мутации не чаще ×3 от базы. +* **Автоловля**: опыта нет, рыба ×0.6 цены, не чаще 1 рыбы за 18 с, зелья не действуют и не тратятся, задания не засчитывает. + Доход ≈ 20% ручного (см. economy-balance.md). +* **Отдых** теперь +25% серебра за пойманную рыбу (вместе с серией не больше +40%), а не ×2 опыта. + +## 3. Серебро и снаряжение + +Цели дохода свободного игрока: 60 / 120 / 240 ⚪/мин. Модель при 4 рыбах/мин: **63.6 / 121.7 / 238.1** +(рыба + задания + босс + заказы + ежедневка − обычные расходники). + +| | До v2 | После | +|---|---|---| +| Удочки | 0 / 150 / 600 / 1 800 / 4 500 / 9 000 / 25 000 / 75 000 | 0 / 600 / 1 400 / 3 000 / 6 000 / 15 000 / 30 000 / 75 000 | +| Сумки | 150 (ур.2) / 700 (4) / 2 500 (7) / 9 000 (12) / 30 000 (20) | 400 (2) / 1 000 (4) / 5 000 (10) / 15 000 (18) / 30 000 (21) | +| Улучшение удочки | 40…12 000 × (ур+1)^1.5; +8% удачи, клёв ×0.96 | 15…2 200 × (ур+1)^1.5; +4% удачи, клёв ×0.99 | +| Удача удочек | 0 … +200% | 0 … +100% | +| Рыба | мир 1: 5…2 000; мир 2: 18…5 000; мир 3: 48…15 000 | мир 1: 2…720; мир 2: 4…1 120; мир 3: 6…1 970 | +| Серия | +10% цены и опыта за рыбу, до ×2 | +2% цены, до +20% | +| Задания | серебро и опыт × (1 + 0.25·(ур−1)) | только серебро × tier мира (1 / 2 / 4) | +| Коллекция | 50…6 000 ⚪ и 40…4 000 XP × (1/4/12) | 25…125 ⚪ × tier, всё с мастерством = 600 / 1 200 / 2 400 | +| Босс | 300 ⚪ × мир × уровень + 250 XP × мир + зелье сразу | 60 ⚪ × tier + зелье в сумку | +| Ежедневка | 100…1 500 × (1 + 0.2·(ур−1)) | 60…400 × tier, зелья в сумку | +| Наживка | 40 / 90 / 120 / 400 за 10 | 15 / 30 / 40 / 150 за 10 | +| События | клёв ×0.5, ярмарка ×1.5, мутации ×3 | клёв ×0.85, ярмарка ×1.25, мутации ×2 | + +Маршрут покупок обычного игрока (модель): Bamboo 13 мин, Fiberglass 46 мин, Carbon 2 ч, Coral 3 ч 15 мин, +Golden 6 ч 41 мин, Frost 11 ч 46 мин, Legend 21 ч 56 мин; между удочками — сумки и улучшения (первые улучшения — с 1-й минуты). +Без расходников игра проходится: зелья и наживка не обязательны. + +**Платные преимущества сохранены как обещано**: VIP (+25% удачи и серебра), x2 Серебро, Талисман (+50% удачи), +Бездонная сумка (+100 мест), наборы серебра (формула «больше с уровнем» не менялась). Они ускоряют покупки, +но не уровни (опыт от них не зависел и раньше). Удача от пропусков проходит через новую мягкую формулу — +это изменение формулы удачи для всех, а не снятие бонуса. + +## 4. Зелья + +* Покупка, награды и донат кладут зелье **в сумку зелий**; пьёт игрок сам (магазин → вкладка «Зелья»). +* Одновременно действует одно. Другое — только с подтверждением; окно показывает, сколько осталось у прежнего + и что остаток пропадёт. То же зелье поверх добавляет попытки (до 60). Слабое не продлевает сильное. +* Новые зелья — **на попытки** (20): попытка засчитывается **при поклёвке** (дальше поймал, сорвалась или ушла). + Отмена до поклёвки — бесплатна; узнать редкость по поклёвке и отменить без траты нельзя. Эффект берётся + снимком при забросе. Автоловля зелья не использует и не тратит. Отключение после поклёвки — попытка уже потрачена. +* Роли: 🎯 Сосредоточение (зелёная зона +5%), 🔎 Исследователь (непойманные виды мира ×3), 🏆 Трофей (тяжелее рыба), + ⏱ Быстрый клёв (×0.9 в пределах общего потолка), ✨ Мутации (×1.5 в пределах потолка ×3). Зелий на опыт нет. +* Зелье ≠ наживка ≠ прикормка: зелье — на рыбака, наживка — какая рыба клюёт, прикормка (позже) — на место. +* **Донатное «Супер-зелье удачи»** (+200% удачи, 15 мин): теперь ложится в сумку и тратит **время игры**, а не + настенное. Купленное раньше и действующее при входе переносится как «Зелье удачи (старое)» с тем же + остатком секунд и той же силой — игрок ничего не теряет (раньше время шло и офлайн). + +## 5. Рынок игроков (первая версия) + +* Фиксированная цена, только игроки этого сервера, только серебро. Без Robux, вывода и новой валюты. +* С **8 уровня** (вместе с миром 2) — и продавцу, и покупателю. +* Рыба: «Эпическая» и реже или с мутацией Золотая/Радужная (`Config.Market`). +* Комиссия 5% с продавца, до 3 лотов, лот висит 30 минут, цена — от цены скупщика × 1.2 до × 50. + Нижняя граница исключает перепродажу скупщику с наваром; купленная рыба у скупщика — по базовой цене без + бонусов пропусков и ярмарки. +* Купить можно только рыбу из открытого покупателю мира. +* Купленная рыба: не открывает вид в коллекции, не даёт опыт, рекорды, задания, заказы гильдии и испытания; + хранит `origin` (кто, где, когда поймал), `gid`, `bought` и `history` (до 5 сделок). В сумке помечена «🛒 куплена». +* Покупка приходит в «Посылки» (никогда не теряется при полной сумке); снятый лот — в сумку или в посылки. +* Окно подтверждения показывает вид, редкость, мутацию, вес, продавца, цену, комиссию, выручку продавца, + цену скупщика и предупреждение, что цена — решение продавца. + +### Транзакции + +В Roblox нет атомарной записи двух профилей сразу, поэтому сделка — восстанавливаемый протокол с журналом +`FishMarket_v1` (ключ на лот, пишется один раз через `UpdateAsync`): + +1. Выставить: рыба → залог продавца, **сохранение продавца**, только потом лот виден. +2. Купить: лот блокируется в памяти, серебро списывается, запись `pending`, **сохранение покупателя**. +3. Журнал: `cas(lid, sold)`. Кто первым записал `sold` или `cancelled` — тот и решил. +4. Применить у обоих (идемпотентно), сохранить. +5. Неясный ответ журнала — не откатываем вслепую: повторяем `cas(cancelled)` и применяем то, что в журнале. +6. При входе игрока незавершённые залоги и `pending` разбираются по журналу (`Market.recover`), повтор — раз в минуту. + +Профили теперь под **замком сессии** (`PlayerStore`): профиль открыт только на одном сервере; замок старше +10 минут считается брошенным; если профиль ещё у другого сервера — игрока просят зайти через минуту. +Выход ждёт незавершённых сделок до 20 с, `BindToClose` сохраняет всех параллельно. +Без DataStore на живом сервере рынок закрыт; в Studio без API — журнал в памяти (данные всё равно не сохраняются). + +## 6. Миграция сохранений (`Progression.migrate`, `data.econ = 2`) + +* Уровень не меняется; доля заполнения текущего уровня переносится в новый порог. +* Серебро, жемчуг, печати, удочки, улучшения, сумки, пропуска, коллекция, рекорды — без изменений. +* Рыба в сумке сохраняет свою цену; получает `gid` и `origin.legacy`. +* Действующее старое зелье → «Зелье удачи (старое)» с остатком секунд. +* Отдых: те же секунды, но эффект — +25% серебра. +* Миграция однократна (повтор ничего не меняет); в данных остаётся запись `migration` (было/стало). +* Новые игроки сразу получают `econ = 2`. + +## 7. Телеметрия (`Telemetry.lua`, Roblox Analytics) + +* Серебро: `LogEconomyEvent` на каждое начисление и трату (продажа, задание, цепочка, босс, ежедневка, заказ, + коллекция, донат, рынок; удочки, сумки, улучшения, зелья, наживка, покупка на рынке). +* Опыт карьеры: копится по источникам, раз в 5 минут и при выходе — `CareerXP`. +* Уровни: `LogProgressionCompleteEvent("Career", level)`. +* Зелья: `PotionBought`, `PotionGranted`, `PotionActivated`. Рынок: `MarketListed`, `MarketBuy`, `MarketFee`. + Миграция: `EconomyMigrated`. +* В Studio: `game.ServerStorage.EconomyDebug:Invoke("telemetry")`. + +**Что измерить в первую очередь**: успешные ручные поимки в минуту за сессию (по `CareerXP` / минуты в игре). +Если реальный темп не 4, а 6–8 рыб/мин, пересчитать `Config.LevelXP` в `tools/economy_model.py`, а не замедлять клёв. + +## 8. Тесты + +`node tools/run-tests.js` (Studio открыт, скрипты синхронизированы Rojo): 4 набора, 45 проверок. + +* `tests/potions.spec.lua` — сумка, одно действующее, замена с подтверждением, слабое не продлевает сильное, + трата при поклёвке, время только в игре, перенос старого зелья. +* `tests/progression.spec.lua` — только ручная поимка даёт опыт, в конфиге нет других источников, кривая 120 / 660 / 1300 мин, + миграция (доля уровня, имущество, идемпотентность, переполненный опыт), потолки удачи и мутаций. +* `tests/market.spec.lua` — правила и цены (NaN, ∞, отрицательные, дробные), лимиты, двойная и одновременная + покупка, нехватка серебра, закрытый мир, сбой сохранения покупателя и продавца, журнал упал до и после записи, + истечение лота, полная сумка и посылки, падение сервера до и после фиксации в любом порядке входа, журнал + недоступен при входе, выход продавца во время сделки, спам запросов, перепродажа и история. +* `tests/playerstore.spec.lua` — замок сессии, перехват брошенного, запрет записи после перехвата, снятие замка, + ошибки хранилища, очередь сохранений. + +Тесты используют поддельные DataStore и журнал. **Живой DataStore** (настоящие задержки, лимиты, неясные ответы) +проверяется только в опубликованном плейсе. + +## 9. Проверка в Studio + +1. Rojo подключён (`rojo serve`, Plugins → Rojo → Connect), `node tools/run-tests.js` — «ALL 4 SUITES PASSED». +2. Play: верхняя панель «Уровень 1 · 0 / 100 XP»; поймать рыбу → «+5 XP», серебро 2–20. +3. Магазин → «Зелья»: купить «Сосредоточение» → в сумке зелий, не действует; «Выпить» → в HUD «🎯 20 поп.»; + другое зелье → окно «Заменить зелье?». Отмена до поклёвки не тратит попытку, поклёвка — тратит. +4. Рынок (кнопка «Рынок», клавиша K): до 8 уровня — замок. Для проверки в командной строке сервера: + `game.ServerStorage.EconomyDebug:Invoke("set", game.Players:GetPlayers()[1], "level", 10)` и + `...:Invoke("grant", player, "Som")` — эпическая рыба в сумку; выставить, снять, вернуть. + Покупку проверять с двумя игроками: Test → Clients and Servers → 2 Players. +5. Старое сохранение: в опубликованном плейсе зайти аккаунтом с прогрессом — уровень тот же, полоска опыта + заполнена на ту же долю. + +## 10. Что осталось и решения за вами + +* **Не замерено**: время до уровней и покупок — расчёт. Нужны телеметрия и плейтесты (новичок на телефоне, опытный, + платные пропуска, автоловля) минимум до мира 2. +* **Живой DataStore** для рынка и замка сессии в тестах не проверялся — только в опубликованном плейсе. +* **Наборы серебра за Robux** по-прежнему растут с уровнем (на ур. 25 «Гора золота» ≈ 92 000 ⚪, больше «Удочки Легенды»). + Описание товара это обещает, поэтому формула не тронута. Решите, менять ли её для будущих покупок + (вместе с текстом товара); уже купленное не затрагивается. +* Талисман удачи и VIP дают ту же прибавку к удаче, но удача теперь смягчена для всех — сообщите игрокам об изменении формулы. +* Заказы гильдии обновляются по-прежнему раз в 3 часа (не после сдачи), ранги — без требования для миров. +* Прикормка (зона) и система материалов/рецептов не делались: автоловля пока даёт только дополнительное серебро. diff --git a/docs/measured-progression-proposal.md b/docs/measured-progression-proposal.md new file mode 100644 index 0000000..ce7037f --- /dev/null +++ b/docs/measured-progression-proposal.md @@ -0,0 +1,86 @@ +# Размеренное развитие — предложение для теста + +Дата: 2026-11-11. Основание: src/ReplicatedStorage/FishConfig.lua, GameServer.server.lua, Guild.lua. +Это новый вариант дизайна, не внедрённый баланс. Старый guild-economy-design.md не заменён. + +## Границы расчёта + +Нет фактической телеметрии сессий. Скрипт tools/progression_budget.py считает математические ожидания текущего улова и бюджет предложенной кривой. Это не полная симуляция игры: он не воспроизводит покупку снастей, поведение игрока, погоду, задачи, неудачи, случайные хвосты распределений и пройденные испытания. Ожидание текущей стоимости игнорирует поштучное округление. Цены предметов и доход ниже — целевой бюджет, а не вывод из новой таблицы рыб: её ещё требуется откалибровать. + +Время в предложении — суммарная эффективная игра с продажами и обычными перемещениями, без AFK. База: 4 успешные ручные поимки за минуту, проверка чувствительности: 3 и 5. Нельзя дополнительно прибавлять время продаж, уже включённое в этот показатель. Для реальных игроков измерить именно поимки за минуту сессии. + +## Почему текущее развитие разгоняется + +- XP до уровня 8: 3608, до уровня 18: 32773, до уровня 25: 78639. +- Серия даёт до x2 XP, отдых ещё x2, первая поимка вида ещё x2. Мутация дополнительно удваивает базовый XP. +- Первая мифическая рыба первого мира без мутации при полной серии и отдыхе: 900*2*2*2=7200 XP. С мутацией: 14400. Награда коллекции мифической редкости даёт отдельно 4000 XP. +- Удача повышает долю рыб с большим XP, поэтому улучшение снастей и зелья ускоряют карьеру сразу через частоту и качество улова. +- Босс: до 250/1000/3000 XP в мирах 1/2/3. Награда серебром дополнительно растёт с уровнем игрока. +- Коллекция: 6490 XP в первом мире, 25960 во втором, 77880 в третьем за все категории. Это разовые награды, не постоянный доход. +- Награды цепочек растут с уровнем, а зелье автоматически включается по завершении цепочки. +- Поэтому простой множитель требований к уровню не устранит случайные скачки и разные темпы игроков. + +## Основное решение + +Разделить карьерный уровень и исследование. Карьера открывает миры и основные классы снастей; исследование конкретных рыб открывает подсказки, рецепты, оформление и целевые экспедиции. + +XP карьеры за успешную ручную поимку: мир 1 = 5, мир 2 = 7, мир 3 = 9. Редкость, вес, мутации, серия, первая поимка и отдых этот XP не умножают. Задачи, боссы и коллекции дают серебро, материалы, печати, исследование, но не карьерный XP. Исследование не конвертируется обратно в XP карьеры. Не добавлять платные множители карьерного XP. + +За сложную и редкую рыбу награждать стоимостью, исследованием и трофеями. Следить, чтобы эти награды оправдывали более длинное вываживание. Это сознательный компромисс: карьерный темп становится стабильнее, а ценность редкости сохраняется в других системах. + +Автоловля и офлайн-ловушки производят материалы и часть серебра без карьерного XP. Это предложение изменения текущей механики; сначала проверить отдельной тестовой версией и объяснить игрокам. Допускается вариант со слабым XP автоловли, но его необходимо рассчитывать отдельно с учётом фактического количества AFK-часов. + +## Кривая + +Полная таблица: progression-level-table.md. Данные: progression-budget-results.json. + +Уровень 3: 13 минут; 5: 40 минут; 8/мир 2: 120 минут; 10: 195 минут; 13: 335 минут; 18/мир 3: 660 минут; 25: 1300 минут. + +При 3 поимках/мин: мир 2 за 160 минут, мир 3 за 880, уровень 25 за 1733. +При 5 поимках/мин: мир 2 за 96 минут, мир 3 за 528, уровень 25 за 1040. + +По сравнению с базой игрок с 5 поимками/мин быстрее на 20%, с 3 — медленнее на 33%. Это сценарии чувствительности, не процентили аудитории. 21 ч 40 мин до уровня 25 предполагают содержательные занятия на это время. Если контент не выдерживает длительность, сокращать целевые интервалы, а не добавлять ожидание поклёвки. + +## Скорость снастей и расходников + +Текущий множитель ожидания лучшей удочки со звёздами: 0.42*0.96^5 ≈ 0.342; при событии клёва x0.5, дожде x0.85, черве x0.9 — около 0.131. Среднее ожидание 5 секунд превращается в 0.65 секунды. Это только поклёвка, не полный цикл. + +Предлагается: суммарное сокращение ожидания от снастей/погоды/расходников не выше 25%; ровный ритм без ускорения анимаций. Если замеры дают 6–8 поимок за минуту сессии, пересчитать XP-пороги по фактической скорости, а не заставлять ждать искусственно. Зелья и прикормки меняют цель, вес и удобство ловли, а не карьерный XP. Удача не должна многократно разгонять серебро без контроля. Зелья выдаются предметами, один эффект одновременно, дешёвые не продлевают сильные. + +## Бюджет серебра + +База без покупок за Robux, после обычных расходников, но до покупки оборудования: 60/120/240 серебра в минуту для миров 1/2/3. Включает продажу, задания, средний вклад боссов и разовых наград. Это целевые средние, не текущие цифры кода. Бюджет не означает обрезание реального дохода игрока. + +| Этап | Минут | Доход этапа | Снасти | Сумки | Улучшения | Косметика | Остаток этапа | +|---|---:|---:|---:|---:|---:|---:|---:| +| Мир 1, до ур.8 | 120 | 7200 | 5000 | 1400 | 400 | 0 | 400 | +| Мир 2, до ур.18 | 540 | 64800 | 51000 | 5000 | 6000 | 0 | 2800 | +| Мир 3, до ур.25 | 640 | 153600 | 75000 | 15000 | 30000 | 20000 | 13600 | + +Остатки переносятся: 400, затем 3200, затем 16800. Косметика и часть улучшений необязательны. Доход, пропущенные покупки и удачные трофеи меняют накопления. Контрольные суммы в таблице сходятся, но доступность каждой покупки по времени требует тестирования маршрута. + +Предлагаемые цены последовательных удочек: Basic 0; Bamboo 600 (ур.3); Fiberglass 1400 (ур.5); Carbon 3000 (ур.8); Coral 6000 (ур.10); Golden 15000 (ур.13); Frost 30000 (ур.18); Legend 75000 (ур.25). Первая сумка 400, следующая 1000. При базовом доходе ранний маршрут: Bamboo около 13-й минуты, сумка около 20-й, Fiberglass около 40-й. Carbon оплачивается из бюджета первого мира при открытии второго, Frost — из бюджета второго при открытии третьего. + +Не повышать цены одинаковым множителем: поздний доход уже значительно выше раннего. Сохранить нормальный бесплатный базовый способ ловли. Расходники должны иметь понятную задачу, а не превращаться в обязательный налог. + +## Награды и ритм + +Убрать XP из коллекций и босса; сначала выдать рецепты, ингредиенты, тематические предметы. Серебро за полный набор категорий коллекции одного мира ограничить бюджетом примерно 10 минут базового дохода: 600/1200/2400, распределёнными по категориям. Босс: ориентир 60/120/240 серебра при полноценном участии, без множителя уровня; количество побед учитывается в общем бюджете. Первичные значения нужно проверить против целевых 60/120/240 дохода в минуту. + +Не выдавать сразу много бесплатных зелий. Обучение — 1–2 демонстрационных расходника, дальше рецепты и выбор наград. Ежедневка — материалы и небольшой выбор полезных предметов, без XP и сброса календаря за пропуск. + +Раз в 10–15 минут должно быть небольшое достижение (рецепт, информация о рыбе, этап заказа), раз в 30–60 минут — заметное улучшение. Это не обязательная частота всплывающих окон. Награды можно собирать в журнале без постоянных фанфар. + +Гильдия: обычные заказы обновляются после сдачи. Миры открываются на 8/18 без дополнительной стены ожидания погоды или полного бестиария. Ранг даёт параллельные возможности. Если оставить ранг обязательным, его достижение нужно включить в модель до обещания указанных времён. + +## Проверка и переход + +1. Измерить поимки/минуту всей сессии, XP/минуту по источникам, серебро по источникам/расходам, время до уровней и покупок. +2. Отдельно: новичок на телефоне, опытный игрок, усиленный комплект, платные преимущества, автоловля. Проверить 3/4/5/6+ успешных поимок/минуту, серии, разовые коллекции и события. +3. Протестировать новый профиль минимум до мира 2 и продолжение профилей уровней 8/18. Математическая модель не заменяет эти проверки. +4. Ввести версию экономики. Не понижать уровни и не удалять имущество; переносить долю заполнения текущего уровня в новый порог. Отдельно решить компенсацию ранее оплаченных преимуществ; не конвертировать их молча. +5. Изменять XP и серебро раздельно; сравнивать темп и возвраты, а не только длину сессии. + +Roblox Economy Events позволяют измерять источники, расходы и остатки ресурсов: https://create.roblox.com/docs/production/analytics/economy-events . В текущем поиске по src вызовов Analytics/LogEconomy не обнаружено. + +Скрипт запуска: py -3 tools/progression_budget.py . Он обновляет только два расчётных документа в docs и не меняет игровой баланс. diff --git a/docs/progression-budget-results.json b/docs/progression-budget-results.json new file mode 100644 index 0000000..b3a095b --- /dev/null +++ b/docs/progression-budget-results.json @@ -0,0 +1,339 @@ +{ + "assumptions": "Current: stationary catch expectations, excludes quests, first discoveries, collection rewards and catch timing. Proposed: budget model, 4 successful manual catches/effective minute, fixed career XP 5/7/9 per world; no other career XP sources or multipliers. Proposed world access exactly at levels 8/18; guild must not add delays. Effective minutes include normal travel/selling, exclude AFK.", + "current_xp_to_level": { + "3": 201, + "5": 949, + "8": 3608, + "18": 32773, + "25": 78639 + }, + "current_expectations": [ + { + "world": 1, + "luck": 1, + "xp_per_catch": 21.517, + "silver_per_catch_before_combo_sale": 23.679, + "xp_per_min_4_catches_combo2": 172.14 + }, + { + "world": 1, + "luck": 1.8, + "xp_per_catch": 41.985, + "silver_per_catch_before_combo_sale": 55.337, + "xp_per_min_4_catches_combo2": 335.88 + }, + { + "world": 2, + "luck": 2.5, + "xp_per_catch": 104.747, + "silver_per_catch_before_combo_sale": 183.605, + "xp_per_min_4_catches_combo2": 837.98 + }, + { + "world": 3, + "luck": 4, + "xp_per_catch": 279.672, + "silver_per_catch_before_combo_sale": 725.492, + "xp_per_min_4_catches_combo2": 2237.38 + } + ], + "proposed_levels": [ + { + "from_level": 1, + "to_level": 2, + "world": 1, + "xp_required": 100, + "target_minutes": 5, + "cumulative_minutes": 5 + }, + { + "from_level": 2, + "to_level": 3, + "world": 1, + "xp_required": 160, + "target_minutes": 8, + "cumulative_minutes": 13 + }, + { + "from_level": 3, + "to_level": 4, + "world": 1, + "xp_required": 240, + "target_minutes": 12, + "cumulative_minutes": 25 + }, + { + "from_level": 4, + "to_level": 5, + "world": 1, + "xp_required": 300, + "target_minutes": 15, + "cumulative_minutes": 40 + }, + { + "from_level": 5, + "to_level": 6, + "world": 1, + "xp_required": 400, + "target_minutes": 20, + "cumulative_minutes": 60 + }, + { + "from_level": 6, + "to_level": 7, + "world": 1, + "xp_required": 500, + "target_minutes": 25, + "cumulative_minutes": 85 + }, + { + "from_level": 7, + "to_level": 8, + "world": 1, + "xp_required": 700, + "target_minutes": 35, + "cumulative_minutes": 120 + }, + { + "from_level": 8, + "to_level": 9, + "world": 2, + "xp_required": 980, + "target_minutes": 35, + "cumulative_minutes": 155 + }, + { + "from_level": 9, + "to_level": 10, + "world": 2, + "xp_required": 1120, + "target_minutes": 40, + "cumulative_minutes": 195 + }, + { + "from_level": 10, + "to_level": 11, + "world": 2, + "xp_required": 1260, + "target_minutes": 45, + "cumulative_minutes": 240 + }, + { + "from_level": 11, + "to_level": 12, + "world": 2, + "xp_required": 1260, + "target_minutes": 45, + "cumulative_minutes": 285 + }, + { + "from_level": 12, + "to_level": 13, + "world": 2, + "xp_required": 1400, + "target_minutes": 50, + "cumulative_minutes": 335 + }, + { + "from_level": 13, + "to_level": 14, + "world": 2, + "xp_required": 1540, + "target_minutes": 55, + "cumulative_minutes": 390 + }, + { + "from_level": 14, + "to_level": 15, + "world": 2, + "xp_required": 1680, + "target_minutes": 60, + "cumulative_minutes": 450 + }, + { + "from_level": 15, + "to_level": 16, + "world": 2, + "xp_required": 1820, + "target_minutes": 65, + "cumulative_minutes": 515 + }, + { + "from_level": 16, + "to_level": 17, + "world": 2, + "xp_required": 1960, + "target_minutes": 70, + "cumulative_minutes": 585 + }, + { + "from_level": 17, + "to_level": 18, + "world": 2, + "xp_required": 2100, + "target_minutes": 75, + "cumulative_minutes": 660 + }, + { + "from_level": 18, + "to_level": 19, + "world": 3, + "xp_required": 2700, + "target_minutes": 75, + "cumulative_minutes": 735 + }, + { + "from_level": 19, + "to_level": 20, + "world": 3, + "xp_required": 2880, + "target_minutes": 80, + "cumulative_minutes": 815 + }, + { + "from_level": 20, + "to_level": 21, + "world": 3, + "xp_required": 3060, + "target_minutes": 85, + "cumulative_minutes": 900 + }, + { + "from_level": 21, + "to_level": 22, + "world": 3, + "xp_required": 3240, + "target_minutes": 90, + "cumulative_minutes": 990 + }, + { + "from_level": 22, + "to_level": 23, + "world": 3, + "xp_required": 3420, + "target_minutes": 95, + "cumulative_minutes": 1085 + }, + { + "from_level": 23, + "to_level": 24, + "world": 3, + "xp_required": 3600, + "target_minutes": 100, + "cumulative_minutes": 1185 + }, + { + "from_level": 24, + "to_level": 25, + "world": 3, + "xp_required": 4140, + "target_minutes": 115, + "cumulative_minutes": 1300 + } + ], + "milestones": [ + { + "from_level": 2, + "to_level": 3, + "world": 1, + "xp_required": 160, + "target_minutes": 8, + "cumulative_minutes": 13 + }, + { + "from_level": 4, + "to_level": 5, + "world": 1, + "xp_required": 300, + "target_minutes": 15, + "cumulative_minutes": 40 + }, + { + "from_level": 7, + "to_level": 8, + "world": 1, + "xp_required": 700, + "target_minutes": 35, + "cumulative_minutes": 120 + }, + { + "from_level": 9, + "to_level": 10, + "world": 2, + "xp_required": 1120, + "target_minutes": 40, + "cumulative_minutes": 195 + }, + { + "from_level": 12, + "to_level": 13, + "world": 2, + "xp_required": 1400, + "target_minutes": 50, + "cumulative_minutes": 335 + }, + { + "from_level": 17, + "to_level": 18, + "world": 2, + "xp_required": 2100, + "target_minutes": 75, + "cumulative_minutes": 660 + }, + { + "from_level": 24, + "to_level": 25, + "world": 3, + "xp_required": 4140, + "target_minutes": 115, + "cumulative_minutes": 1300 + } + ], + "sensitivity": [ + { + "catches_per_effective_minute": 3, + "to_level": 8, + "minutes": 160.0 + }, + { + "catches_per_effective_minute": 3, + "to_level": 18, + "minutes": 880.0 + }, + { + "catches_per_effective_minute": 3, + "to_level": 25, + "minutes": 1733.3 + }, + { + "catches_per_effective_minute": 4, + "to_level": 8, + "minutes": 120.0 + }, + { + "catches_per_effective_minute": 4, + "to_level": 18, + "minutes": 660.0 + }, + { + "catches_per_effective_minute": 4, + "to_level": 25, + "minutes": 1300.0 + }, + { + "catches_per_effective_minute": 5, + "to_level": 8, + "minutes": 96.0 + }, + { + "catches_per_effective_minute": 5, + "to_level": 18, + "minutes": 528.0 + }, + { + "catches_per_effective_minute": 5, + "to_level": 25, + "minutes": 1040.0 + } + ] +} diff --git a/docs/progression-level-table.md b/docs/progression-level-table.md new file mode 100644 index 0000000..6cd3104 --- /dev/null +++ b/docs/progression-level-table.md @@ -0,0 +1,30 @@ +# Предлагаемая кривая уровней + +Расчёт бюджета, не замер живых игроков и не симуляция клиента. 4 успешные ручные поимки за минуту эффективной игры, включая обычные перемещения и продажу, без AFK. Опыт карьеры: 5/7/9 за рыбу миров 1/2/3. Других источников и множителей XP карьеры нет. Доступ к мирам на уровнях 8/18; ранг не добавляет ожидания. Таблица не применена к игре. + +| Переход | Мир | XP на переход | Минут на переход | Минут всего | +|---|---:|---:|---:|---:| +| 1 → 2 | 1 | 100 | 5 | 5 | +| 2 → 3 | 1 | 160 | 8 | 13 | +| 3 → 4 | 1 | 240 | 12 | 25 | +| 4 → 5 | 1 | 300 | 15 | 40 | +| 5 → 6 | 1 | 400 | 20 | 60 | +| 6 → 7 | 1 | 500 | 25 | 85 | +| 7 → 8 | 1 | 700 | 35 | 120 | +| 8 → 9 | 2 | 980 | 35 | 155 | +| 9 → 10 | 2 | 1120 | 40 | 195 | +| 10 → 11 | 2 | 1260 | 45 | 240 | +| 11 → 12 | 2 | 1260 | 45 | 285 | +| 12 → 13 | 2 | 1400 | 50 | 335 | +| 13 → 14 | 2 | 1540 | 55 | 390 | +| 14 → 15 | 2 | 1680 | 60 | 450 | +| 15 → 16 | 2 | 1820 | 65 | 515 | +| 16 → 17 | 2 | 1960 | 70 | 585 | +| 17 → 18 | 2 | 2100 | 75 | 660 | +| 18 → 19 | 3 | 2700 | 75 | 735 | +| 19 → 20 | 3 | 2880 | 80 | 815 | +| 20 → 21 | 3 | 3060 | 85 | 900 | +| 21 → 22 | 3 | 3240 | 90 | 990 | +| 22 → 23 | 3 | 3420 | 95 | 1085 | +| 23 → 24 | 3 | 3600 | 100 | 1185 | +| 24 → 25 | 3 | 4140 | 115 | 1300 | diff --git a/src/ReplicatedStorage/FishConfig.lua b/src/ReplicatedStorage/FishConfig.lua index 8b459a6..7f4263d 100644 --- a/src/ReplicatedStorage/FishConfig.lua +++ b/src/ReplicatedStorage/FishConfig.lua @@ -8,8 +8,9 @@ Config.GameName = "Клёвое место" ---------------------------------------------------------------- миры -- center = центр мира на карте; mult = множитель наград коллекции Config.Worlds = { + -- tier — множитель серебряных наград мира (задания, босс, коллекция, ежедневка): доход 60 / 120 / 240 ⚪ в минуту { - id = "World1", name = "Тихое озеро", icon = "🌊", level = 1, mult = 1, + id = "World1", name = "Тихое озеро", icon = "🌊", level = 1, mult = 1, tier = 1, center = Vector3.new(0, 0, 1500), color = Color3.fromRGB(60, 200, 255), desc = "Спокойное лесное озеро. Отличное место, чтобы начать.", clock = 16.2, @@ -48,7 +49,7 @@ Config.Worlds = { }, }, { - id = "World2", name = "Тропический остров", icon = "🏝", level = 8, mult = 4, + id = "World2", name = "Тропический остров", icon = "🏝", level = 8, mult = 4, tier = 2, center = Vector3.new(1500, 0, 0), color = Color3.fromRGB(255, 190, 70), desc = "Бирюзовое море, пальмы и яркая рифовая рыба.", clock = 13, @@ -56,7 +57,7 @@ Config.Worlds = { sea = 74, -- всё дальше этого радиуса от центра — море (лагуна вокруг острова, пляж — кольцо ~r 64..79) }, { - id = "World3", name = "Ледяной фьорд", icon = "❄", level = 18, mult = 12, + id = "World3", name = "Ледяной фьорд", icon = "❄", level = 18, mult = 12, tier = 4, center = Vector3.new(-1500, 0, 0), color = Color3.fromRGB(150, 220, 255), desc = "Рыбалка в лунках среди льдов и северного сияния.", clock = 18.3, @@ -72,7 +73,7 @@ Config.Worlds = { terrainColors = { Snow = Color3.fromRGB(205, 212, 228) }, }, { - id = "World4", name = "Вулкан", icon = "🌋", level = 30, mult = 30, soon = true, + id = "World4", name = "Вулкан", icon = "🌋", level = 30, mult = 30, tier = 8, soon = true, center = Vector3.new(0, 0, -1500), color = Color3.fromRGB(255, 90, 40), desc = "Рыбалка в лаве. Скоро!", }, @@ -281,69 +282,71 @@ end Config.Zones = { World1 = { fish = { - F({ id = "Karas", name = "Карась", rarity = "Common", price = 5, xp = 8, minW = 0.2, maxW = 1.2, size = 1.0, shape = "tall", color = Color3.fromRGB(205, 170, 75), color2 = Color3.fromRGB(170, 120, 50) }), - F({ id = "Plotva", name = "Плотва", rarity = "Common", price = 6, xp = 8, minW = 0.1, maxW = 0.8, size = 0.9, shape = "classic", color = Color3.fromRGB(195, 200, 210), color2 = Color3.fromRGB(220, 80, 60) }), - F({ id = "Ersh", name = "Ёрш", rarity = "Common", price = 7, xp = 9, minW = 0.1, maxW = 0.4, size = 0.8, shape = "classic", color = Color3.fromRGB(135, 125, 75), color2 = Color3.fromRGB(95, 85, 50), spikes = true, spots = 6 }), - F({ id = "Okun", name = "Окунь", rarity = "Uncommon", price = 15, xp = 18, minW = 0.3, maxW = 1.5, size = 1.0, shape = "classic", color = Color3.fromRGB(150, 180, 70), color2 = Color3.fromRGB(230, 90, 40), stripes = 5, spikes = true }), - F({ id = "Lesh", name = "Лещ", rarity = "Uncommon", price = 18, xp = 20, minW = 0.5, maxW = 3.0, size = 1.2, shape = "tall", color = Color3.fromRGB(175, 145, 95), color2 = Color3.fromRGB(120, 95, 60) }), - F({ id = "Lin", name = "Линь", rarity = "Uncommon", price = 20, xp = 22, minW = 0.4, maxW = 2.5, size = 1.1, shape = "classic", color = Color3.fromRGB(95, 125, 55), color2 = Color3.fromRGB(60, 85, 35) }), - F({ id = "Shuka", name = "Щука", rarity = "Rare", price = 45, xp = 45, minW = 1.0, maxW = 8.0, size = 1.5, shape = "long", color = Color3.fromRGB(110, 140, 85), color2 = Color3.fromRGB(200, 210, 150), spots = 12 }), - F({ id = "Sudak", name = "Судак", rarity = "Rare", price = 50, xp = 48, minW = 1.0, maxW = 6.0, size = 1.4, shape = "long", color = Color3.fromRGB(165, 165, 135), color2 = Color3.fromRGB(80, 80, 70), stripes = 6, spikes = true }), - F({ id = "Som", name = "Сом", rarity = "Epic", price = 130, xp = 110, minW = 5.0, maxW = 40, size = 2.0, shape = "long", color = Color3.fromRGB(75, 75, 90), color2 = Color3.fromRGB(180, 175, 160), whiskers = true }), - F({ id = "Koi", name = "Карп кои", rarity = "Epic", price = 150, xp = 120, minW = 2.0, maxW = 9.0, size = 1.4, shape = "classic", color = Color3.fromRGB(250, 245, 240), color2 = Color3.fromRGB(240, 110, 40), spots = 7, whiskers = true }), - F({ id = "Gold", name = "Золотая рыбка", rarity = "Legendary", price = 500, xp = 350, minW = 0.1, maxW = 0.5, size = 0.9, shape = "classic", color = Color3.fromRGB(255, 195, 40), color2 = Color3.fromRGB(255, 120, 30), glow = true, bigTail = true }), - F({ id = "Crystal", name = "Хрустальный осётр", rarity = "Mythic", price = 2000, xp = 900, minW = 10, maxW = 60, size = 2.0, shape = "sturgeon", color = Color3.fromRGB(150, 230, 255), color2 = Color3.fromRGB(230, 250, 255), glow = true, glass = true }), + F({ id = "Karas", name = "Карась", rarity = "Common", price = 2, minW = 0.2, maxW = 1.2, size = 1.0, shape = "tall", color = Color3.fromRGB(205, 170, 75), color2 = Color3.fromRGB(170, 120, 50) }), + F({ id = "Plotva", name = "Плотва", rarity = "Common", price = 2, minW = 0.1, maxW = 0.8, size = 0.9, shape = "classic", color = Color3.fromRGB(195, 200, 210), color2 = Color3.fromRGB(220, 80, 60) }), + F({ id = "Ersh", name = "Ёрш", rarity = "Common", price = 3, minW = 0.1, maxW = 0.4, size = 0.8, shape = "classic", color = Color3.fromRGB(135, 125, 75), color2 = Color3.fromRGB(95, 85, 50), spikes = true, spots = 6 }), + F({ id = "Okun", name = "Окунь", rarity = "Uncommon", price = 6, minW = 0.3, maxW = 1.5, size = 1.0, shape = "classic", color = Color3.fromRGB(150, 180, 70), color2 = Color3.fromRGB(230, 90, 40), stripes = 5, spikes = true }), + F({ id = "Lesh", name = "Лещ", rarity = "Uncommon", price = 6, minW = 0.5, maxW = 3.0, size = 1.2, shape = "tall", color = Color3.fromRGB(175, 145, 95), color2 = Color3.fromRGB(120, 95, 60) }), + F({ id = "Lin", name = "Линь", rarity = "Uncommon", price = 7, minW = 0.4, maxW = 2.5, size = 1.1, shape = "classic", color = Color3.fromRGB(95, 125, 55), color2 = Color3.fromRGB(60, 85, 35) }), + F({ id = "Shuka", name = "Щука", rarity = "Rare", price = 16, minW = 1.0, maxW = 8.0, size = 1.5, shape = "long", color = Color3.fromRGB(110, 140, 85), color2 = Color3.fromRGB(200, 210, 150), spots = 12 }), + F({ id = "Sudak", name = "Судак", rarity = "Rare", price = 18, minW = 1.0, maxW = 6.0, size = 1.4, shape = "long", color = Color3.fromRGB(165, 165, 135), color2 = Color3.fromRGB(80, 80, 70), stripes = 6, spikes = true }), + F({ id = "Som", name = "Сом", rarity = "Epic", price = 46, minW = 5.0, maxW = 40, size = 2.0, shape = "long", color = Color3.fromRGB(75, 75, 90), color2 = Color3.fromRGB(180, 175, 160), whiskers = true }), + F({ id = "Koi", name = "Карп кои", rarity = "Epic", price = 52, minW = 2.0, maxW = 9.0, size = 1.4, shape = "classic", color = Color3.fromRGB(250, 245, 240), color2 = Color3.fromRGB(240, 110, 40), spots = 7, whiskers = true }), + F({ id = "Gold", name = "Золотая рыбка", rarity = "Legendary", price = 185, minW = 0.1, maxW = 0.5, size = 0.9, shape = "classic", color = Color3.fromRGB(255, 195, 40), color2 = Color3.fromRGB(255, 120, 30), glow = true, bigTail = true }), + F({ id = "Crystal", name = "Хрустальный осётр", rarity = "Mythic", price = 720, minW = 10, maxW = 60, size = 2.0, shape = "sturgeon", color = Color3.fromRGB(150, 230, 255), color2 = Color3.fromRGB(230, 250, 255), glow = true, glass = true }), }, }, World2 = { fish = { - F({ id = "Clown", name = "Рыба-клоун", rarity = "Common", price = 18, xp = 18, minW = 0.1, maxW = 0.4, size = 0.8, shape = "classic", color = Color3.fromRGB(255, 120, 30), color2 = Color3.fromRGB(255, 255, 255), stripes = 3 }), - F({ id = "Sergeant", name = "Рыба-сержант", rarity = "Common", price = 20, xp = 18, minW = 0.2, maxW = 0.9, size = 0.9, shape = "tall", color = Color3.fromRGB(240, 230, 110), color2 = Color3.fromRGB(40, 40, 45), stripes = 5 }), - F({ id = "Mullet", name = "Барабулька", rarity = "Common", price = 22, xp = 20, minW = 0.1, maxW = 0.6, size = 0.9, shape = "classic", color = Color3.fromRGB(235, 110, 100), color2 = Color3.fromRGB(255, 220, 120), whiskers = true }), - F({ id = "Angel", name = "Рыба-ангел", rarity = "Uncommon", price = 45, xp = 40, minW = 0.3, maxW = 1.5, size = 1.0, shape = "tall", color = Color3.fromRGB(60, 120, 230), color2 = Color3.fromRGB(255, 220, 40), stripes = 4, bigFins = true }), - F({ id = "Puffer", name = "Иглобрюх", rarity = "Uncommon", price = 50, xp = 42, minW = 0.3, maxW = 2.0, size = 1.0, shape = "puffer", color = Color3.fromRGB(230, 205, 140), color2 = Color3.fromRGB(110, 90, 60), spots = 10 }), - F({ id = "Parrot", name = "Рыба-попугай", rarity = "Uncommon", price = 55, xp = 45, minW = 1.0, maxW = 5.0, size = 1.2, shape = "classic", color = Color3.fromRGB(60, 210, 190), color2 = Color3.fromRGB(240, 90, 180), spots = 5 }), - F({ id = "Ray", name = "Скат", rarity = "Rare", price = 120, xp = 90, minW = 3.0, maxW = 25, size = 1.6, shape = "ray", color = Color3.fromRGB(110, 115, 140), color2 = Color3.fromRGB(230, 230, 240), spots = 14 }), - F({ id = "Barracuda", name = "Барракуда", rarity = "Rare", price = 130, xp = 95, minW = 2.0, maxW = 20, size = 1.7, shape = "long", color = Color3.fromRGB(175, 185, 200), color2 = Color3.fromRGB(60, 70, 85), stripes = 8 }), - F({ id = "Swordfish", name = "Рыба-меч", rarity = "Epic", price = 350, xp = 220, minW = 30, maxW = 200, size = 2.0, shape = "sword", color = Color3.fromRGB(55, 75, 130), color2 = Color3.fromRGB(200, 210, 230) }), - F({ id = "Moray", name = "Мурена", rarity = "Epic", price = 320, xp = 210, minW = 2.0, maxW = 15, size = 1.8, shape = "eel", color = Color3.fromRGB(80, 140, 60), color2 = Color3.fromRGB(230, 220, 90), spots = 12 }), - F({ id = "Shark", name = "Рифовая акула", rarity = "Legendary", price = 1200, xp = 700, minW = 40, maxW = 180, size = 2.4, shape = "shark", color = Color3.fromRGB(110, 125, 145), color2 = Color3.fromRGB(235, 235, 240) }), - F({ id = "SunJelly", name = "Солнечная медуза", rarity = "Mythic", price = 5000, xp = 2000, minW = 1.0, maxW = 8.0, size = 1.8, shape = "jelly", color = Color3.fromRGB(255, 200, 80), color2 = Color3.fromRGB(255, 120, 200), glow = true, glass = true }), + F({ id = "Clown", name = "Рыба-клоун", rarity = "Common", price = 4, minW = 0.1, maxW = 0.4, size = 0.8, shape = "classic", color = Color3.fromRGB(255, 120, 30), color2 = Color3.fromRGB(255, 255, 255), stripes = 3 }), + F({ id = "Sergeant", name = "Рыба-сержант", rarity = "Common", price = 5, minW = 0.2, maxW = 0.9, size = 0.9, shape = "tall", color = Color3.fromRGB(240, 230, 110), color2 = Color3.fromRGB(40, 40, 45), stripes = 5 }), + F({ id = "Mullet", name = "Барабулька", rarity = "Common", price = 5, minW = 0.1, maxW = 0.6, size = 0.9, shape = "classic", color = Color3.fromRGB(235, 110, 100), color2 = Color3.fromRGB(255, 220, 120), whiskers = true }), + F({ id = "Angel", name = "Рыба-ангел", rarity = "Uncommon", price = 10, minW = 0.3, maxW = 1.5, size = 1.0, shape = "tall", color = Color3.fromRGB(60, 120, 230), color2 = Color3.fromRGB(255, 220, 40), stripes = 4, bigFins = true }), + F({ id = "Puffer", name = "Иглобрюх", rarity = "Uncommon", price = 11, minW = 0.3, maxW = 2.0, size = 1.0, shape = "puffer", color = Color3.fromRGB(230, 205, 140), color2 = Color3.fromRGB(110, 90, 60), spots = 10 }), + F({ id = "Parrot", name = "Рыба-попугай", rarity = "Uncommon", price = 12, minW = 1.0, maxW = 5.0, size = 1.2, shape = "classic", color = Color3.fromRGB(60, 210, 190), color2 = Color3.fromRGB(240, 90, 180), spots = 5 }), + F({ id = "Ray", name = "Скат", rarity = "Rare", price = 27, minW = 3.0, maxW = 25, size = 1.6, shape = "ray", color = Color3.fromRGB(110, 115, 140), color2 = Color3.fromRGB(230, 230, 240), spots = 14 }), + F({ id = "Barracuda", name = "Барракуда", rarity = "Rare", price = 29, minW = 2.0, maxW = 20, size = 1.7, shape = "long", color = Color3.fromRGB(175, 185, 200), color2 = Color3.fromRGB(60, 70, 85), stripes = 8 }), + F({ id = "Swordfish", name = "Рыба-меч", rarity = "Epic", price = 77, minW = 30, maxW = 200, size = 2.0, shape = "sword", color = Color3.fromRGB(55, 75, 130), color2 = Color3.fromRGB(200, 210, 230) }), + F({ id = "Moray", name = "Мурена", rarity = "Epic", price = 72, minW = 2.0, maxW = 15, size = 1.8, shape = "eel", color = Color3.fromRGB(80, 140, 60), color2 = Color3.fromRGB(230, 220, 90), spots = 12 }), + F({ id = "Shark", name = "Рифовая акула", rarity = "Legendary", price = 270, minW = 40, maxW = 180, size = 2.4, shape = "shark", color = Color3.fromRGB(110, 125, 145), color2 = Color3.fromRGB(235, 235, 240) }), + F({ id = "SunJelly", name = "Солнечная медуза", rarity = "Mythic", price = 1120, minW = 1.0, maxW = 8.0, size = 1.8, shape = "jelly", color = Color3.fromRGB(255, 200, 80), color2 = Color3.fromRGB(255, 120, 200), glow = true, glass = true }), }, }, World3 = { fish = { - F({ id = "Cod", name = "Треска", rarity = "Common", price = 55, xp = 40, minW = 1.0, maxW = 10, size = 1.2, shape = "classic", color = Color3.fromRGB(150, 150, 110), color2 = Color3.fromRGB(230, 225, 200), spots = 14, whiskers = true }), - F({ id = "Herring", name = "Сельдь", rarity = "Common", price = 50, xp = 38, minW = 0.2, maxW = 0.8, size = 0.9, shape = "long", color = Color3.fromRGB(150, 175, 205), color2 = Color3.fromRGB(70, 100, 140) }), - F({ id = "Capelin", name = "Мойва", rarity = "Common", price = 48, xp = 36, minW = 0.05, maxW = 0.2, size = 0.7, shape = "classic", color = Color3.fromRGB(170, 200, 190), color2 = Color3.fromRGB(80, 120, 110) }), - F({ id = "Flounder", name = "Камбала", rarity = "Uncommon", price = 140, xp = 90, minW = 0.5, maxW = 4.0, size = 1.2, shape = "flat", color = Color3.fromRGB(150, 125, 90), color2 = Color3.fromRGB(230, 120, 60), spots = 10 }), - F({ id = "Redfish", name = "Морской окунь", rarity = "Uncommon", price = 150, xp = 92, minW = 0.5, maxW = 5.0, size = 1.1, shape = "classic", color = Color3.fromRGB(225, 70, 60), color2 = Color3.fromRGB(255, 160, 120), spikes = true }), - F({ id = "Char", name = "Арктический голец", rarity = "Uncommon", price = 160, xp = 95, minW = 0.5, maxW = 6.0, size = 1.2, shape = "long", color = Color3.fromRGB(120, 130, 150), color2 = Color3.fromRGB(255, 130, 150), spots = 12 }), - F({ id = "Halibut", name = "Палтус", rarity = "Rare", price = 380, xp = 200, minW = 5.0, maxW = 90, size = 1.9, shape = "flat", color = Color3.fromRGB(90, 95, 80), color2 = Color3.fromRGB(150, 150, 130), spots = 16 }), - F({ id = "Wolffish", name = "Морской волк", rarity = "Rare", price = 400, xp = 210, minW = 3.0, maxW = 20, size = 1.7, shape = "long", color = Color3.fromRGB(110, 120, 140), color2 = Color3.fromRGB(60, 65, 80), stripes = 7, teeth = true }), - F({ id = "Angler", name = "Удильщик", rarity = "Epic", price = 1100, xp = 500, minW = 5.0, maxW = 50, size = 1.6, shape = "angler", color = Color3.fromRGB(60, 50, 70), color2 = Color3.fromRGB(120, 255, 230), glow = true }), - F({ id = "IceEel", name = "Ледяная мурена", rarity = "Epic", price = 1000, xp = 480, minW = 3.0, maxW = 25, size = 1.9, shape = "eel", color = Color3.fromRGB(150, 210, 245), color2 = Color3.fromRGB(240, 250, 255), glass = true }), - F({ id = "Greenland", name = "Полярная акула", rarity = "Legendary", price = 3500, xp = 1500, minW = 200, maxW = 900, size = 2.6, shape = "shark", color = Color3.fromRGB(80, 90, 100), color2 = Color3.fromRGB(160, 170, 180) }), - F({ id = "Leviathan", name = "Ледяной левиафан", rarity = "Mythic", price = 15000, xp = 4000, minW = 500, maxW = 3000, size = 2.4, shape = "eel", color = Color3.fromRGB(110, 230, 255), color2 = Color3.fromRGB(200, 120, 255), glow = true, spikes = true }), + F({ id = "Cod", name = "Треска", rarity = "Common", price = 7, minW = 1.0, maxW = 10, size = 1.2, shape = "classic", color = Color3.fromRGB(150, 150, 110), color2 = Color3.fromRGB(230, 225, 200), spots = 14, whiskers = true }), + F({ id = "Herring", name = "Сельдь", rarity = "Common", price = 7, minW = 0.2, maxW = 0.8, size = 0.9, shape = "long", color = Color3.fromRGB(150, 175, 205), color2 = Color3.fromRGB(70, 100, 140) }), + F({ id = "Capelin", name = "Мойва", rarity = "Common", price = 6, minW = 0.05, maxW = 0.2, size = 0.7, shape = "classic", color = Color3.fromRGB(170, 200, 190), color2 = Color3.fromRGB(80, 120, 110) }), + F({ id = "Flounder", name = "Камбала", rarity = "Uncommon", price = 18, minW = 0.5, maxW = 4.0, size = 1.2, shape = "flat", color = Color3.fromRGB(150, 125, 90), color2 = Color3.fromRGB(230, 120, 60), spots = 10 }), + F({ id = "Redfish", name = "Морской окунь", rarity = "Uncommon", price = 20, minW = 0.5, maxW = 5.0, size = 1.1, shape = "classic", color = Color3.fromRGB(225, 70, 60), color2 = Color3.fromRGB(255, 160, 120), spikes = true }), + F({ id = "Char", name = "Арктический голец", rarity = "Uncommon", price = 21, minW = 0.5, maxW = 6.0, size = 1.2, shape = "long", color = Color3.fromRGB(120, 130, 150), color2 = Color3.fromRGB(255, 130, 150), spots = 12 }), + F({ id = "Halibut", name = "Палтус", rarity = "Rare", price = 49, minW = 5.0, maxW = 90, size = 1.9, shape = "flat", color = Color3.fromRGB(90, 95, 80), color2 = Color3.fromRGB(150, 150, 130), spots = 16 }), + F({ id = "Wolffish", name = "Морской волк", rarity = "Rare", price = 52, minW = 3.0, maxW = 20, size = 1.7, shape = "long", color = Color3.fromRGB(110, 120, 140), color2 = Color3.fromRGB(60, 65, 80), stripes = 7, teeth = true }), + F({ id = "Angler", name = "Удильщик", rarity = "Epic", price = 143, minW = 5.0, maxW = 50, size = 1.6, shape = "angler", color = Color3.fromRGB(60, 50, 70), color2 = Color3.fromRGB(120, 255, 230), glow = true }), + F({ id = "IceEel", name = "Ледяная мурена", rarity = "Epic", price = 131, minW = 3.0, maxW = 25, size = 1.9, shape = "eel", color = Color3.fromRGB(150, 210, 245), color2 = Color3.fromRGB(240, 250, 255), glass = true }), + F({ id = "Greenland", name = "Полярная акула", rarity = "Legendary", price = 460, minW = 200, maxW = 900, size = 2.6, shape = "shark", color = Color3.fromRGB(80, 90, 100), color2 = Color3.fromRGB(160, 170, 180) }), + F({ id = "Leviathan", name = "Ледяной левиафан", rarity = "Mythic", price = 1970, minW = 500, maxW = 3000, size = 2.4, shape = "eel", color = Color3.fromRGB(110, 230, 255), color2 = Color3.fromRGB(200, 120, 255), glow = true, spikes = true }), }, }, } ---------------------------------------------------------------- удочки -- luck = бонус удачи, speed = множитель ожидания клёва (меньше = быстрее), zone = ширина зелёной зоны, --- icon = картинка удочки в хотбаре (Tool.TextureId) +-- icon = картинка удочки в хотбаре (Tool.TextureId). +-- Экономика v2: удочка ускоряет клёв умеренно (всё вместе — не больше чем на 25%, Config.Economy.waitFloor), +-- удача растёт плавно — лучшая снасть даёт заметно больше дорогой рыбы, но не делает мифическую обычной Config.Rods = { - { id = "Basic", name = "Старая удочка", price = 0, level = 1, luck = 0.00, speed = 1.00, zone = 0.22, upgradeCost = 40, style = "wood", icon = "rbxassetid://83350883185349" }, - { id = "Bamboo", name = "Бамбуковая удочка", price = 150, level = 3, luck = 0.15, speed = 0.88, zone = 0.25, upgradeCost = 120, style = "bamboo", icon = "rbxassetid://98615001898640" }, - { id = "Fiberglass", name = "Стеклопластиковая", price = 600, level = 5, luck = 0.30, speed = 0.78, zone = 0.27, upgradeCost = 300, style = "glass", icon = "rbxassetid://100031752289540" }, - { id = "Carbon", name = "Карбоновая удочка", price = 1800, level = 8, luck = 0.55, speed = 0.68, zone = 0.29, upgradeCost = 700, style = "carbon", icon = "rbxassetid://71788597596034" }, - { id = "Coral", name = "Коралловая удочка", price = 4500, level = 10, luck = 0.80, speed = 0.62, zone = 0.31, upgradeCost = 1300, style = "coral", icon = "rbxassetid://139114393074237" }, - { id = "Golden", name = "Золотая удочка", price = 9000, level = 13, luck = 1.00, speed = 0.56, zone = 0.33, upgradeCost = 2200, style = "gold", icon = "rbxassetid://83212298735071" }, - { id = "Frost", name = "Ледяная удочка", price = 25000, level = 18, luck = 1.40, speed = 0.50, zone = 0.35, upgradeCost = 5000, style = "frost", icon = "rbxassetid://134579643216329" }, - { id = "Legend", name = "Удочка Легенды", price = 75000, level = 25, luck = 2.00, speed = 0.42, zone = 0.38, upgradeCost = 12000, style = "legend", icon = "rbxassetid://84863811378769" }, + { id = "Basic", name = "Старая удочка", price = 0, level = 1, luck = 0.00, speed = 1.00, zone = 0.22, upgradeCost = 15, style = "wood", icon = "rbxassetid://83350883185349" }, + { id = "Bamboo", name = "Бамбуковая удочка", price = 600, level = 3, luck = 0.10, speed = 0.97, zone = 0.25, upgradeCost = 25, style = "bamboo", icon = "rbxassetid://98615001898640" }, + { id = "Fiberglass", name = "Стеклопластиковая", price = 1400, level = 5, luck = 0.20, speed = 0.95, zone = 0.27, upgradeCost = 50, style = "glass", icon = "rbxassetid://100031752289540" }, + { id = "Carbon", name = "Карбоновая удочка", price = 3000, level = 8, luck = 0.30, speed = 0.93, zone = 0.29, upgradeCost = 100, style = "carbon", icon = "rbxassetid://71788597596034" }, + { id = "Coral", name = "Коралловая удочка", price = 6000, level = 10, luck = 0.45, speed = 0.91, zone = 0.31, upgradeCost = 200, style = "coral", icon = "rbxassetid://139114393074237" }, + { id = "Golden", name = "Золотая удочка", price = 15000, level = 13, luck = 0.60, speed = 0.89, zone = 0.33, upgradeCost = 450, style = "gold", icon = "rbxassetid://83212298735071" }, + { id = "Frost", name = "Ледяная удочка", price = 30000, level = 18, luck = 0.80, speed = 0.87, zone = 0.35, upgradeCost = 900, style = "frost", icon = "rbxassetid://134579643216329" }, + { id = "Legend", name = "Удочка Легенды", price = 75000, level = 25, luck = 1.00, speed = 0.85, zone = 0.38, upgradeCost = 2200, style = "legend", icon = "rbxassetid://84863811378769" }, } -Config.RodUpgrade = { maxLevel = 5, luckPerLevel = 0.08, zonePerLevel = 0.012, speedPerLevel = 0.96 } +Config.RodUpgrade = { maxLevel = 5, luckPerLevel = 0.04, zonePerLevel = 0.012, speedPerLevel = 0.99 } function Config.UpgradeCost(rod, currentLevel) return math.floor(rod.upgradeCost * (currentLevel + 1) ^ 1.5) end @@ -351,53 +354,143 @@ end ---------------------------------------------------------------- сумки Config.Bags = { { id = "Pouch", name = "Холщовая сумка", price = 0, level = 1, capacity = 12, color = Color3.fromRGB(170, 140, 95) }, - { id = "Satchel", name = "Сумка рыбака", price = 150, level = 2, capacity = 25, color = Color3.fromRGB(110, 140, 80) }, - { id = "Backpack", name = "Туристический рюкзак", price = 700, level = 4, capacity = 45, color = Color3.fromRGB(60, 110, 180) }, - { id = "BigNet", name = "Огромный садок", price = 2500, level = 7, capacity = 80, color = Color3.fromRGB(200, 80, 50) }, - { id = "Chest", name = "Сундук за спиной", price = 9000, level = 12, capacity = 140, color = Color3.fromRGB(140, 90, 50) }, - { id = "Magic", name = "Магический мешок", price = 30000, level = 20, capacity = 250, color = Color3.fromRGB(120, 60, 200) }, + { id = "Satchel", name = "Сумка рыбака", price = 400, level = 2, capacity = 25, color = Color3.fromRGB(110, 140, 80) }, + { id = "Backpack", name = "Туристический рюкзак", price = 1000, level = 4, capacity = 45, color = Color3.fromRGB(60, 110, 180) }, + { id = "BigNet", name = "Огромный садок", price = 5000, level = 10, capacity = 80, color = Color3.fromRGB(200, 80, 50) }, + { id = "Chest", name = "Сундук за спиной", price = 15000, level = 18, capacity = 140, color = Color3.fromRGB(140, 90, 50) }, + { id = "Magic", name = "Магический мешок", price = 30000, level = 21, capacity = 250, color = Color3.fromRGB(120, 60, 200) }, } ---------------------------------------------------------------- удача -Config.LuckPerPlayerLevel = 0.02 -- +2% за уровень игрока +Config.LuckPerPlayerLevel = 0.01 -- +1% за уровень игрока Config.MasteryLuck = 0.10 -- +10% навсегда за полностью собранный мир + +---------------------------------------------------------------- экономика v2 +-- Карьера (уровень) и исследование (коллекция, рекорды, редкости) разделены: +-- * опыт карьеры даёт ТОЛЬКО успешная ручная поимка, фиксированно по миру (careerXP); +-- редкость, вес, мутации, серия, первая поимка вида и отдых его не умножают; +-- * задания, босс, коллекция, ежедневка — серебро, жемчуг и зелья, без опыта; +-- * автоловля и ловушки — дополнительный доход без опыта. +-- Модель баланса: tools/economy_model.py (py -3 tools/economy_model.py), итоги — docs/economy-balance.md +Config.Economy = { + version = 2, + careerXP = { World1 = 5, World2 = 7, World3 = 9 }, + autoXP = 0, + -- удача: бонус (удача − 1) смягчается к потолку luckCap; вес редкости = база × (1 + бонус × rarityLuck), + -- у «Обычной» — база ÷ (1 + бонус × rarityLuck.Common) + luckCap = 3, + rarityLuck = { Common = 0.3, Uncommon = 0.35, Rare = 0.7, Epic = 1.0, Legendary = 1.3, Mythic = 1.6 }, + -- мутации: шанс × (1 + бонус × mutationLuck) × события/погода/наживка/зелье, но всё вместе не больше × mutationCap + mutationLuck = 0.5, + mutationCap = 3, + -- клёв: все ускорения вместе (удочка, улучшения, событие, погода, наживка, зелье) не короче waitFloor от базы + waitFloor = 0.75, + minBite = 2.0, + -- сервер не засчитывает подсечку быстрее reelPerHit секунд на каждое попадание (защита от мгновенной «мини-игры») + reelPerHit = 0.35, + -- надбавки к цене пойманной рыбы складываются и ограничены valueBonusCap (серия + отдых) + valueBonusCap = 0.4, + restSilver = 0.25, + -- автоловля: рыба дешевле, цикл не короче autoMinCycle секунд + autoValue = 0.6, + autoMinCycle = 18, + -- версия формулы опыта до экономики v2 (для переноса доли текущего уровня) + legacyXP = function(level) + return math.floor(50 * level ^ 1.6) + end, +} + +-- опыт карьеры на переход с уровня N на N+1 (N = индекс). Цель: 4 успешные ручные поимки в минуту +-- эффективной игры (с продажей и переходами, без AFK): ур. 5 ≈ 40 мин, ур. 8 (Мир 2) ≈ 2 ч, ур. 18 (Мир 3) ≈ 11 ч, +-- ур. 25 ≈ 21,7 ч. Это расчёт, а не замер: проверять по телеметрии (CareerXP, LevelUp) +Config.LevelXP = { + 100, 160, 240, 300, 400, 500, 700, -- 1→8, Мир 1: 5 XP за рыбу + 980, 1120, 1260, 1260, 1400, 1540, 1680, 1820, 1960, 2100, -- 8→18, Мир 2: 7 XP + 2700, 2880, 3060, 3240, 3420, 3600, 4140, -- 18→25, Мир 3: 9 XP +} +-- после 25-го уровня: +5 минут на каждый следующий (36 XP в минуту в Мире 3) +Config.LevelXPAfter = { perMinute = 36, minutes = 115, step = 5 } + +---------------------------------------------------------------- зелья +-- Зелье действует на рыбака, наживка — на то, какая рыба клюёт, прикормка (позже) — на место. +-- Купленные и полученные зелья лежат в сумке зелий; пьёт их игрок сам. Одновременно — одно зелье. +-- charges — число попыток: попытка засчитывается, когда рыба клюнула (дальше — поймал, сорвалась или ушла); +-- отмена до поклёвки и автоловля заряды не тратят. +-- duration — зелья на время (донат): секунды тикают, пока игрок в игре. +-- Эффекты: zone — шире зелёная зона мини-игры; weightCurve — показатель кривой веса (меньше = тяжелее, база 2.2); +-- newSpecies — вес ещё не пойманных видов текущего мира; mutation — множитель шанса мутаций (в пределах mutationCap); +-- speed — множитель ожидания клёва (в пределах waitFloor); luck — бонус удачи Config.Potions = { - { id = "Luck1", name = "Зелье удачи", price = 120, bonus = 0.5, duration = 300, color = Color3.fromRGB(90, 230, 120) }, - { id = "Luck2", name = "Большое зелье удачи", price = 450, bonus = 1.0, duration = 600, color = Color3.fromRGB(255, 200, 60), level = 5 }, - { id = "Luck3", name = "Эликсир фортуны", price = 2500, bonus = 2.0, duration = 600, color = Color3.fromRGB(200, 120, 255), level = 12 }, + { id = "Focus", name = "Зелье сосредоточения", icon = "🎯", price = 150, level = 3, charges = 20, zone = 0.05, + color = Color3.fromRGB(110, 200, 255), desc = "Зелёная зона мини-игры шире на 5%: меньше срывов" }, + { id = "Research", name = "Зелье исследователя", icon = "🔎", price = 250, level = 4, charges = 20, newSpecies = 3, + color = Color3.fromRGB(150, 230, 140), desc = "Непойманные виды этого мира попадаются в 3 раза чаще" }, + { id = "Trophy", name = "Зелье трофея", icon = "🏆", price = 300, level = 5, charges = 20, weightCurve = 1.4, + color = Color3.fromRGB(255, 200, 80), desc = "Рыба тяжелее: больше рекордов и заказов на вес" }, + { id = "Swift", name = "Зелье быстрого клёва", icon = "⏱", price = 200, level = 6, charges = 20, speed = 0.9, + color = Color3.fromRGB(255, 150, 90), desc = "Клюёт на 10% быстрее (общий предел ускорения — 25%)" }, + { id = "Mutation", name = "Зелье мутаций", icon = "✨", price = 600, level = 10, charges = 20, mutation = 1.5, + color = Color3.fromRGB(220, 130, 255), desc = "Мутации в 1,5 раза чаще (общий предел — ×3)" }, + -- донат (Developer Product «Luck»): не продаётся за серебро + { id = "SuperLuck", name = "Супер-зелье удачи", icon = "🍀", duration = 900, luck = 2.0, paid = true, + color = Color3.fromRGB(90, 230, 120), desc = "+200% удачи на 15 минут игры" }, + -- зелье удачи из сохранений до v2 (оставшееся время перенесено как есть) + { id = "Legacy", name = "Зелье удачи (старое)", icon = "🍀", duration = 0, luck = 0, legacy = true, + color = Color3.fromRGB(90, 230, 120), desc = "Удача от зелья, выпитого до обновления" }, +} +Config.PotionMaxCharges = 60 -- то же зелье можно допить сверху, но не больше стольких попыток + +---------------------------------------------------------------- рынок игроков +-- Фиксированная цена, только на этом сервере, за серебро. Без Robux и обмена «рыба на рыбу». +Config.Market = { + enabled = true, -- при недоступном DataStore рынок выключается сам (кроме Studio — там тестовое хранилище) + studioFakeLedger = true, -- в Studio без доступа к API: журнал сделок в памяти (данные игроков всё равно не сохраняются) + minLevel = 8, -- доступ — с открытия Мира 2: ранний игрок не обходит прогресс + minRank = 4, -- «Эпическая» и реже… + mutations = { Golden = true, Rainbow = true }, -- …или любая рыба с этими мутациями + fee = 0.05, -- комиссия с продавца + maxListings = 3, -- лотов у одного продавца + duration = 1800, -- секунд, потом лот снимается и рыба возвращается + minPriceMult = 1.2, -- цена не ниже цены скупщика × 1.2 (перепродать скупщику дороже невозможно) + maxPriceMult = 50, -- и не выше × 50 (защита от опечатки) + inboxMax = 50, -- посылок (купленная/возвращённая рыба), если сумка полна + actionCooldown = 0.4, -- секунд между действиями рынка } ---------------------------------------------------------------- коллекция --- награда за то, что поймал ВСЕ виды одной редкости в мире (умножается на mult мира) +-- награда за то, что поймал ВСЕ виды одной редкости в мире (× tier мира); опыт карьеры коллекция не даёт. +-- Всё вместе с мастерством ≈ 10 минут дохода мира: 600 / 1200 / 2400 ⚪ Config.CollectionRewards = { - Common = { coins = 50, xp = 40 }, - Uncommon = { coins = 120, xp = 100 }, - Rare = { coins = 300, xp = 250 }, - Epic = { coins = 800, xp = 600 }, - Legendary = { coins = 2000, xp = 1500 }, - Mythic = { coins = 6000, xp = 4000 }, + Common = { coins = 25 }, + Uncommon = { coins = 40 }, + Rare = { coins = 60 }, + Epic = { coins = 90 }, + Legendary = { coins = 110 }, + Mythic = { coins = 125 }, } -Config.MasteryCoins = 5000 -- за весь мир (тоже умножается на mult) +Config.MasteryCoins = 150 -- за весь мир (× tier) и +10% удачи навсегда ---------------------------------------------------------------- цепочки заданий -- короткие задания идут по очереди: награда сразу, следующее появляется мгновенно. -- после последнего шага — бонус цепочки и следующая цепочка; каждый новый круг цели растут --- coins/xp = награда за 1 единицу цели (умножается на цель и уровень игрока); --- max — потолок цели, byLevel — цель растёт с уровнем игрока; +-- coins = серебро за 1 единицу цели (× цель × tier мира, где игрок открыл самый дальний мир), не меньше +-- Config.QuestMinCoins × tier; опыт карьеры задания не дают. +-- max — потолок цели, byLevel — цель растёт с tier (заработать на продаже); -- forms — слово после числа для 1 / 2–4 / 5+ (подставляется вместо второго %s) local FISH, TIMES = { "рыбу", "рыбы", "рыб" }, { "раз", "раза", "раз" } Config.QuestKinds = { - catch = { text = "Поймай %d %s", forms = FISH, coins = 5, xp = 4 }, - uncommon = { text = "Поймай %d %s «Необычная» или реже", forms = FISH, coins = 18, xp = 14 }, - rare = { text = "Поймай %d %s «Редкая» или реже", forms = FISH, coins = 60, xp = 50 }, - perfect = { text = "Подсеки %d %s без промаха", forms = TIMES, coins = 10, xp = 8 }, - perfectCast = { text = "Забрось в зелёную зону %d %s", forms = TIMES, coins = 8, xp = 6 }, - combo = { text = "Набери серию из %d рыб", coins = 12, xp = 10, max = 15 }, - sell = { text = "Продай %d %s", forms = FISH, coins = 3, xp = 3 }, - earn = { text = "Заработай %d ⚪ на продаже", coins = 0.25, xp = 0.2, byLevel = true }, - buy = { text = "Купи что-нибудь в магазине", coins = 40, xp = 30, max = 1 }, - boss = { text = "Нанеси боссу %d урона", coins = 15, xp = 12 }, + catch = { text = "Поймай %d %s", forms = FISH, coins = 1 }, + uncommon = { text = "Поймай %d %s «Необычная» или реже", forms = FISH, coins = 4 }, + rare = { text = "Поймай %d %s «Редкая» или реже", forms = FISH, coins = 12 }, + perfect = { text = "Подсеки %d %s без промаха", forms = TIMES, coins = 2 }, + perfectCast = { text = "Забрось в зелёную зону %d %s", forms = TIMES, coins = 2 }, + combo = { text = "Набери серию из %d рыб", coins = 2, max = 15 }, + sell = { text = "Продай %d %s", forms = FISH, coins = 0.5 }, + earn = { text = "Заработай %d ⚪ на продаже", coins = 0.05, byLevel = true }, + buy = { text = "Купи что-нибудь в магазине", coins = 15, max = 1 }, + boss = { text = "Нанеси боссу %d урона", coins = 2 }, } +Config.QuestMinCoins = 3 Config.QuestChains = { { name = "🎣 Утренний клёв", steps = { { "catch", 3 }, { "perfectCast", 2 }, { "sell", 3 }, { "catch", 5 }, { "uncommon", 1 } } }, { name = "🔥 Без промаха", steps = { { "perfect", 3 }, { "combo", 3 }, { "catch", 6 }, { "earn", 80 }, { "combo", 5 } } }, @@ -405,21 +498,24 @@ Config.QuestChains = { { name = "🏆 Мастер озера", steps = { { "combo", 6 }, { "catch", 10 }, { "perfect", 6 }, { "rare", 2 }, { "earn", 300 } } }, } Config.QuestTierGrowth = 0.5 -- каждый следующий круг цепочек: цели ×(1 + 0.5 · номер круга) -Config.ChainBonus = { coins = 120, xp = 100, potion = "Luck1" } -- за всю цепочку (растёт с уровнем и кругом) +-- за всю цепочку: серебро (× tier и растёт с кругом); зелье в сумку зелий — за первую цепочку +-- (знакомство с зельями) и за каждый пройденный круг из всех цепочек (одно из potions) +Config.ChainBonus = { coins = 30, firstPotion = "Focus", roundPotions = { "Focus", "Research", "Trophy" } } ---------------------------------------------------------------- серия улова --- каждая рыба подряд без срыва: +10% к цене и опыту следующей, до ×2; +-- каждая рыба подряд без срыва: +2% к цене следующей, до +20% (опыт карьеры серия не меняет); -- срыв, ушедшая рыба или timeout секунд без улова — серия сгорает -Config.Combo = { step = 0.1, max = 2.0, timeout = 90 } +Config.Combo = { step = 0.02, max = 0.2, timeout = 90 } ---------------------------------------------------------------- босс озера -- раз в interval секунд в мир, где больше всего игроков, приплывает босс. Его ловят всем сервером: -- каждая пойманная там рыба наносит урон = ранг редкости (+1 за подсечку без промаха). --- Если за duration секунд урона хватило — награда всем, кто помог (× mult мира, минимум 40% за малый вклад) +-- Если за duration секунд урона хватило — награда всем, кто помог (× tier мира, минимум 40% за малый вклад); +-- опыта карьеры нет, зелье — в сумку зелий Config.Boss = { firstDelay = 240, interval = 600, duration = 180, hpPerPlayer = 12, - reward = { coins = 300, xp = 250, potion = "Luck1" }, + reward = { coins = 60, potion = "Trophy" }, worlds = { World1 = { name = "Сом-великан", fish = "Som", mutation = "Golden", scale = 5 }, World2 = { name = "Королевская акула", fish = "Shark", mutation = "Golden", scale = 3 }, @@ -427,23 +523,23 @@ Config.Boss = { }, } --- ежедневная награда (7 дней по кругу), серебро растёт с уровнем +-- ежедневная награда (7 дней по кругу): серебро × tier мира, зелья — в сумку зелий; пропуск дня не наказывает Config.DailyRewards = { - { coins = 100 }, - { coins = 200 }, - { coins = 300, potion = "Luck1" }, - { coins = 450 }, - { coins = 600, potion = "Luck1" }, - { coins = 800 }, - { coins = 1500, potion = "Luck2" }, + { coins = 60 }, + { coins = 90 }, + { coins = 120, potion = "Focus" }, + { coins = 150 }, + { coins = 180, potion = "Trophy" }, + { coins = 240 }, + { coins = 400, potion = "Mutation" }, } ---------------------------------------------------------------- события на сервере Config.Events = { - { id = "Bite", name = "⚡ Клёвый час", desc = "Рыба клюёт в 2 раза быстрее", duration = 180, speed = 0.5 }, + { id = "Bite", name = "⚡ Клёвый час", desc = "Рыба клюёт на 15% быстрее", duration = 180, speed = 0.85 }, { id = "Luck", name = "🍀 Удачный ветер", desc = "Удача +50% для всех", duration = 180, luck = 0.5 }, - { id = "Stars", name = "🌟 Звездопад", desc = "Мутации в 3 раза чаще", duration = 180, mutation = 3 }, - { id = "Fair", name = "🐟 Рыбная ярмарка", desc = "Рыба продаётся на 50% дороже", duration = 180, sell = 1.5 }, + { id = "Stars", name = "🌟 Звездопад", desc = "Мутации в 2 раза чаще", duration = 180, mutation = 2 }, + { id = "Fair", name = "🐟 Рыбная ярмарка", desc = "Рыба продаётся на 25% дороже", duration = 180, sell = 1.25 }, } Config.EventFirstDelay = 120 Config.EventGapMin = 420 @@ -487,9 +583,9 @@ end Config.Weathers = { { id = "Clear", name = "Ясно", icon = "☀", weight = 40, duration = { 240, 420 } }, { id = "Cloudy", name = "Пасмурно", icon = "☁", weight = 25, duration = { 180, 360 }, luck = 0.05, desc = "Удача +5%" }, - { id = "Rain", name = "Дождь", icon = "🌧", weight = 20, duration = { 150, 300 }, speed = 0.85, desc = "Клюёт на 15% быстрее", + { id = "Rain", name = "Дождь", icon = "🌧", weight = 20, duration = { 150, 300 }, speed = 0.92, desc = "Клюёт на 8% быстрее", names = { World3 = "Снегопад" } }, - { id = "Storm", name = "Гроза", icon = "⛈", weight = 8, duration = { 120, 240 }, luck = 0.25, speed = 0.9, desc = "Удача +25%", + { id = "Storm", name = "Гроза", icon = "⛈", weight = 8, duration = { 120, 240 }, luck = 0.25, speed = 0.95, desc = "Удача +25%", names = { World3 = "Метель" } }, { id = "Fog", name = "Туман", icon = "🌫", weight = 7, duration = { 150, 300 }, mutation = 1.5, desc = "Мутации ×1.5" }, } @@ -565,7 +661,8 @@ Config.Products = { { key = "Coins1", id = 3728142264, robux = 49, icon = "👝", name = "Кошель серебра", desc = "+1 000 серебра (больше с уровнем)", coins = 1000 }, { key = "Coins2", id = 3728142848, robux = 199, icon = "⚪", name = "Сундук серебра", desc = "+5 000 серебра (больше с уровнем)", coins = 5000 }, { key = "Coins3", id = 3728142885, robux = 599, icon = "🏆", name = "Гора золота", desc = "+20 000 серебра (больше с уровнем)", coins = 20000 }, - { key = "Luck", id = 3728142916, robux = 99, icon = "🧪", name = "Супер-зелье удачи", desc = "+200% удачи на 15 минут", boost = 2.0, duration = 900 }, + -- зелье ложится в сумку зелий (выпить — когда удобно); 15 минут считаются, пока игрок в игре + { key = "Luck", id = 3728142916, robux = 99, icon = "🧪", name = "Супер-зелье удачи", desc = "+200% удачи на 15 минут игры (в сумку зелий)", potion = "SuperLuck" }, } ---------------------------------------------------------------- рыбалка @@ -586,10 +683,62 @@ Config.TutorialDone = 4 function Config.HitsNeeded(rank) return math.ceil(rank / 2) end --- опыт до следующего уровня: до 8-го ≈ 3 600 (1,5–2 часа вместе с заказами гильдии); --- у старых сохранений уровень не понижается — копится только опыт внутри уровня +-- опыт до следующего уровня — таблица Config.LevelXP (экономика v2). У старых сохранений уровень не меняется, +-- а доля заполнения текущего уровня переносится в новый порог (миграция в Progression.lua) function Config.XPForLevel(level) - return math.floor(50 * level ^ 1.6) + level = math.max(1, math.floor(level)) + local t = Config.LevelXP[level] + if t then + return t + end + local a = Config.LevelXPAfter + return a.perMinute * (a.minutes + a.step * (level - #Config.LevelXP)) +end + +-- опыт карьеры за успешную ручную поимку в мире +function Config.CareerXP(worldId) + return Config.Economy.careerXP[worldId] or 0 +end + +-- удача → эффективный бонус: выше единицы растёт всё медленнее к Economy.luckCap; ниже единицы (автоловля) — штраф +function Config.EffectiveLuck(luck) + local b = (luck or 1) - 1 + if b <= 0 then + return math.max(-0.8, b) + end + local cap = Config.Economy.luckCap + return cap * (1 - math.exp(-b / cap)) +end + +-- вес вида данной редкости при эффективном бонусе удачи +function Config.RarityWeight(rarity, beff) + local r = Config.Rarities[rarity] + local k = Config.Economy.rarityLuck[rarity] or 0 + if r.rank == 1 then + return r.weight / math.max(0.2, 1 + beff * k) + end + return r.weight * math.max(0.2, 1 + beff * k) +end + +-- множитель шанса мутаций: от удачи и прочих множителей (события, погода, наживка, зелье), не больше mutationCap +function Config.MutationMult(beff, other) + return math.min(Config.Economy.mutationCap, math.max(0.2, 1 + beff * Config.Economy.mutationLuck) * (other or 1)) +end + +-- множитель ожидания клёва: все ускорения вместе не короче waitFloor +function Config.WaitMult(product) + return math.max(Config.Economy.waitFloor, product) +end + +-- самый дальний открытый мир игрока по уровню (для tier наград) +function Config.TierFor(level) + local tier = 1 + for _, w in ipairs(Config.Worlds) do + if not w.soon and level >= w.level then + tier = math.max(tier, w.tier or 1) + end + end + return tier end ---------------------------------------------------------------- гильдия рыбаков @@ -615,13 +764,13 @@ Config.Guild = { unlocks = "🎣 Автоловля, 4-й заказ на доске" }, { id = "D", name = "Рыбак", seals = 120, orders = 4, color = Color3.fromRGB(70, 130, 230), auto = true, traps = 1, trial = { kind = "catch", minRank = 3, weathers = { Rain = true, Storm = true }, count = 1, text = "Поймать «Редкую» рыбу в дождь или грозу" }, - unlocks = "🏝 Мир 2 (и ур. 8), 🧺 ловушка" }, + unlocks = "🧺 ловушка" }, { id = "C", name = "Опытный рыбак", seals = 350, orders = 4, color = Color3.fromRGB(150, 80, 200), auto = true, traps = 2, discount = 0.05, trial = { kind = "bossWin", count = 1, text = "Помочь одолеть босса озера" }, unlocks = "🧺 2 ловушки, скидка у торговцев 5%" }, { id = "B", name = "Мастер", seals = 900, orders = 4, color = Color3.fromRGB(200, 50, 45), auto = true, traps = 3, discount = 0.05, trial = { kind = "dex", world = "World1", text = "Собрать всю коллекцию «Тихого озера»" }, - unlocks = "❄ Мир 3 (и ур. 18), 🧺 3 ловушки" }, + unlocks = "🧺 3 ловушки" }, { id = "A", name = "Магистр", seals = 2000, orders = 4, color = Color3.fromRGB(230, 180, 60), auto = true, traps = 3, discount = 0.10, trial = { kind = "catch", minRank = 4, night = true, count = 1, text = "Поймать «Эпическую» рыбу ночью" }, unlocks = "Титул «Магистр», скидка 10%" }, @@ -629,8 +778,9 @@ Config.Guild = { trial = { kind = "catch", minRank = 6, count = 1, text = "Поймать «Мифическую» рыбу" }, unlocks = "Золотой жетон, автоловля без ограничения редкости" }, }, - -- миры требуют и уровень, и ранг (номер в списке ranks) - worldRank = { World2 = 3, World3 = 5 }, + -- экономика v2: миры открывает только уровень (8 / 18); ранг гильдии — параллельные возможности, + -- без стены ожидания погоды или полного бестиария. Здесь можно снова потребовать ранг: { World2 = 3 } + worldRank = {}, elderDistance = 22, -- взять испытание / сдать рыбу — рядом со Старейшиной или доской } @@ -640,7 +790,7 @@ Config.Orders = { period = 10800, rerollPearls = 2, pearlChance = 0.2, pearlsMin = 1, pearlsMax = 3, - coinsPerSeal = 12, -- серебро за заказ = печати × это × (1 + 0.5 · (ранг − 1)) + coinsPerSeal = 5, -- серебро за заказ = печати × это × tier мира игрока -- weight — как часто выпадает; seals — печати {мин, макс} kinds = { deliver = { weight = 3, seals = { 5, 12 } }, @@ -652,16 +802,18 @@ Config.Orders = { }, } --- наживка: 1 слот, 1 штука тратится на заброс. price — за пачку из pack штук; currency = "pearls" — за жемчуг +-- наживка: 1 слот, 1 штука тратится на заброс. price — за пачку из pack штук; currency = "pearls" — за жемчуг. +-- Наживка влияет на то, какая рыба клюёт (зелье — на рыбака) Config.Baits = { - { id = "Worm", name = "Червь", icon = "🐛", price = 40, pack = 10, speed = 0.9, desc = "Клюёт на 10% быстрее" }, - { id = "Larva", name = "Мотыль", icon = "🦐", price = 90, pack = 10, luck = 0.15, desc = "Удача +15%" }, - { id = "Firefly", name = "Светлячок", icon = "✨", price = 120, pack = 10, nightLuck = 0.30, desc = "Ночью удача +30% (вместо +10%)" }, - { id = "Blood", name = "Кровавая приманка", icon = "🩸", price = 400, pack = 10, rareWeight = 1.5, rank = 3, desc = "Редкие и выше попадаются в 1,5 раза чаще" }, + { id = "Worm", name = "Червь", icon = "🐛", price = 15, pack = 10, speed = 0.93, desc = "Клюёт на 7% быстрее" }, + { id = "Larva", name = "Мотыль", icon = "🦐", price = 30, pack = 10, luck = 0.15, desc = "Удача +15%" }, + { id = "Firefly", name = "Светлячок", icon = "✨", price = 40, pack = 10, nightLuck = 0.30, desc = "Ночью удача +30% (вместо +10%)" }, + { id = "Blood", name = "Кровавая приманка", icon = "🩸", price = 150, pack = 10, rareWeight = 1.5, rank = 3, desc = "Редкие и выше попадаются в 1,5 раза чаще" }, { id = "Pearl", name = "Жемчужная блесна", icon = "🦪", price = 5, pack = 5, mutation = 2, currency = "pearls", desc = "Шанс мутаций ×2" }, } --- автоловля (с ранга E): сервер сам забрасывает и вытаскивает, но со штрафами +-- автоловля (с ранга E): сервер сам забрасывает и вытаскивает, но со штрафами. Опыта карьеры не даёт, +-- рыба дешевле (Economy.autoValue), цикл не короче Economy.autoMinCycle, зелья не действуют и не тратятся Config.AutoFish = { luck = 0.6, -- удача ×0.6 maxRarity = 3, -- не выше «Редкой» (ранг S снимает) @@ -675,8 +827,9 @@ Config.Traps = { world = "World1", rarities = { Common = 3, Uncommon = 1 }, -- вес редкостей } --- отдых: пока игрока нет, копится двойной опыт — 1 минута за каждые perOffline минут офлайн, не больше max -Config.Rest = { perOffline = 4, max = 3600, mult = 2 } +-- отдых: пока игрока нет, копится бонус +25% серебра за пойманную рыбу (Economy.restSilver) — +-- 1 минута за каждые perOffline минут офлайн, не больше max секунд. Опыт карьеры отдых не меняет +Config.Rest = { perOffline = 4, max = 3600 } function Config.RankById(id) for i, r in ipairs(Config.Guild.ranks) do diff --git a/src/ServerScriptService/GameServer.server.lua b/src/ServerScriptService/GameServer.server.lua index e465fe5..1822616 100644 --- a/src/ServerScriptService/GameServer.server.lua +++ b/src/ServerScriptService/GameServer.server.lua @@ -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 diff --git a/src/ServerScriptService/Guild.lua b/src/ServerScriptService/Guild.lua index 9b877ab..d4c4562 100644 --- a/src/ServerScriptService/Guild.lua +++ b/src/ServerScriptService/Guild.lua @@ -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) diff --git a/src/ServerScriptService/Market.lua b/src/ServerScriptService/Market.lua new file mode 100644 index 0000000..936553c --- /dev/null +++ b/src/ServerScriptService/Market.lua @@ -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 diff --git a/src/ServerScriptService/PlayerStore.lua b/src/ServerScriptService/PlayerStore.lua new file mode 100644 index 0000000..d86ad6e --- /dev/null +++ b/src/ServerScriptService/PlayerStore.lua @@ -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 diff --git a/src/ServerScriptService/Potions.lua b/src/ServerScriptService/Potions.lua new file mode 100644 index 0000000..e5e4c39 --- /dev/null +++ b/src/ServerScriptService/Potions.lua @@ -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 diff --git a/src/ServerScriptService/Progression.lua b/src/ServerScriptService/Progression.lua new file mode 100644 index 0000000..01ee200 --- /dev/null +++ b/src/ServerScriptService/Progression.lua @@ -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 diff --git a/src/ServerScriptService/Telemetry.lua b/src/ServerScriptService/Telemetry.lua new file mode 100644 index 0000000..123b40a --- /dev/null +++ b/src/ServerScriptService/Telemetry.lua @@ -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 diff --git a/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua b/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua index b84dd73..54d2e86 100644 --- a/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua +++ b/src/StarterPlayer/StarterPlayerScripts/FishingClient.client.lua @@ -272,11 +272,12 @@ local side = new("Frame", { }) -- старые вызовы передают эмодзи — переводим в имя рисованной иконки -H.MENU_ICON = { ["🎒"] = "bag", ["📖"] = "book", ["🌍"] = "map", ["📜"] = "scroll", ["💎"] = "crystal", ["⚙"] = "horn", ["⚔"] = "guild" } +H.MENU_ICON = { ["🎒"] = "bag", ["📖"] = "book", ["🌍"] = "map", ["📜"] = "scroll", ["💎"] = "crystal", ["⚙"] = "horn", ["⚔"] = "guild", ["🏪"] = "coin" } H.MENU_TIP = { ["Сумка"] = "Улов и продажа рыбы", ["Рыбы"] = "Коллекция и награды за неё", ["Миры"] = "Острова для рыбалки", ["Задания"] = "Задания и ежедневная награда", ["Донат"] = "Наборы и усиления", ["Звук"] = "Громкость музыки и звуков", ["Гильдия"] = "Ранг, заказы, наживка и ловушки", + ["Рынок"] = "Ценная рыба от других игроков этого сервера (с 8 уровня)", } local sideDots = {} local function sideButton(order, icon, label, key, color, onClick) @@ -463,14 +464,16 @@ local function showCatch(fish, extra) viewport(catchView, Models.buildFish(fish.id, fish.mutation, 1, true), VIEW.fish, 0.75) catchStroke.Color = mut and mut.color or r.color catchGrad.Color = ColorSequence.new(r.color:Lerp(C.bg, 0.55), C.bg) - catchHeader.Text = extra and extra.new and "🆕 НОВЫЙ ВИД! Опыт x2" or (extra and extra.record and "🏆 НОВЫЙ РЕКОРД!" or "ПОЙМАНА РЫБА") + catchHeader.Text = extra and extra.new and "🆕 НОВЫЙ ВИД! В коллекцию" or (extra and extra.record and "🏆 НОВЫЙ РЕКОРД!" or "ПОЙМАНА РЫБА") catchHeader.TextColor3 = (extra and (extra.new or extra.record)) and C.gold or C.muted catchName.Text = fish.name catchName.TextColor3 = r.color catchInfo.Text = ("%s%s · %.2f кг"):format( hex(r.color), r.name, mut and (" · " .. mut.name .. " x" .. mut.mult .. "") or "", fish.weight) - catchValue.Text = ("⚪ %s ⭐ +%d XP%s"):format(fmt(fish.value), fish.xp * ((extra and extra.new) and 2 or 1), - (extra and extra.combo and extra.combo > 1.001) and (" 🔥 x%.1f"):format(extra.combo) or "") + -- опыт карьеры фиксированный за мир; серия и отдых — надбавка к серебру + catchValue.Text = ("⚪ %s%s%s%s"):format(fmt(fish.value), (fish.xp or 0) > 0 and (" ⭐ +%d XP"):format(fish.xp) or "", + (extra and extra.combo and extra.combo > 1.001) and (" 🔥 +%d%%"):format(math.floor((extra.combo - 1) * 100 + 0.5)) or "", + (extra and extra.rest) and " 🛌 +" .. math.floor(Config.Economy.restSilver * 100) .. "%" or "") catchCard.Visible = true H.placeToasts(true) TweenService:Create(catchCard, TweenInfo.new(0.45, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Position = UDim2.new(0.5, 0, 0, 120) }):Play() @@ -826,8 +829,55 @@ local function progressBar(parent, pos, size, frac, color) return back end +-- окно подтверждения поверх всего: заголовок, текст (RichText), «Отмена» и кнопка действия. +-- extra = { okColor, cancelText } (необязательно) +do + local dim = new("TextButton", { Name = "ConfirmDim", Size = UDim2.fromScale(1, 1), BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = 0.45, + AutoButtonColor = false, Text = "", Visible = false, ZIndex = 60, Modal = true, Parent = screen }) + local box = new("Frame", { Size = UDim2.new(1, -24, 0, 230), AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), BackgroundColor3 = WHITE, ZIndex = 61, Parent = dim }, + { corner(12), stroke(C.gold, 3, 0), Theme.woodGradient(C.wood, C.woodDark), new("UISizeConstraint", { MaxSize = Vector2.new(520, 300) }) }) + Theme.rivets(box, 9, 6) + local title = text({ Size = UDim2.new(1, -32, 0, 34), Position = UDim2.fromOffset(16, 12), Font = TITLE, TextSize = 24, TextXAlignment = Enum.TextXAlignment.Center, + TextColor3 = C.goldBright, TextStrokeColor3 = C.ink, TextStrokeTransparency = 0.3, ZIndex = 62, Parent = box }) + local body = text({ Size = UDim2.new(1, -36, 1, -122), Position = UDim2.fromOffset(18, 52), Font = BODY2, TextSize = 16, RichText = true, TextWrapped = true, + TextYAlignment = Enum.TextYAlignment.Top, ZIndex = 62, Parent = box }) + local onOk = nil + local cancel = btn({ Size = UDim2.new(0.5, -24, 0, 48), AnchorPoint = Vector2.new(0, 1), Position = UDim2.new(0, 16, 1, -14), BackgroundColor3 = C.grey, Text = "Отмена", TextSize = 19, ZIndex = 62, Parent = box }, function() + dim.Visible = false + onOk = nil + end) + local ok = btn({ Size = UDim2.new(0.5, -24, 0, 48), AnchorPoint = Vector2.new(1, 1), Position = UDim2.new(1, -16, 1, -14), BackgroundColor3 = C.green, Text = "OK", TextSize = 19, ZIndex = 62, Parent = box }, function() + dim.Visible = false + local f = onOk + onOk = nil + if f then + f() + end + end) + for _, b in ipairs({ cancel, ok }) do + for _, d in ipairs(b:GetDescendants()) do + if d:IsA("GuiObject") then + d.ZIndex = 63 + end + end + end + function H.confirm(titleText, bodyText, okText, fn, extra) + title.Text = titleText + body.Text = bodyText + ok.Text = okText or "OK" + ok.BackgroundColor3 = (extra and extra.okColor) or C.green + cancel.Text = (extra and extra.cancelText) or "Отмена" + onOk = fn + dim.Visible = true + popIn(box, 0.8) + end +end + -- помощники интерфейса для других скриптов (GuildClient): тот же стиль окон, кнопок и уведомлений Theme.kit = { + confirm = function(...) + H.confirm(...) + end, new = new, text = text, btn = btn, corner = corner, stroke = stroke, gradient = gradient, clear = clear, makeWindow = makeWindow, scrollArea = scrollArea, itemRow = itemRow, progressBar = progressBar, sideButton = sideButton, notify = notify, popIn = popIn, fmt = fmt, timeStr = timeStr, @@ -846,7 +896,7 @@ local shopWin = makeWindow("🎣 Магазин Михалыча", Color3.fromRG { id = "rods", label = "🎣 Удочки" }, { id = "upgrade", label = "✨ Улучшение" }, { id = "bags", label = "🎒 Сумки" }, - { id = "luck", label = "🍀 Удача" }, + { id = "luck", label = "🍀 Зелья" }, }) local shopLists = { rods = scrollArea(shopWin.pages.rods), @@ -962,6 +1012,77 @@ shopWin.render = function(tab) }) end elseif tab == "luck" then + -- зелья: действующее, сумка зелий (выпить), лавка (купить в сумку); внизу — из чего складывается удача + local inv = {} + for id, n in string.gmatch(player:GetAttribute("PotionInv") or "", "([^,:]+):(%d+)") do + inv[id] = tonumber(n) + end + local activeId = player:GetAttribute("PotionActive") + local active = activeId and Config.Find(Config.Potions, activeId) + local left = player:GetAttribute("PotionLeft") or 0 + local function leftText(p, n) + return p.charges and (n .. " попыток") or (timeStr(n) .. " игры") + end + local function drink(p) + if active and active.id ~= p.id then + -- замена: сервер всё равно спросит, но сразу показываем, что пропадёт + H.confirm("🧪 Заменить зелье?", ("Сейчас действует %s %s — осталось %s.\nЕсли выпить %s %s, остаток прежнего зелья пропадёт.") + :format(active.icon, active.name, leftText(active, left), p.icon, p.name), "Заменить", function() + remote:FireServer("DrinkPotion", p.id, true) + end) + else + remote:FireServer("DrinkPotion", p.id, false) + end + end + local order = 0 + local function nextOrder() + order += 1 + return order + end + Theme.section(list, nextOrder(), "Действует сейчас", "clover", "одно зелье за раз") + if active then + itemRow(list, nextOrder(), { + icon = active.icon, iconBg = active.color:Lerp(C.bg, 0.6), title = active.name, titleColor = active.color, + lines = active.desc .. ("\nОсталось: %s"):format(leftText(active, left)), + strokeColor = C.gold, buttonText = "Действует", buttonColor = C.grey, active = false, + }) + else + text({ Size = UDim2.new(1, -4, 0, 30), LayoutOrder = nextOrder(), Font = BODY2, TextSize = 15, TextColor3 = C.muted, TextWrapped = true, + Text = "Ничего не действует. Попытка зелья тратится, когда рыба клюнула; отмена до поклёвки и автоловля зелья не тратят.", Parent = list }) + end + local any = false + for _, p in ipairs(Config.Potions) do + if (inv[p.id] or 0) > 0 then + if not any then + Theme.section(list, nextOrder(), "Сумка зелий", "gift", "выпей, когда нужно") + any = true + end + local same = active and active.id == p.id + itemRow(list, nextOrder(), { + icon = p.icon, iconBg = p.color:Lerp(C.bg, 0.6), title = ("%s ×%d"):format(p.name, inv[p.id]), titleColor = p.color, + lines = p.desc .. "\n" .. (p.charges and (p.charges .. " попыток") or (math.floor(p.duration / 60) .. " минут игры")), + buttonText = same and "Добавить" or "Выпить", buttonColor = same and C.blue or C.green, active = true, + onClick = function() + drink(p) + end, + }) + end + end + Theme.section(list, nextOrder(), "Лавка зелий", "coin", "покупка — в сумку зелий") + for _, p in ipairs(Config.Potions) do + if p.price and not p.paid and not p.legacy then + local bText, bColor, okBuy = buyButton(p.price, p.level or 1, myLevel, coins) + itemRow(list, nextOrder(), { + icon = p.icon, iconBg = p.color:Lerp(C.bg, 0.6), title = p.name, titleColor = p.color, + lines = p.desc .. ("\n%d попыток · не даёт опыта, не обязательно для прогресса"):format(p.charges), + buttonText = bText, buttonColor = bColor, active = okBuy, + onClick = function() + remote:FireServer("Buy", "Potion", p.id) + end, + }) + end + end + -- из чего складывается удача local lv = levels[player:GetAttribute("Rod") or "Basic"] or 0 local rod = Config.Find(Config.Rods, player:GetAttribute("Rod") or "Basic") or Config.Rods[1] local boost = player:GetAttribute("BoostBonus") or 0 @@ -969,33 +1090,24 @@ shopWin.render = function(tab) local ps = attrSet("Passes") local evId = workspace:GetAttribute("Event") local event = evId and Config.Find(Config.Events, evId) + local beff = Config.EffectiveLuck(total / 100) + local mm = Config.MutationMult(beff, (event and event.mutation) or 1) local mutLine = {} for _, m in ipairs(Config.Mutations) do - table.insert(mutLine, ("%s %.1f%%"):format(hex(m.color), m.name, math.min(100, m.chance * total / 100 * ((event and event.mutation) or 1) * 100))) + table.insert(mutLine, ("%s %.1f%%"):format(hex(m.color), m.name, math.min(100, m.chance * mm * 100))) end local lines = { - ("🍀 Твоя удача: %d%%"):format(total), + ("🍀 Твоя удача: %d%%"):format(total), ("Базовая 100%% · 🎣 Удочка +%d%% · ✨ Улучшения +%d%%"):format(math.floor(rod.luck * 100 + 0.5), math.floor(lv * Config.RodUpgrade.luckPerLevel * 100 + 0.5)), ("⭐ Уровень +%d%% · 🏆 Мастерство миров +%d%%"):format(math.floor(((player:GetAttribute("Level") or 1) - 1) * Config.LuckPerPlayerLevel * 100 + 0.5), math.floor((player:GetAttribute("Mastery") or 0) * Config.MasteryLuck * 100 + 0.5)), - ("🧪 Зелье +%d%%%s · 👑 Пропуска +%d%%%s"):format(math.floor(boost * 100 + 0.5), boost > 0 and (" (" .. timeStr(player:GetAttribute("BoostLeft") or 0) .. ")") or "", + ("🧪 Зелье +%d%% · 👑 Пропуска +%d%%%s"):format(math.floor(boost * 100 + 0.5), (ps.VIP and 25 or 0) + (ps.LuckyCharm and 50 or 0), (event and event.luck) and (" · 🎉 Событие +" .. event.luck * 100 .. "%") or ""), "Шанс мутаций: " .. table.concat(mutLine, " · "), + "Каждые следующие +100% удачи действуют слабее предыдущих.", } - local info = new("Frame", { Size = UDim2.new(1, -4, 0, 160), BackgroundColor3 = WHITE, LayoutOrder = 0, Parent = list }, + local info = new("Frame", { Size = UDim2.new(1, -4, 0, 176), BackgroundColor3 = WHITE, LayoutOrder = nextOrder(), Parent = list }, { corner(14), stroke(Color3.fromRGB(90, 220, 120), 2, 0.2), gradient(Color3.fromRGB(35, 70, 55), C.panel, 90), new("UIPadding", { PaddingLeft = UDim.new(0, 16), PaddingTop = UDim.new(0, 10), PaddingRight = UDim.new(0, 16) }) }) text({ Size = UDim2.fromScale(1, 1), TextSize = 15, RichText = true, TextYAlignment = Enum.TextYAlignment.Top, TextWrapped = true, Text = table.concat(lines, "\n"), Parent = info }) - for i, p in ipairs(Config.Potions) do - local bText, bColor, active = buyButton(p.price, p.level or 1, myLevel, coins) - itemRow(list, i, { - icon = "🧪", iconBg = p.color:Lerp(C.bg, 0.6), - title = p.name, titleColor = p.color, - lines = ("Удача +%d%% на %d мин.\nРедкая рыба и мутации попадаются чаще!"):format(p.bonus * 100, p.duration / 60), - buttonText = bText, buttonColor = bColor, active = active, - onClick = function() - remote:FireServer("Buy", "Potion", p.id) - end, - }) - end end end @@ -1118,7 +1230,7 @@ local function renderDex() }) text({ Size = UDim2.new(1, -250, 0, 16), Position = UDim2.fromOffset(70, 34), Font = BODY2, TextSize = 13, TextColor3 = C.muted, - Text = ("Собери всех: +%s серебра и +%d%% удачи навсегда"):format(fmt(Config.MasteryCoins * world.mult), math.floor(Config.MasteryLuck * 100 + 0.5)), Parent = head, + Text = ("Собери всех: +%s серебра и +%d%% удачи навсегда"):format(fmt(Config.MasteryCoins * (world.tier or 1)), math.floor(Config.MasteryLuck * 100 + 0.5)), Parent = head, }) local _, setHeadBar = Theme.bar(head, { Size = UDim2.new(1, -250, 0, 10), Position = UDim2.fromOffset(70, 54) }, C.gold) setHeadBar(found / math.max(1, #all)) @@ -1150,7 +1262,7 @@ local function renderDex() local hdr = Theme.section(section, 0, ("%s %d/%d"):format(hex(r.color:Lerp(WHITE, 0.25)), r.name, have, #group), "fish") hdr.Size = UDim2.new(1, 0, 0, 40) text({ Size = UDim2.new(0, 170, 1, 0), AnchorPoint = Vector2.new(1, 0), Position = UDim2.new(1, -166, 0, 0), Font = BODY2, TextSize = 13, TextColor3 = C.muted, - TextXAlignment = Enum.TextXAlignment.Right, RichText = true, Text = ("+%s серебра · +%s XP"):format(fmt(reward.coins * world.mult), fmt(reward.xp * world.mult)), Parent = hdr }) + TextXAlignment = Enum.TextXAlignment.Right, RichText = true, Text = ("+%s серебра"):format(fmt(reward.coins * (world.tier or 1))), Parent = hdr }) local _, setRB = Theme.bar(hdr, { Size = UDim2.new(0, 120, 0, 8), AnchorPoint = Vector2.new(1, 1), Position = UDim2.new(1, -166, 1, -1) }, r.color) setRB(have / #group) local key = dexWorld .. ":" .. rarity @@ -1297,7 +1409,14 @@ bagWin.render = function(tab) new("UIPadding", { PaddingLeft = UDim.new(0, 20), Parent = price }) Theme.icon(new("Frame", { Size = UDim2.fromOffset(20, 20), AnchorPoint = Vector2.new(0, 0.5), Position = UDim2.new(0, -14, 0.5, 0), BackgroundTransparency = 1, ZIndex = 6, Parent = price }), "coin") Theme.pressFx(price) - Theme.tooltip(cell, ("%s · %s · %.2f кг%s"):format(it.name, r.name, it.weight, mut and (" · " .. mut.name) or "")) + if it.bought then + -- купленная на рынке: не свой улов (не идёт в коллекцию, заказы и испытания) + local tag = new("Frame", { Size = UDim2.fromOffset(0, 18), AutomaticSize = Enum.AutomaticSize.X, AnchorPoint = Vector2.new(1, 0), Position = UDim2.new(1, -24, 0, 6), + BackgroundColor3 = C.blue, ZIndex = 6, Parent = cell }, { corner(6), new("UIPadding", { PaddingLeft = UDim.new(0, 4), PaddingRight = UDim.new(0, 4) }) }) + text({ Size = UDim2.new(0, 0, 1, 0), AutomaticSize = Enum.AutomaticSize.X, Font = TITLE, TextSize = 12, Text = "🛒 куплена", ZIndex = 7, Parent = tag }) + end + Theme.tooltip(cell, ("%s · %s · %.2f кг%s%s"):format(it.name, r.name, it.weight, mut and (" · " .. mut.name) or "", + it.bought and ("
🛒 Куплена у %s за %s ⚪ — не твой улов: не в коллекцию, заказы и испытания; скупщик даёт базовую цену"):format(it.bought.fromName or "?", fmt(it.bought.price or 0)) or "")) end end elseif tab == "dex" then @@ -1356,8 +1475,8 @@ worldsWin.render = function() itemRow(worldsList, i, { icon = w.icon, iconBg = w.color:Lerp(C.bg, 0.6), title = w.name, titleColor = w.color, - lines = w.desc .. "\n" .. (w.soon and "В разработке" or ("Уровень: %d%s · Рыб поймано: %d / %d · Награды x%d"):format(w.level, - Config.Guild.worldRank[w.id] and (", ранг " .. Config.Guild.ranks[Config.Guild.worldRank[w.id]].id) or "", found, total, w.mult)), + lines = w.desc .. "\n" .. (w.soon and "В разработке" or ("Уровень: %d%s · Рыб поймано: %d / %d · Опыт: %d за рыбу"):format(w.level, + Config.Guild.worldRank[w.id] and (", ранг " .. Config.Guild.ranks[Config.Guild.worldRank[w.id]].id) or "", found, total, Config.CareerXP(w.id))), strokeColor = (here and here.id == w.id) and C.gold or nil, buttonText = bText, buttonColor = bColor, active = active, onClick = function() @@ -1475,7 +1594,7 @@ questWin.render = function(tab) end text({ Size = UDim2.new(1, -6, 0, 40), Position = UDim2.fromOffset(3, 90), Font = TITLE, TextSize = 14, TextXAlignment = Enum.TextXAlignment.Center, TextWrapped = true, TextColor3 = C.goldBright, - Text = fmt(r.coins * (1 + (myLevel - 1) * 0.2)) .. (r.potion and "\n+ зелье" or ""), ZIndex = 2, Parent = cell, + Text = fmt(r.coins * Config.TierFor(myLevel)) .. (r.potion and ("\n+ " .. ((Config.Find(Config.Potions, r.potion) or {}).icon or "🧪")) or ""), ZIndex = 2, Parent = cell, }) if isNext then popIn(cell, 0.8) @@ -1674,10 +1793,14 @@ local function refreshHud() H.lvl.Text = tostring(player:GetAttribute("Level") or 1) H.xpText.Text = ("%d / %d XP"):format(xp, need) TweenService:Create(H.xpFill, TweenInfo.new(0.3), { Size = UDim2.fromScale(math.clamp(xp / need, 0, 1), 1) }):Play() - local boost = player:GetAttribute("BoostBonus") or 0 H.luck.Text = ("Удача %d%%"):format(player:GetAttribute("Luck") or 100) - H.boostChip.Visible = boost > 0 - H.boost.Text = ("+%d%% %s"):format(boost * 100, timeStr(player:GetAttribute("BoostLeft") or 0)) + -- действующее зелье: значок и остаток (попытки или время игры) + local potion = Config.Find(Config.Potions, player:GetAttribute("PotionActive") or "") + H.boostChip.Visible = potion ~= nil + if potion then + local left = player:GetAttribute("PotionLeft") or 0 + H.boost.Text = potion.icon .. " " .. (player:GetAttribute("PotionKind") == "charges" and (left .. " поп.") or timeStr(left)) + end local count, cap = player:GetAttribute("BagCount") or 0, player:GetAttribute("BagCap") or 10 H.bag.Text = ("%d / %d"):format(count, cap) H.bag.TextColor3 = count >= cap and Color3.fromRGB(255, 130, 120) or C.text @@ -1688,7 +1811,7 @@ end local pending = false player.AttributeChanged:Connect(function(name) refreshHud() - if name == "BoostLeft" and not (shopWin.isOpen() and shopWin.current == "luck") then + if (name == "BoostLeft" or name == "PotionLeft") and not (shopWin.isOpen() and shopWin.current == "luck") then return end if not pending then @@ -3211,10 +3334,11 @@ bestOffer = function(bagWasFull) desc = "Больше удачи и шире зелёная зона" }) end end + -- зелья не навязываем: предложение только если сумка зелий пуста и ничего не действует local potion = Config.Potions[1] - if coins >= potion.price and (player:GetAttribute("BoostBonus") or 0) == 0 then - table.insert(options, { kind = "Potion", id = potion.id, icon = "🧪", title = potion.name, price = potion.price, prio = 0.5, - desc = ("+%d%% удачи на %d мин"):format(potion.bonus * 100, potion.duration / 60) }) + if coins >= potion.price * 3 and lvl >= (potion.level or 1) and (player:GetAttribute("PotionInv") or "") == "" and not player:GetAttribute("PotionActive") then + table.insert(options, { kind = "Potion", id = potion.id, icon = potion.icon, title = potion.name, price = potion.price, prio = 0.5, + desc = potion.desc .. " · " .. potion.charges .. " попыток" }) end table.sort(options, function(x, y) return x.prio > y.prio @@ -3325,11 +3449,11 @@ remote.OnClientEvent:Connect(function(action, a, b, c, d) refreshDots() refreshTracker() elseif action == "QuestDone" then - notify(("✅ %s +%s ⚪ +%s XP"):format(questText(a, b), fmt(c), fmt(d or 0)), Color3.fromRGB(120, 255, 140)) + notify(("✅ %s +%s ⚪"):format(questText(a, b), fmt(c)), Color3.fromRGB(120, 255, 140)) Audio.play("quest") elseif action == "ChainDone" then floatText("🏆 Цепочка пройдена!", C.gold) - notify(("🎁 %s: +%s ⚪ +%s XP%s"):format(a, fmt(b), fmt(c), d and (" + " .. d) or ""), C.gold) + notify(("🎁 %s: +%s ⚪%s"):format(a, fmt(b), d and (" + " .. d) or ""), C.gold) Audio.play("fanfare") elseif action == "ComboLost" then notify(("💔 Серия из %d прервана"):format(a), Color3.fromRGB(255, 130, 110)) @@ -3345,7 +3469,17 @@ remote.OnClientEvent:Connect(function(action, a, b, c, d) notify(("🌊 %s ушёл на глубину…"):format(b), C.muted) end elseif action == "BossReward" then - notify(("🎁 За босса: +%s ⚪ +%s XP%s"):format(fmt(a), fmt(b), c and (" + " .. c) or ""), Color3.fromRGB(120, 255, 140)) + notify(("🎁 За босса: +%s ⚪%s"):format(fmt(a), c and (" + " .. c .. " (в сумку зелий)") or ""), Color3.fromRGB(120, 255, 140)) + elseif action == "PotionConfirm" then + -- a — что хотим выпить, b — что действует сейчас, c — его остаток + local want, cur = Config.Find(Config.Potions, a), Config.Find(Config.Potions, b) + if want and cur then + local leftText = cur.charges and (c .. " попыток") or timeStr(c) + H.confirm("🧪 Заменить зелье?", ("Сейчас действует %s %s — осталось %s.\nЕсли выпить %s %s, остаток прежнего зелья пропадёт.") + :format(cur.icon, cur.name, leftText, want.icon, want.name), "Заменить", function() + remote:FireServer("DrinkPotion", a, true) + end) + end elseif action == "OpenShop" then shopWin.open("rods") elseif action == "OpenQuests" then diff --git a/src/StarterPlayer/StarterPlayerScripts/GuildClient.client.lua b/src/StarterPlayer/StarterPlayerScripts/GuildClient.client.lua index 088fa02..c7c339b 100644 --- a/src/StarterPlayer/StarterPlayerScripts/GuildClient.client.lua +++ b/src/StarterPlayer/StarterPlayerScripts/GuildClient.client.lua @@ -279,7 +279,7 @@ end) ---------------------------------------------------------------- HUD: жемчуг, печати, ранг, отдых --- ряд «фишек» в панели игрока: ранг, печати, жемчуг; ниже — отдых (только пока есть двойной опыт) +-- ряд «фишек» в панели игрока: ранг, печати, жемчуг; ниже — отдых (только пока есть бонус к серебру) local guildRow = K.hudRow(3) local rankChip, rankText = Theme.chip(guildRow, "guild", 1) local sealChip, sealText = Theme.chip(guildRow, "seal", 2) @@ -304,7 +304,7 @@ local function refreshHud() pearlText.Text = fmt(player:GetAttribute("Pearls") or 0) local rest = player:GetAttribute("RestLeft") or 0 restPlate.Visible = rest > 0 - restText.Text = ("🛌 Отдых: опыт ×2 ещё %d мин"):format(math.ceil(rest / 60)) + restText.Text = ("🛌 Отдых: +%d%% серебра за рыбу ещё %d мин"):format(math.floor(Config.Economy.restSilver * 100 + 0.5), math.ceil(rest / 60)) -- значок на кнопке «Гильдия»: в ловушках есть рыба или хватает печатей на новый ранг if K.sideDots and K.sideDots["Гильдия"] then K.sideDots["Гильдия"].Visible = (player:GetAttribute("TrapFish") or 0) > 0 or (nextSeals ~= nil and seals >= nextSeals) diff --git a/src/StarterPlayer/StarterPlayerScripts/MarketClient.client.lua b/src/StarterPlayer/StarterPlayerScripts/MarketClient.client.lua new file mode 100644 index 0000000..de2614c --- /dev/null +++ b/src/StarterPlayer/StarterPlayerScripts/MarketClient.client.lua @@ -0,0 +1,313 @@ +-- MarketClient (LocalScript) -> StarterPlayer > StarterPlayerScripts +-- Окно рынка игроков: витрина лотов этого сервера, продажа своей ценной рыбы, посылки (купленная и +-- вернувшаяся рыба, если сумка была полна). Все проверки — на сервере (Market.lua); клиент только +-- показывает и спрашивает подтверждение. Стиль — Theme.kit из FishingClient. + +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local UserInputService = game:GetService("UserInputService") + +local player = Players.LocalPlayer +local Config = require(ReplicatedStorage:WaitForChild("FishConfig")) +local Models = require(ReplicatedStorage:WaitForChild("GameModels")) +local Theme = require(script.Parent:WaitForChild("UiTheme")) +local remote = ReplicatedStorage:WaitForChild("GameEvent") + +while not Theme.kit or not Theme.kit.confirm do + task.wait(0.1) +end +local K = Theme.kit +local C = Theme.C +local new, text, btn, corner, stroke = K.new, K.text, K.btn, K.corner, K.stroke +local fmt = K.fmt +local M = Config.Market +local WHITE = Color3.new(1, 1, 1) + +local state = nil -- последний снимок рынка от сервера +local myItems = {} -- сумка (для вкладки «Продать») + +local win = K.makeWindow("🏪 Рынок рыбаков", C.gold, { + { id = "shop", label = "🏪 Витрина" }, + { id = "sell", label = "⚪ Продать" }, + { id = "inbox", label = "🎁 Посылки" }, +}) +local lists = { + shop = K.scrollArea(win.pages.shop), + sell = K.scrollArea(win.pages.sell), + inbox = K.scrollArea(win.pages.inbox), +} + +local function hex(c) + return "#" .. c:ToHex() +end + +local function fishLine(it) + local r = Config.Rarities[it.rarity] or Config.Rarities.Common + local mut = it.mutation and Config.Find(Config.Mutations, it.mutation) + return ("%s%s · %.2f кг"):format(hex(r.color), r.name, mut and (" · " .. mut.name .. "") or "", it.weight or 0) +end + +local function eligible(it) + local r = Config.Rarities[it.rarity] + return (r and r.rank >= M.minRank) or (it.mutation and M.mutations[it.mutation]) or false +end + +local function bounds(it) + local v = math.max(1, math.floor(it.value or 1)) + return math.ceil(v * M.minPriceMult), math.floor(v * M.maxPriceMult) +end + +local function fee(price) + return math.max(1, math.floor(price * M.fee + 0.5)) +end + +local function note(list, order, msg) + text({ Size = UDim2.new(1, -4, 0, 0), AutomaticSize = Enum.AutomaticSize.Y, LayoutOrder = order, Font = K.BODY2, TextSize = 15, TextColor3 = C.muted, + TextWrapped = true, RichText = true, Text = msg, Parent = list }) +end + +---------------------------------------------------------------- выставление: выбор цены + +local pricer = {} +do + local dim = new("Frame", { Size = UDim2.fromScale(1, 1), BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = 0.45, Visible = false, ZIndex = 55, Parent = K.screen }) + local box = new("Frame", { Size = UDim2.new(1, -24, 0, 280), AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), BackgroundColor3 = WHITE, ZIndex = 56, Parent = dim }, + { corner(12), stroke(C.gold, 3, 0), Theme.woodGradient(C.wood, C.woodDark), new("UISizeConstraint", { MaxSize = Vector2.new(520, 300) }) }) + Theme.rivets(box, 9, 6) + pricer.title = text({ Size = UDim2.new(1, -32, 0, 32), Position = UDim2.fromOffset(16, 12), Font = K.TITLE, TextSize = 22, TextXAlignment = Enum.TextXAlignment.Center, + TextColor3 = C.goldBright, ZIndex = 57, Parent = box }) + pricer.info = text({ Size = UDim2.new(1, -32, 0, 44), Position = UDim2.fromOffset(16, 46), Font = K.BODY2, TextSize = 15, RichText = true, TextWrapped = true, + TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 57, Parent = box }) + pricer.box = new("TextBox", { Size = UDim2.fromOffset(200, 44), AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 96), BackgroundColor3 = C.dark, + TextColor3 = C.goldBright, Font = K.TITLE, TextSize = 24, ClearTextOnFocus = false, Text = "", ZIndex = 57, Parent = box }, { corner(8), stroke(C.gold, 2, 0) }) + local function step(mult) + local v = tonumber(pricer.box.Text) or pricer.lo + pricer.box.Text = tostring(math.clamp(math.floor(v * mult + 0.5), pricer.lo, pricer.hi)) + end + btn({ Size = UDim2.fromOffset(56, 44), Position = UDim2.new(0.5, -168, 0, 96), BackgroundColor3 = C.wood, Text = "−", TextSize = 26, ZIndex = 57, Parent = box }, function() + step(0.9) + end) + btn({ Size = UDim2.fromOffset(56, 44), Position = UDim2.new(0.5, 112, 0, 96), BackgroundColor3 = C.wood, Text = "+", TextSize = 26, ZIndex = 57, Parent = box }, function() + step(1.1) + end) + pricer.sum = text({ Size = UDim2.new(1, -32, 0, 48), Position = UDim2.fromOffset(16, 146), Font = K.BODY2, TextSize = 15, RichText = true, TextWrapped = true, + TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 57, Parent = box }) + btn({ Size = UDim2.new(0.5, -24, 0, 46), AnchorPoint = Vector2.new(0, 1), Position = UDim2.new(0, 16, 1, -14), BackgroundColor3 = C.grey, Text = "Отмена", TextSize = 19, ZIndex = 57, Parent = box }, function() + dim.Visible = false + end) + btn({ Size = UDim2.new(0.5, -24, 0, 46), AnchorPoint = Vector2.new(1, 1), Position = UDim2.new(1, -16, 1, -14), BackgroundColor3 = C.green, Text = "Выставить", TextSize = 19, ZIndex = 57, Parent = box }, function() + local price = tonumber(pricer.box.Text) + if price and price % 1 == 0 and price >= pricer.lo and price <= pricer.hi then + dim.Visible = false + remote:FireServer("MarketList", pricer.item.uid, price) + else + pricer.box.Text = tostring(pricer.lo) + end + end) + local function refreshSum() + local price = tonumber(pricer.box.Text) + if not price or not pricer.item then + pricer.sum.Text = ("Цена — целое число от %s до %s ⚪"):format(fmt(pricer.lo or 0), fmt(pricer.hi or 0)) + return + end + local f = fee(price) + pricer.sum.Text = ("Комиссия рынка %d%%: %s ⚪ · ты получишь %s ⚪\nЛот висит %d мин, снять можно в любой момент") + :format(math.floor(M.fee * 100 + 0.5), fmt(f), fmt(price - f), math.floor(M.duration / 60)) + end + pricer.box:GetPropertyChangedSignal("Text"):Connect(refreshSum) + function pricer.open(it) + pricer.item = it + pricer.lo, pricer.hi = bounds(it) + pricer.title.Text = "Выставить: " .. it.name + pricer.info.Text = fishLine(it) .. ("\nСкупщик даёт за неё ≈ %s ⚪ · цена на рынке: %s – %s ⚪"):format(fmt(it.value or 0), fmt(pricer.lo), fmt(pricer.hi)) + pricer.box.Text = tostring(math.max(pricer.lo, math.floor((it.value or 1) * 2))) + refreshSum() + dim.Visible = true + end +end + +---------------------------------------------------------------- вкладки + +local function closedNote(list) + if not state then + note(list, 1, "Загрузка…") + return true + end + if not state.enabled then + note(list, 1, "🏪 Рынок сейчас закрыт.") + return true + end + if not state.access then + note(list, 1, ("🔒 Рынок открывается с %d уровня (вместе с Миром 2). Сейчас у тебя %d.\nНа рынке игроки продают друг другу ценную рыбу за серебро.") + :format(M.minLevel, state.level or 1)) + return true + end + return false +end + +local function renderShop(list) + if closedNote(list) then + return + end + note(list, 0, "Лоты игроков этого сервера. Цену назначает продавец — это не оценка стоимости рыбы. " + .. "Купленная рыба — не твой улов: не открывает вид в коллекции, не даёт опыт, рекорды и заказы.") + local n = 0 + for _, L in ipairs(state.listings) do + if not L.mine and L.state == "open" then + n += 1 + local it = L.item + local locked = (L.worldLevel or 0) > (state.level or 1) + local coins = player:GetAttribute("Coins") or 0 + local left = math.max(0, L.expires - (state.now or os.time())) + K.itemRow(list, n, { + model = Models.buildFish(it.id, it.mutation, 1, true), dir = K.VIEW.fish, zoom = 0.72, + title = it.name, titleColor = (Config.Rarities[it.rarity] or Config.Rarities.Common).color, + lines = fishLine(it) .. ("\nПродаёт %s%s · ещё %d мин"):format(L.sellerName or "?", it.caughtBy and (" · поймал " .. it.caughtBy) or "", math.ceil(left / 60)), + buttonText = locked and "🔒 Мир закрыт" or ("⚪ " .. fmt(L.price)), + buttonColor = locked and C.grey or (coins >= L.price and C.green or Color3.fromRGB(150, 95, 60)), + active = not locked, + onClick = function() + K.confirm("🏪 Купить рыбу?", ("%s — %s\nПродавец: %s\nЦена: %s ⚪ (продавец платит комиссию %s ⚪ и получит %s ⚪)\n" + .. "Цена — решение продавца. Скупщик даст за эту рыбу ≈ %s ⚪. Купленная рыба придёт в «Посылки».") + :format(it.name, fishLine(it), L.sellerName or "?", fmt(L.price), fmt(L.fee), fmt(L.proceeds), fmt(it.value or 0)), "Купить за " .. fmt(L.price), function() + remote:FireServer("MarketBuy", L.id, L.price) + end) + end, + }) + end + end + if n == 0 then + note(list, 1, "Пока никто ничего не продаёт. Выставь свою рыбу во вкладке «Продать».") + end +end + +local function renderSell(list) + if closedNote(list) then + return + end + local order = 0 + local function o() + order += 1 + return order + end + local mine = {} + for _, L in ipairs(state.listings) do + if L.mine then + table.insert(mine, L) + end + end + Theme.section(list, o(), ("Мои лоты: %d / %d"):format(#mine, M.maxListings), "coin", ("комиссия %d%%"):format(math.floor(M.fee * 100 + 0.5))) + for _, L in ipairs(mine) do + local it = L.item + local left = math.max(0, L.expires - (state.now or os.time())) + K.itemRow(list, o(), { + model = Models.buildFish(it.id, it.mutation, 1, true), dir = K.VIEW.fish, zoom = 0.72, + title = it.name .. " " .. fmt(L.price) .. " ⚪", titleColor = (Config.Rarities[it.rarity] or Config.Rarities.Common).color, + lines = fishLine(it) .. ("\nПолучишь %s ⚪ после комиссии · ещё %d мин"):format(fmt(L.proceeds), math.ceil(left / 60)), + buttonText = L.state == "open" and "Снять" or "Идёт сделка…", buttonColor = L.state == "open" and C.crimson or C.grey, active = L.state == "open", + onClick = function() + remote:FireServer("MarketCancel", L.id) + end, + }) + end + Theme.section(list, o(), "Рыба из сумки", "bag", "«Эпическая» и реже или золотая/радужная") + local any = false + for _, it in ipairs(myItems) do + if eligible(it) then + any = true + local lo = bounds(it) + K.itemRow(list, o(), { + model = Models.buildFish(it.id, it.mutation, 1, true), dir = K.VIEW.fish, zoom = 0.72, + title = it.name, titleColor = (Config.Rarities[it.rarity] or Config.Rarities.Common).color, + lines = fishLine(it) .. ("\nСкупщик: ≈ %s ⚪ · на рынке от %s ⚪%s"):format(fmt(it.value or 0), fmt(lo), it.bought and " · 🛒 куплена" or ""), + buttonText = #mine >= M.maxListings and "Лимит лотов" or "Выставить", buttonColor = #mine >= M.maxListings and C.grey or C.green, + active = #mine < M.maxListings, + onClick = function() + pricer.open(it) + end, + }) + end + end + if not any then + note(list, o(), "В сумке нет рыбы для рынка. Подходит «Эпическая» и реже или рыба с золотой/радужной мутацией.") + end +end + +local function renderInbox(list) + if not state then + note(list, 1, "Загрузка…") + return + end + note(list, 0, ("Сюда приходит купленная рыба и рыба с полной сумкой. Она не пропадёт.%s") + :format(state.pending > 0 and ("\n⏳ Подтверждаются сделки: " .. state.pending) or "")) + for i, it in ipairs(state.inbox) do + K.itemRow(list, i, { + model = Models.buildFish(it.id, it.mutation, 1, true), dir = K.VIEW.fish, zoom = 0.72, + title = it.name, titleColor = (Config.Rarities[it.rarity] or Config.Rarities.Common).color, + lines = fishLine(it) .. (it.bought and ("\n🛒 Куплена у %s за %s ⚪"):format(it.bought.fromName or "?", fmt(it.bought.price or 0)) or "\nВернулась с рынка"), + buttonText = "В сумку", buttonColor = C.green, active = true, + onClick = function() + remote:FireServer("MarketClaim") + end, + }) + end + if #state.inbox == 0 then + note(list, 1, "Посылок нет.") + end +end + +win.render = function(tab) + local list = lists[tab] + if not list then + return + end + K.clear(list) + if tab == "shop" then + renderShop(list) + elseif tab == "sell" then + renderSell(list) + else + renderInbox(list) + end +end + +---------------------------------------------------------------- кнопка и события + +local function open() + remote:FireServer("MarketState") + remote:FireServer("RequestInventory") -- сумка для вкладки «Продать» + win.toggle("shop") +end +K.sideButton(8, "🏪", "Рынок", "K", C.gold, open) +Theme.kit.windows = Theme.kit.windows or {} +Theme.kit.windows.market = win + +UserInputService.InputBegan:Connect(function(input, processed) + if not processed and input.KeyCode == Enum.KeyCode.K then + open() + end +end) + +remote.OnClientEvent:Connect(function(action, a, b) + if action == "Market" then + state = a + win.refresh() + elseif action == "Inventory" then + myItems = a or {} + if win.isOpen() and win.current == "sell" then + win.refresh() + end + end +end) + +-- значок «!» на кнопке, пока в посылках что-то лежит +local function inboxDot() + local dot = K.sideDots and K.sideDots["Рынок"] + if dot then + dot.Visible = (player:GetAttribute("MarketInbox") or 0) > 0 + end +end +player:GetAttributeChangedSignal("MarketInbox"):Connect(inboxDot) +inboxDot() + +remote:FireServer("MarketState") diff --git a/tests/lib.lua b/tests/lib.lua new file mode 100644 index 0000000..538b27d --- /dev/null +++ b/tests/lib.lua @@ -0,0 +1,69 @@ +-- Мини-фреймворк тестов для запуска в Studio через MCP (node tools/run-tests.js). +-- Модули сервера клонируются в отдельную папку, чтобы каждый набор тестов получал свежее состояние. +local T = { results = {}, passed = 0, failed = 0 } + +local SSS = game:GetService("ServerScriptService") +local holder = Instance.new("Folder") +holder.Name = "TestModules_" .. tostring(math.random(1, 1e9)) +holder.Parent = game:GetService("ServerStorage") +T.holder = holder + +-- свежая копия модулей (зависимости ищутся через script.Parent — кладём их рядом) +function T.fresh(...) + local folder = Instance.new("Folder") + folder.Parent = holder + local out = {} + for _, name in ipairs({ "Potions", "Progression", "Market", "PlayerStore" }) do + local m = SSS:FindFirstChild(name) + if m then + m:Clone().Parent = folder + end + end + for i, name in ipairs({ ... }) do + out[i] = require(folder[name]) + end + return table.unpack(out) +end + +function T.test(name, fn) + local ok, err = xpcall(fn, function(e) + return tostring(e) .. "\n" .. debug.traceback(nil, 2) + end) + if ok then + T.passed += 1 + table.insert(T.results, "PASS " .. name) + else + T.failed += 1 + table.insert(T.results, "FAIL " .. name .. " :: " .. tostring(err):sub(1, 600)) + end +end + +function T.eq(a, b, msg) + if a ~= b then + error(("%s: expected %s, got %s"):format(msg or "eq", tostring(b), tostring(a)), 2) + end +end + +function T.ok(v, msg) + if not v then + error(msg or "expected truthy", 2) + end +end + +function T.deep(t) + if type(t) ~= "table" then + return t + end + local c = {} + for k, v in pairs(t) do + c[k] = T.deep(v) + end + return c +end + +function T.report(suite) + holder:Destroy() + return ("%s: %d passed, %d failed\n%s"):format(suite, T.passed, T.failed, table.concat(T.results, "\n")) +end + +return T diff --git a/tests/market.spec.lua b/tests/market.spec.lua new file mode 100644 index 0000000..4669d43 --- /dev/null +++ b/tests/market.spec.lua @@ -0,0 +1,393 @@ +-- Рынок: правила, защита от дюпа, гонки, сбои сохранения и журнала, восстановление после падения. +-- Игроки и сохранения — подделки; журнал — Market.memoryLedger() с инъекцией сбоев. (T — из tests/lib.lua) +local Config = require(game:GetService("ReplicatedStorage").FishConfig) + +local function fish(uid, id, extra) + local f = Config.FindFish(id) + local it = { uid = uid, id = id, name = f.name, rarity = f.rarity, weight = f.minW, value = f.price * 2, gid = "x-" .. uid } + for k, v in pairs(extra or {}) do + it[k] = v + end + return it +end + +-- мир: свежий модуль, игроки, профили, сохранения (снимки = «то, что в DataStore») +local function world(opts) + opts = opts or {} + local Market = T.fresh("Market") + local W = { Market = Market, profiles = {}, saved = {}, saveOk = {}, saveDelay = 0, clock = 1000, notes = {} } + W.ledger = opts.ledger or Market.memoryLedger() + local n = 0 + function W.player(name, level, coins, items) + n += 1 + local p = { UserId = 100 + n, DisplayName = name, Name = name, Parent = true } + W.profiles[p] = { level = level, coins = coins, items = items or {}, nextUid = 100 } + return p + end + Market.init({ + profiles = W.profiles, ledger = W.ledger, + save = function(p) + if W.saveDelay > 0 then + task.wait(W.saveDelay) + end + if W.saveOk[p] == false then + return false + end + W.saved[p] = T.deep(W.profiles[p]) + return true + end, + notify = function(p, text) + table.insert(W.notes, (p and p.DisplayName or "?") .. ": " .. text) + end, + changed = function() end, + send = function() end, + bagCapacity = function(_, d) + return d.cap or 25 + end, + now = function() + return W.clock + end, + wait = function() + task.wait() + end, + guid = function() + n += 1 + return "L" .. n + end, + }) + -- серебро + рыба во всех профилях (включая залог, pending и посылки) — для проверки сохранения ценности + function W.totals() + local coins, fishCount = 0, 0 + for _, d in pairs(W.profiles) do + coins += d.coins + fishCount += #d.items + if d.market then + for _ in pairs(d.market.escrow or {}) do + fishCount += 1 + end + for _, pend in pairs(d.market.pending or {}) do + coins += pend.price -- уже списано, но ещё не решено + end + fishCount += #(d.market.inbox or {}) + end + end + return coins, fishCount + end + return W +end + +local function settle() + for _ = 1, 30 do + task.wait() + end +end + +T.test("на рынок — только ценная рыба, цена в пределах, с 8 уровня", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Karas"), fish(2, "Som"), fish(3, "Karas", { mutation = "Golden" }) }) + local low = W.player("Low", 5, 0, { fish(1, "Som") }) + local M = W.Market + T.eq((M.list(A, 1, 100)), false, "обычная без мутации") + local lo, hi = M.bounds(W.profiles[A].items[2]) + T.ok(lo > W.profiles[A].items[2].value, "минимум выше цены скупщика — нет перепродажи с наваром") + for _, bad in ipairs({ lo - 1, hi + 1, -5, 0, 1.5, 0 / 0, math.huge, "abc", nil }) do + T.eq((M.list(A, 2, bad)), false, "цена " .. tostring(bad)) + end + T.eq((M.list(low, 1, 1000)), false, "уровень") + T.ok(M.list(A, 3, M.bounds(W.profiles[A].items[3])), "золотая мутация подходит") + T.ok(M.list(A, 2, lo)) + T.eq(#W.profiles[A].items, 1, "рыба ушла в залог — продать скупщику нельзя") + T.eq((M.list(A, 2, lo)), false, "вторично выставить ту же рыбу нельзя") +end) + +T.test("лимит лотов", function() + local W = world() + local items = {} + for i = 1, 5 do + items[i] = fish(i, "Som") + end + local A = W.player("A", 10, 0, items) + for i = 1, Config.Market.maxListings do + T.ok(W.Market.list(A, i, 200)) + end + T.eq((W.Market.list(A, 5, 200)), false) +end) + +T.test("покупка: серебро и рыба переходят, комиссия удерживается, журнал «sold»", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local c0, f0 = W.totals() + local _, lid = W.Market.list(A, 1, 300) + T.eq(W.saved[A].market.escrow[lid].price, 300, "залог сохранён до показа лота") + local ok = W.Market.buy(B, lid, 300) + T.ok(ok) + local fee = W.Market.fee(300) + T.eq(W.profiles[B].coins, 700) + T.eq(W.profiles[A].coins, 300 - fee) + T.eq(#W.profiles[B].market.inbox, 1) + local it = W.profiles[B].market.inbox[1] + T.eq(it.bought.from, A.UserId) + T.eq(it.history[1].price, 300) + T.eq(W.ledger.rows[lid].s, "sold") + local c1, f1 = W.totals() + T.eq(c1, c0 - fee, "серебро: минус только комиссия") + T.eq(f1, f0, "рыба не размножилась и не пропала") +end) + +T.test("повтор и чужие ошибки покупки", function() + local W = world() + local A = W.player("A", 20, 0, { fish(1, "Som"), fish(2, "Angler") }) + local B = W.player("B", 10, 100, {}) + local C = W.player("C", 10, 5000, {}) + local _, lid = W.Market.list(A, 1, 300) + local _, lid3 = W.Market.list(A, 2, W.Market.bounds(W.profiles[A].items[1])) + T.eq((W.Market.buy(B, lid, 300)), false, "не хватает серебра") + T.eq((W.Market.buy(A, lid, 300)), false, "свой лот") + T.eq((W.Market.buy(C, lid, 299)), false, "цена не та") + T.eq((W.Market.buy(C, lid3, W.Market._listings()[lid3].price)), false, "рыба из закрытого мира") + T.ok(W.Market.buy(C, lid, 300)) + T.eq((W.Market.buy(C, lid, 300)), false, "повтор того же лота") + T.eq(W.profiles[C].coins, 4700, "списано один раз") +end) + +T.test("одновременные покупки одного лота: проходит одна", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local C = W.player("C", 10, 1000, {}) + local _, lid = W.Market.list(A, 1, 300) + W.saveDelay = 0.05 + local rb, rc + task.spawn(function() + rb = W.Market.buy(B, lid, 300) + end) + task.spawn(function() + rc = W.Market.buy(C, lid, 300) + end) + task.wait(0.3) + T.ok((rb == true) ~= (rc == true), "ровно одна успешна: " .. tostring(rb) .. "/" .. tostring(rc)) + T.eq(W.profiles[B].coins + W.profiles[C].coins, 1700) +end) + +T.test("сбой сохранения покупателя — откат, лот снова открыт", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local _, lid = W.Market.list(A, 1, 300) + W.saveOk[B] = false + T.eq((W.Market.buy(B, lid, 300)), false) + T.eq(W.profiles[B].coins, 1000) + T.eq(next(W.profiles[B].market.pending), nil) + T.eq(W.Market._listings()[lid].state, "open") + T.eq(W.ledger.rows[lid], nil, "в журнале ничего") +end) + +T.test("сбой сохранения продавца при выставлении — рыба в сумке", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + W.saveOk[A] = false + T.eq((W.Market.list(A, 1, 300)), false) + T.eq(#W.profiles[A].items, 1) + T.eq(next(W.profiles[A].market.escrow), nil) +end) + +T.test("журнал упал до записи — сделка отменяется, всё возвращается", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local c0, f0 = W.totals() + local _, lid = W.Market.list(A, 1, 300) + W.ledger.fault.failBefore = 1 + local ok, code = W.Market.buy(B, lid, 300) + T.eq(ok, false) + T.eq(code, "pending") + settle() + T.eq(W.ledger.rows[lid].s, "cancelled") + T.eq(W.profiles[B].coins, 1000, "возврат") + T.eq(#W.profiles[A].items, 1, "рыба вернулась продавцу") + local c1, f1 = W.totals() + T.eq(c1, c0) + T.eq(f1, f0) + T.eq(W.Market._inflight()[A], nil, "операции завершены") +end) + +T.test("журнал записал, но ответ потерялся — сделка всё равно доводится", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local c0, f0 = W.totals() + local _, lid = W.Market.list(A, 1, 300) + W.ledger.fault.failAfter = 1 + W.Market.buy(B, lid, 300) + settle() + T.eq(W.ledger.rows[lid].s, "sold") + T.eq(#W.profiles[B].market.inbox, 1, "покупатель получил") + T.eq(W.profiles[A].coins, 300 - W.Market.fee(300), "продавец получил") + local c1, f1 = W.totals() + T.eq(c1, c0 - W.Market.fee(300)) + T.eq(f1, f0) +end) + +T.test("снятие лота: рыба назад, купить уже нельзя", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local _, lid = W.Market.list(A, 1, 300) + T.ok(W.Market.cancel(A, lid, "manual")) + T.eq(#W.profiles[A].items, 1) + T.eq(W.ledger.rows[lid].s, "cancelled") + T.eq((W.Market.buy(B, lid, 300)), false) + T.eq((W.Market.cancel(B, lid, "manual")), false, "чужой лот не снять") +end) + +T.test("лот истекает по времени; полная сумка — рыба в посылки и забирается позже", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local _, lid = W.Market.list(A, 1, 300) + local d = W.profiles[A] + d.cap = 0 -- сумка «полна» + W.clock += Config.Market.duration + 1 + W.Market.tick() + settle() + T.eq(W.Market._listings()[lid], nil) + T.eq(#d.market.inbox, 1, "в посылках") + d.cap = 25 + T.eq(W.Market.claim(A), 1) + T.eq(#d.items, 1) +end) + +T.test("падение сервера после фиксации: восстановление по журналу у обоих", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local _, lid = W.Market.list(A, 1, 300) + -- «сохранённое»: залог у продавца, pending и списание у покупателя; журнал уже «sold»; дальше сервер упал + local Ad = T.deep(W.profiles[A]) + local Bd = T.deep(W.profiles[B]) + Bd.coins -= 300 + Bd.market = Bd.market or {} + Bd.market.pending = { [lid] = { price = 300, sellerId = A.UserId, sellerName = "A", item = T.deep(Ad.market.escrow[lid].item), t = 1 } } + W.ledger.rows[lid] = { s = "sold", buyer = B.UserId, seller = A.UserId, price = 300, fee = W.Market.fee(300) } + -- новый сервер: свежий модуль, тот же журнал + local W2 = world({ ledger = W.ledger }) + W2.profiles[A], W2.profiles[B] = Ad, Bd + T.ok(W2.Market.recover(A, Ad)) + T.ok(W2.Market.recover(B, Bd)) + T.eq(Ad.coins, 300 - W.Market.fee(300)) + T.eq(next(Ad.market.escrow), nil) + T.eq(#Bd.market.inbox, 1) + T.eq(Bd.coins, 700) + -- повторное восстановление ничего не удваивает + T.eq(W2.Market.recover(A, Ad), false) + T.eq(W2.Market.recover(B, Bd), false) + T.eq(Ad.coins, 300 - W.Market.fee(300)) +end) + +T.test("падение до фиксации: кто бы ни зашёл первым — возврат обоим", function() + for _, order in ipairs({ "sellerFirst", "buyerFirst" }) do + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local _, lid = W.Market.list(A, 1, 300) + local Ad = T.deep(W.profiles[A]) + local Bd = T.deep(W.profiles[B]) + Bd.coins -= 300 + Bd.market = { pending = { [lid] = { price = 300, sellerId = A.UserId, item = T.deep(Ad.market.escrow[lid].item), t = 1 } } } + local W2 = world({ ledger = W.ledger }) + W2.profiles[A], W2.profiles[B] = Ad, Bd + if order == "sellerFirst" then + W2.Market.recover(A, Ad) + W2.Market.recover(B, Bd) + else + W2.Market.recover(B, Bd) + W2.Market.recover(A, Ad) + end + T.eq(W.ledger.rows[lid].s, "cancelled", order) + T.eq(Bd.coins, 1000, order .. ": серебро вернулось") + T.eq(#Ad.items, 1, order .. ": рыба вернулась") + end +end) + +T.test("журнал недоступен при входе — сделка ждёт, ничего не теряется", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local _, lid = W.Market.list(A, 1, 300) + local Ad = T.deep(W.profiles[A]) + local W2 = world({ ledger = W.ledger }) + W2.profiles[A] = Ad + W.ledger.fault.failBefore = 1 + T.eq(W2.Market.recover(A, Ad), false) + T.ok(W2.Market.unresolved(Ad), "залог на месте") + T.ok(W2.Market.recover(A, Ad), "со второго раза") + T.eq(#Ad.items, 1) +end) + +T.test("продавец уходит во время покупки: выход ждёт сделку, дюпа нет", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + local B = W.player("B", 10, 1000, {}) + local c0, f0 = W.totals() + local _, lid = W.Market.list(A, 1, 300) + W.saveDelay = 0.1 + local done = false + task.spawn(function() + W.Market.buy(B, lid, 300) + end) + task.wait(0.02) + A.Parent = nil + task.spawn(function() + W.Market.onLeave(A, 5) + done = true + end) + task.wait(0.5) + T.ok(done, "выход завершился") + T.eq(W.ledger.rows[lid].s, "sold") + local c1, f1 = W.totals() + T.eq(c1, c0 - W.Market.fee(300)) + T.eq(f1, f0) +end) + +T.test("выход продавца снимает его лоты", function() + local W = world() + local A = W.player("A", 10, 0, { fish(1, "Som") }) + W.Market.list(A, 1, 300) + A.Parent = nil + W.Market.onLeave(A, 1) + T.eq(#W.profiles[A].items, 1) + T.eq(next(W.Market._listings()), nil) +end) + +T.test("частые запросы с клиента режутся", function() + local W = world() + local items = {} + for i = 1, 3 do + items[i] = fish(i, "Som") + end + local A = W.player("A", 10, 0, items) + W.Market.onAction(A, "MarketList", 1, 300) + W.Market.onAction(A, "MarketList", 2, 300) + W.Market.onAction(A, "MarketList", 3, 300) + local n = 0 + for _ in pairs(W.Market._listings()) do + n += 1 + end + T.eq(n, 1, "одно действие за " .. Config.Market.actionCooldown .. " с") +end) + +T.test("купленную рыбу можно перепродать; история не длиннее 5", function() + local W = world() + local hist = {} + for i = 1, 5 do + hist[i] = { from = i, to = i + 1, price = 100, t = i } + end + local A = W.player("A", 10, 0, { fish(1, "Som", { bought = { from = 1, price = 100 }, history = hist }) }) + local B = W.player("B", 10, 1000, {}) + local _, lid = W.Market.list(A, 1, 300) + T.ok(W.Market.buy(B, lid, 300)) + local it = W.profiles[B].market.inbox[1] + T.eq(#it.history, 5) + T.eq(it.history[5].to, B.UserId) +end) + +return T.report("market") diff --git a/tests/playerstore.spec.lua b/tests/playerstore.spec.lua new file mode 100644 index 0000000..fbc5952 --- /dev/null +++ b/tests/playerstore.spec.lua @@ -0,0 +1,127 @@ +-- Замок сессии профиля (PlayerStore). Поддельный DataStore с семантикой UpdateAsync. (T — из tests/lib.lua) +local PlayerStore = T.fresh("PlayerStore") + +local function fakeStore() + local S = { rows = {}, fail = 0, delay = 0, log = {} } + function S:UpdateAsync(key, fn) + if self.delay > 0 then + task.wait(self.delay) + end + if self.fail > 0 then + self.fail -= 1 + error("DataStore error (fake)") + end + local cur = self.rows[key] and T.deep(self.rows[key]) + local new = fn(cur) + if new ~= nil then + self.rows[key] = T.deep(new) + table.insert(self.log, key) + end + return new + end + return S +end + +local clock = 1000 +local function server(store, job) + return PlayerStore.new(store, { jobId = job, staleAfter = 600, loadTries = 2, now = function() + return clock + end, wait = function() end }) +end + +T.test("новый игрок: загрузка ставит замок", function() + local st = fakeStore() + local s1 = server(st, "job1") + local status, v = s1:load("p1") + T.eq(status, "ok") + T.eq(v._lock.job, "job1") +end) + +T.test("профиль открыт другим сервером — не пускаем, данные не трогаем", function() + local st = fakeStore() + server(st, "job1"):load("p1") + st.rows.p1.coins = 50 + local status = server(st, "job2"):load("p1") + T.eq(status, "locked") + T.eq(st.rows.p1._lock.job, "job1") +end) + +T.test("сервер упал: устаревший замок перехватывается", function() + local st = fakeStore() + server(st, "job1"):load("p1") + clock += 700 + local status = server(st, "job2"):load("p1") + T.eq(status, "ok") + T.eq(st.rows.p1._lock.job, "job2") +end) + +T.test("старый сервер после перехвата писать не может", function() + local st = fakeStore() + local s1, s2 = server(st, "job1"), server(st, "job2") + s1:load("p1") + clock += 700 + s2:load("p1") + st.rows.p1.coins = 999 + local ok, status = s1:save("p1", { coins = 1 }) + T.eq(ok, false) + T.eq(status, "lost") + T.eq(st.rows.p1.coins, 999, "не перезаписано") +end) + +T.test("выход снимает замок — другой сервер сразу загружает", function() + local st = fakeStore() + local s1 = server(st, "job1") + local _, data = s1:load("p1") + data.coins = 10 + T.ok(s1:save("p1", data, true)) + T.eq(st.rows.p1._lock, nil) + local status, v = server(st, "job2"):load("p1") + T.eq(status, "ok") + T.eq(v.coins, 10) +end) + +T.test("ошибка хранилища: сохранение сообщает false", function() + local st = fakeStore() + local s1 = server(st, "job1") + local _, data = s1:load("p1") + st.fail = 1 + local ok, status = s1:save("p1", data) + T.eq(ok, false) + T.eq(status, "error") + T.ok(s1:save("p1", data), "следующее проходит") +end) + +T.test("ошибка при загрузке — повтор, потом error (без потери данных)", function() + local st = fakeStore() + st.rows.p1 = { coins = 5 } + st.fail = 5 + local status = server(st, "job1"):load("p1") + T.eq(status, "error") + T.eq(st.rows.p1.coins, 5) +end) + +T.test("сохранения одного игрока идут по очереди", function() + local st = fakeStore() + local s1 = server(st, "job1") + s1.wait = task.wait + local _, data = s1:load("p1") + st.delay = 0.05 + local order = {} + task.spawn(function() + local d = T.deep(data) + d.v = 1 + s1:save("p1", d) + table.insert(order, 1) + end) + task.spawn(function() + local d = T.deep(data) + d.v = 2 + s1:save("p1", d) + table.insert(order, 2) + end) + task.wait(0.4) + T.eq(#order, 2) + T.eq(st.rows.p1.v, 2, "последнее записанное — последнее начатое") +end) + +return T.report("playerstore") diff --git a/tests/potions.spec.lua b/tests/potions.spec.lua new file mode 100644 index 0000000..1dcbb92 --- /dev/null +++ b/tests/potions.spec.lua @@ -0,0 +1,137 @@ +-- Зелья: сумка, одно действующее, замена только с подтверждением, слабое не продлевает сильное, +-- трата попытки при поклёвке, перенос старого зелья. (T — из tests/lib.lua) +local Potions = T.fresh("Potions") +local Config = require(game:GetService("ReplicatedStorage").FishConfig) + +local function fresh() + return { potions = nil, boostUntil = 0, boostBonus = 0 } +end + +T.test("награда кладётся в сумку и не пьётся сама", function() + local d = fresh() + T.ok(Potions.add(d, "Focus", 1)) + T.eq(Potions.count(d, "Focus"), 1) + T.eq(Potions.active(d), nil, "ничего не действует") +end) + +T.test("выпить: попытки и минус из сумки", function() + local d = fresh() + Potions.add(d, "Focus", 2) + local ok, code = Potions.activate(d, "Focus") + T.ok(ok) + T.eq(code, "started") + local _, a = Potions.active(d) + T.eq(a.left, 20) + T.eq(Potions.count(d, "Focus"), 1) +end) + +T.test("другое зелье без подтверждения — отказ, ничего не меняется", function() + local d = fresh() + Potions.add(d, "Mutation", 1) + Potions.add(d, "Focus", 1) + Potions.activate(d, "Mutation") + local ok, code, info = Potions.activate(d, "Focus", false) + T.eq(ok, false) + T.eq(code, "needConfirm") + T.eq(info.activeId, "Mutation") + local def, a = Potions.active(d) + T.eq(def.id, "Mutation", "сильное не тронуто") + T.eq(a.left, 20, "слабое не продлило сильное") + T.eq(Potions.count(d, "Focus"), 1, "слабое осталось в сумке") +end) + +T.test("замена с подтверждением: сообщаем, что пропало", function() + local d = fresh() + Potions.add(d, "Mutation", 1) + Potions.add(d, "Focus", 1) + Potions.activate(d, "Mutation") + Potions.consumeAttempt(d, "Mutation") + local ok, code, info = Potions.activate(d, "Focus", true) + T.ok(ok) + T.eq(code, "replaced") + T.eq(info.lostId, "Mutation") + T.eq(info.lostLeft, 19) + T.eq((Potions.active(d)).id, "Focus") +end) + +T.test("то же зелье поверх продлевает, но не выше предела", function() + local d = fresh() + Potions.add(d, "Trophy", 5) + Potions.activate(d, "Trophy") + T.eq(select(2, Potions.activate(d, "Trophy")), "extended") + T.eq(select(2, Potions.active(d)).left, 40) + Potions.activate(d, "Trophy") + T.eq(select(2, Potions.active(d)).left, Config.PotionMaxCharges) + local ok, code = Potions.activate(d, "Trophy") + T.eq(ok, false) + T.eq(code, "full") + T.eq(Potions.count(d, "Trophy"), 2, "лишнее не списано") +end) + +T.test("попытка тратится только для зелья, действовавшего при забросе", function() + local d = fresh() + Potions.add(d, "Swift", 1) + Potions.activate(d, "Swift") + T.eq(Potions.consumeAttempt(d, "Focus"), false, "чужой снимок") + T.eq(Potions.consumeAttempt(d, nil), false, "без зелья при забросе") + T.eq(select(2, Potions.active(d)).left, 20) + for _ = 1, 20 do + T.ok(Potions.consumeAttempt(d, "Swift")) + end + T.eq(Potions.active(d), nil, "кончилось") +end) + +T.test("отмена до поклёвки не тратит (consume не вызывается) — эффект берётся снимком", function() + local d = fresh() + Potions.add(d, "Research", 1) + Potions.activate(d, "Research") + local snap = Potions.effect(d) + T.eq(snap.newSpecies, 3) + -- игрок отменил до поклёвки: сервер не зовёт consumeAttempt + T.eq(select(2, Potions.active(d)).left, 20) +end) + +T.test("зелья на время тикают, на попытки — нет", function() + local d = fresh() + Potions.add(d, "SuperLuck", 1) + Potions.activate(d, "SuperLuck") + T.eq(Potions.effect(d).luck, 2.0) + Potions.tick(d, 899) + T.eq(select(2, Potions.active(d)).left, 1) + T.eq(Potions.tick(d, 1), true, "закончилось") + local d2 = fresh() + Potions.add(d2, "Focus", 1) + Potions.activate(d2, "Focus") + Potions.tick(d2, 1000) + T.eq(select(2, Potions.active(d2)).left, 20) +end) + +T.test("перенос старого зелья удачи: остаток секунд и сила сохраняются", function() + local d = { boostUntil = 1000 + 420, boostBonus = 1.0 } + Potions.migrateLegacy(d, 1000) + local def, a = Potions.active(d) + T.eq(def.id, "Legacy") + T.eq(a.left, 420) + T.eq(Potions.effect(d).luck, 1.0) + T.eq(d.boostUntil, 0) + local d2 = { boostUntil = 500, boostBonus = 2 } + Potions.migrateLegacy(d2, 1000) + T.eq(Potions.active(d2), nil, "истёкшее не переносится") +end) + +T.test("старое и неизвестное нельзя добавить или выпить", function() + local d = fresh() + T.eq(Potions.add(d, "Legacy", 1), false) + T.eq(Potions.add(d, "Nope", 1), false) + T.eq(Potions.add(d, "Focus", -3), false) + T.eq((Potions.activate(d, "Legacy")), false) + T.eq(select(2, Potions.activate(d, "Focus")), "none") +end) + +T.test("нет зелий на опыт карьеры", function() + for _, p in ipairs(Config.Potions) do + T.eq(p.xp, nil, p.id) + end +end) + +return T.report("potions") diff --git a/tests/progression.spec.lua b/tests/progression.spec.lua new file mode 100644 index 0000000..f975c3a --- /dev/null +++ b/tests/progression.spec.lua @@ -0,0 +1,110 @@ +-- Опыт карьеры и миграция v1 → v2. (T — из tests/lib.lua) +local Progression = T.fresh("Progression") +local Config = require(game:GetService("ReplicatedStorage").FishConfig) + +T.test("опыт за поимку: только ручная, фиксированный по миру", function() + T.eq(Progression.catchXP("World1"), 5) + T.eq(Progression.catchXP("World2"), 7) + T.eq(Progression.catchXP("World3"), 9) + T.eq(Progression.catchXP("World1", { auto = true }), 0, "автоловля") + T.eq(Progression.catchXP("World3", { bought = true }), 0, "купленная") +end) + +T.test("других источников опыта карьеры в конфиге нет", function() + for k, r in pairs(Config.CollectionRewards) do + T.eq(r.xp, nil, "коллекция " .. k) + end + for k, q in pairs(Config.QuestKinds) do + T.eq(q.xp, nil, "задание " .. k) + end + T.eq(Config.ChainBonus.xp, nil, "цепочка") + T.eq(Config.Boss.reward.xp, nil, "босс") + for _, zone in pairs(Config.Zones) do + for _, f in ipairs(zone.fish) do + T.eq(f.xp, nil, "рыба " .. f.id) + end + end + T.eq(Config.Economy.autoXP, 0) +end) + +T.test("кривая: мир 2 за 120 мин, мир 3 за 660, ур.25 за 1300 при 4 рыбах/мин", function() + local function minutes(to) + local t = 0 + for lvl = 1, to - 1 do + local w = lvl >= 18 and "World3" or (lvl >= 8 and "World2" or "World1") + t += Config.XPForLevel(lvl) / (4 * Config.CareerXP(w)) + end + return t + end + T.eq(math.floor(minutes(8) + 0.5), 120) + T.eq(math.floor(minutes(18) + 0.5), 660) + T.eq(math.floor(minutes(25) + 0.5), 1300) + T.eq(Config.XPForLevel(25), 36 * (115 + 5), "после таблицы") +end) + +T.test("уровень растёт по таблице, один вызов — не больше 3 уровней", function() + local d = { level = 1, xp = 0 } + local lv = Progression.addXp(d, 99) + T.eq(#lv, 0) + lv = Progression.addXp(d, 1) + T.eq(lv[1], 2) + T.eq(d.xp, 0) + local d2 = { level = 1, xp = 0 } + lv = Progression.addXp(d2, 1000000) + T.eq(#lv, 3, "предохранитель") + T.eq(d2.level, 4) +end) + +T.test("миграция: уровень тот же, доля текущего уровня сохраняется", function() + local oldNeed = Config.Economy.legacyXP(10) + local d = { level = 10, xp = math.floor(oldNeed / 2), coins = 12345, rods = { Basic = true, Carbon = true }, passes = { VIP = true }, + discovered = { Karas = { count = 3, best = 1 } }, items = { { uid = 7, id = "Som", value = 130 } }, rest = 120, + boostUntil = 0, boostBonus = 0 } + T.ok(Progression.migrate(d, { now = 1000, userId = 42, name = "Tester" })) + T.eq(d.level, 10) + local frac = d.xp / Config.XPForLevel(10) + T.ok(math.abs(frac - 0.5) < 0.01, "доля " .. frac) + T.eq(d.coins, 12345, "серебро") + T.ok(d.rods.Carbon and d.passes.VIP and d.discovered.Karas, "имущество") + T.eq(d.items[1].gid, "42-7") + T.eq(d.items[1].value, 130, "цена пойманной рыбы не меняется") + T.eq(d.rest, 120) + T.eq(d.econ, Config.Economy.version) + -- повторный запуск ничего не меняет + local xp = d.xp + T.eq(Progression.migrate(d, { now = 5000, userId = 42 }), false) + T.eq(d.xp, xp) +end) + +T.test("миграция: высокий уровень и переполненный опыт не дают лишних уровней", function() + local d = { level = 31, xp = 10 ^ 9, items = {} } + Progression.migrate(d, { now = 1, userId = 1 }) + T.eq(d.level, 31) + T.ok(d.xp < Config.XPForLevel(31)) +end) + +T.test("миграция переносит действующее зелье удачи", function() + local d = { level = 3, xp = 0, items = {}, boostUntil = 1300, boostBonus = 0.5 } + Progression.migrate(d, { now = 1000, userId = 1 }) + T.eq(d.potions.active.id, "Legacy") + T.eq(d.potions.active.left, 300) + T.eq(d.potions.active.luck, 0.5) +end) + +T.test("удача смягчена: мифическая не становится частой, мутации не выше потолка", function() + local beff = Config.EffectiveLuck(1 + 10) + T.ok(beff < Config.Economy.luckCap, "потолок") + local total, myth = 0, 0 + for _, f in ipairs(Config.Zones.World1.fish) do + local w = Config.RarityWeight(f.rarity, beff) + total += w + if f.rarity == "Mythic" then + myth += w + end + end + T.ok(myth / total < 0.01, "мифическая < 1% даже при удаче +1000%") + T.eq(Config.MutationMult(beff, 100), Config.Economy.mutationCap) + T.eq(Config.WaitMult(0.1), Config.Economy.waitFloor) +end) + +return T.report("progression") diff --git a/tools/baseline/FishConfig_v1.lua b/tools/baseline/FishConfig_v1.lua new file mode 100644 index 0000000..2090d74 --- /dev/null +++ b/tools/baseline/FishConfig_v1.lua @@ -0,0 +1,722 @@ +-- FishConfig (ModuleScript) -> ReplicatedStorage +-- Все настройки игры. Меняй цифры здесь, чтобы настроить баланс. + +local Config = {} + +Config.GameName = "Клёвое место" + +---------------------------------------------------------------- миры +-- center = центр мира на карте; mult = множитель наград коллекции +Config.Worlds = { + { + id = "World1", name = "Тихое озеро", icon = "🌊", level = 1, mult = 1, + center = Vector3.new(0, 0, 1500), color = Color3.fromRGB(60, 200, 255), + desc = "Спокойное лесное озеро. Отличное место, чтобы начать.", + clock = 16.2, + waterY = 0, + lakes = { { 0, -15, 62 }, { -42, 8, 34 }, { 44, 2, 36 }, { 0, 22, 30 }, { 48, -50, 22 } }, -- { x, z, радиус } от центра + -- внешний вид только этого мира (применяет клиент при входе, при выходе возвращает как было) + tint = Color3.fromRGB(255, 247, 236), + -- свет и эффекты: свойства Lighting и его эффектов; чего здесь нет, остаётся как в MapBuilder + look = { + lighting = { + -- днём солнце не выжигает светлый песок и траву: яркость и экспозиция ниже + Brightness = 2.0, ExposureCompensation = -0.35, + Ambient = Color3.fromRGB(62, 66, 84), OutdoorAmbient = Color3.fromRGB(105, 112, 132), + ColorShift_Top = Color3.fromRGB(255, 232, 196), + EnvironmentDiffuseScale = 0.5, EnvironmentSpecularScale = 0.6, + }, + -- дымка вдали: Density — сколько тумана, Haze — насколько он плотный у горизонта + atmosphere = { + Density = 0.38, Offset = 0.1, Haze = 1.2, Glare = 0.15, + Color = Color3.fromRGB(188, 204, 224), Decay = Color3.fromRGB(196, 176, 160), + }, + color = { Saturation = 0.16, Contrast = 0.12, Brightness = -0.04 }, + -- свечение только у по-настоящему ярких мест (огни ночью), без ореолов вокруг светлого днём + bloom = { Intensity = 0.25, Size = 24, Threshold = 1.9 }, + sunRays = { Intensity = 0.05, Spread = 0.6 }, + -- мягкий тонмаппинг: светлое не выгорает в белое + grading = { TonemapperPreset = Enum.TonemapperPreset.Default }, + -- лёгкое размытие дальнего плана + dof = { Enabled = true, FarIntensity = 0.2, FocusDistance = 60, InFocusRadius = 120, NearIntensity = 0 }, + }, + -- земля мира залита материалом Snow (ровный, без травинок), дорожки — Salt; здесь они перекрашиваются + terrainColors = { + Snow = Color3.fromRGB(127, 163, 63), Salt = Color3.fromRGB(191, 155, 105), + Rock = Color3.fromRGB(132, 139, 155), Slate = Color3.fromRGB(132, 139, 155), + Mud = Color3.fromRGB(78, 110, 92), Sand = Color3.fromRGB(205, 190, 140), + }, + }, + { + id = "World2", name = "Тропический остров", icon = "🏝", level = 8, mult = 4, + center = Vector3.new(1500, 0, 0), color = Color3.fromRGB(255, 190, 70), + desc = "Бирюзовое море, пальмы и яркая рифовая рыба.", + clock = 13, + waterY = 0, + sea = 74, -- всё дальше этого радиуса от центра — море (лагуна вокруг острова, пляж — кольцо ~r 64..79) + }, + { + id = "World3", name = "Ледяной фьорд", icon = "❄", level = 18, mult = 12, + center = Vector3.new(-1500, 0, 0), color = Color3.fromRGB(150, 220, 255), + desc = "Рыбалка в лунках среди льдов и северного сияния.", + clock = 18.3, + waterY = 1, + lakes = { { 0, 0, 70 }, { -55, 30, 45 }, { 55, -25, 50 }, { 5, -70, 40 } }, -- подо льдом + holes = { + { 0, 40 }, { -22, 18 }, { 22, 12 }, { 0, -12 }, { -30, -30 }, { 30, 40 }, { -60, 35 }, + { -45, 15 }, { 55, -25 }, { 75, -5 }, { 40, -50 }, { 5, -75 }, { -15, -60 }, { 25, -80 }, + }, + holeRadius = 6, + -- цвета террейна общие на весь плейс, а в нём сохранены цвета «Тихого озера» (зелёный Snow) — + -- поэтому снег фьорда задаём явно + terrainColors = { Snow = Color3.fromRGB(205, 212, 228) }, + }, + { + id = "World4", name = "Вулкан", icon = "🌋", level = 30, mult = 30, soon = true, + center = Vector3.new(0, 0, -1500), color = Color3.fromRGB(255, 90, 40), + desc = "Рыбалка в лаве. Скоро!", + }, +} +Config.WorldRadius = 260 + +-- камера игрока: насколько близко и далеко можно отвести колесом (в studs); +-- maxZoom держит обзор внутри локаций — дальше видно край карты +Config.Camera = { minZoom = 0.5, maxZoom = 35 } + +-- лента активности (слева внизу у всех игроков) и оповещения о редком улове +-- announceRank / announceMutations — крупный баннер со звуком у всех на сервере; +-- globalRank / globalMutations — улов уходит и на другие серверы игры (MessagingService); +-- lines — сколько строк в ленте, lineTime — сколько секунд строка остаётся видна +Config.Feed = { + announceRank = 4, announceMutations = { Golden = true, Rainbow = true }, + globalRank = 5, globalMutations = { Rainbow = true }, + lines = 6, lineTime = 30, +} + +-- доски лидеров в лобби (глобальные, по всем серверам; обновляются раз в refresh секунд). +-- attr — атрибут игрока, который считает сервер; store — имя OrderedDataStore (смена имени = новый топ с нуля) +Config.Leaderboards = { + refresh = 60, size = 10, + boards = { + { id = "Donate", title = "💎 Топ донатеров", attr = "RobuxSpent", store = "TopRobux_v1", unit = "R$", color = Color3.fromRGB(205, 140, 255) }, + { id = "Earn", title = "⚪ Топ по заработку", attr = "CoinsEarned", store = "TopEarned_v1", unit = "⚪", color = Color3.fromRGB(255, 214, 90) }, + { id = "Catch", title = "🎣 Топ рыболовов", attr = "TotalCaught", store = "TopCaught_v1", unit = "🐟", color = Color3.fromRGB(120, 210, 255) }, + }, +} + +-- экран загрузки: при входе в игру и при каждом телепорте игрок уже стоит на месте, сцена прогружается +-- и свет локации ставится под ним; картинку видно только после этого (секунды — минимум показа) +Config.Loading = { + firstJoin = 3, + teleport = 2.5, +} + +-- лобби: те же поля внешнего вида, что у миров (clock, tint, look, terrainColors); клиент применяет их вне миров +Config.Lobby = { + id = "Lobby", + clock = 16.3, -- предвечернее солнце: тени длиннее, свет теплее + tint = Color3.fromRGB(255, 242, 228), + look = { + lighting = { + Brightness = 2.0, ExposureCompensation = -0.3, + Ambient = Color3.fromRGB(64, 60, 72), OutdoorAmbient = Color3.fromRGB(120, 114, 124), + ColorShift_Top = Color3.fromRGB(255, 224, 186), + EnvironmentDiffuseScale = 0.5, EnvironmentSpecularScale = 0.5, + GlobalShadows = true, + }, + -- тёплая дымка: дальние холмы за скалами тонут в ней + atmosphere = { + Density = 0.4, Offset = 0.18, Haze = 1.6, Glare = 0.25, + Color = Color3.fromRGB(222, 212, 204), Decay = Color3.fromRGB(186, 160, 150), + }, + color = { Saturation = 0.18, Contrast = 0.14, Brightness = -0.04 }, + bloom = { Intensity = 0.3, Size = 24, Threshold = 1.8 }, + sunRays = { Intensity = 0.05, Spread = 0.7 }, + dof = { Enabled = true, FarIntensity = 0.18, FocusDistance = 55, InFocusRadius = 95, NearIntensity = 0 }, + -- мягкий тонмаппинг вместо Retro: светлая плитка и вывески не выгорают в белое + grading = { TonemapperPreset = Enum.TonemapperPreset.Default }, + }, + terrainColors = { + Grass = Color3.fromRGB(104, 150, 72), Ground = Color3.fromRGB(120, 98, 74), Rock = Color3.fromRGB(140, 126, 130), + }, +} + +function Config.WorldAt(pos) + for _, w in ipairs(Config.Worlds) do + if not w.soon then + local d = Vector3.new(pos.X - w.center.X, 0, pos.Z - w.center.Z).Magnitude + if d < Config.WorldRadius then + return w + end + end + end + return nil +end + +-- куда бросать из этой точки (единичный вектор по горизонтали): к центру ближайшего озера или лунки, +-- а если ближе море — от центра острова к морю +function Config.CastDirection(world, pos) + if not world then + return nil + end + local x, z = pos.X - world.center.X, pos.Z - world.center.Z + local best, bestGap + local function consider(dir, gap) + if dir.Magnitude > 0.1 and (not bestGap or gap < bestGap) then + best, bestGap = dir.Unit, gap + end + end + if world.holes then + for _, h in ipairs(world.holes) do + consider(Vector3.new(h[1] - x, 0, h[2] - z), math.sqrt((h[1] - x) ^ 2 + (h[2] - z) ^ 2) - (world.holeRadius or 6)) + end + end + for _, l in ipairs(world.lakes or {}) do + if not world.holes then -- в Мире 3 озёра подо льдом, бросаем только в лунки + consider(Vector3.new(l[1] - x, 0, l[2] - z), math.sqrt((l[1] - x) ^ 2 + (l[2] - z) ^ 2) - l[3]) + end + end + if world.sea then + consider(Vector3.new(x, 0, z), world.sea - math.sqrt(x * x + z * z)) + end + return best +end + +-- расстояние по горизонтали от точки до ближайшей воды (0 — над водой: на причале или в воде) +function Config.WaterGap(world, pos) + if not world then + return math.huge + end + local x, z = pos.X - world.center.X, pos.Z - world.center.Z + local gap = math.huge + if world.holes then + for _, h in ipairs(world.holes) do + gap = math.min(gap, math.sqrt((h[1] - x) ^ 2 + (h[2] - z) ^ 2) - (world.holeRadius or 6)) + end + else + for _, l in ipairs(world.lakes or {}) do + gap = math.min(gap, math.sqrt((l[1] - x) ^ 2 + (l[2] - z) ^ 2) - l[3]) + end + end + if world.sea then + gap = math.min(gap, world.sea - math.sqrt(x * x + z * z)) + end + return math.max(0, gap) +end + +-- можно ли закидывать отсюда (pos — центр персонажа): стоим на берегу или платформе +-- и до воды не дальше Config.CastReach. Возвращает true или текст подсказки. +-- humanoid можно не передавать (на сервере его состояние ненадёжно) — тогда проверяем только по высоте. +function Config.CanCastFrom(world, pos, humanoid) + if not world then + return "🌍 Тут нет рыбы" + end + local inWater = pos.Y < (world.waterY or 0) + 2 -- у плывущего персонажа центр почти на уровне воды + if humanoid then + inWater = inWater or humanoid:GetState() == Enum.HumanoidStateType.Swimming or humanoid.FloorMaterial == Enum.Material.Water + end + if inWater then + return "🏊 Выйди из воды" + end + if humanoid and humanoid.FloorMaterial == Enum.Material.Air then + return "Встань на землю" + end + if Config.WaterGap(world, pos) > Config.CastReach then + return "🌊 Подойди к воде" + end + return true +end + +-- есть ли вода в этой точке мира (озеро, море или лунка) +function Config.IsWater(world, pos) + if not world then + return false + end + local x, z = pos.X - world.center.X, pos.Z - world.center.Z + if world.holes then + local r = world.holeRadius or 6 + for _, h in ipairs(world.holes) do + if (x - h[1]) ^ 2 + (z - h[2]) ^ 2 <= r * r then + return true + end + end + return false + end + if world.sea and math.sqrt(x * x + z * z) >= world.sea then + return true + end + for _, l in ipairs(world.lakes or {}) do + if (x - l[1]) ^ 2 + (z - l[2]) ^ 2 <= (l[3] - 1) ^ 2 then + return true + end + end + return false +end + +---------------------------------------------------------------- редкости +Config.Rarities = { + Common = { name = "Обычная", rank = 1, weight = 55, color = Color3.fromRGB(215, 220, 225) }, + Uncommon = { name = "Необычная", rank = 2, weight = 27, color = Color3.fromRGB(95, 225, 115) }, + Rare = { name = "Редкая", rank = 3, weight = 11, color = Color3.fromRGB(70, 160, 255) }, + Epic = { name = "Эпическая", rank = 4, weight = 4.5, color = Color3.fromRGB(185, 90, 255) }, + Legendary = { name = "Легендарная", rank = 5, weight = 1.2, color = Color3.fromRGB(255, 185, 35) }, + Mythic = { name = "Мифическая", rank = 6, weight = 0.25, color = Color3.fromRGB(255, 80, 150) }, +} +Config.RarityOrder = { "Common", "Uncommon", "Rare", "Epic", "Legendary", "Mythic" } + +---------------------------------------------------------------- мутации +Config.Mutations = { + { id = "Rainbow", name = "Радужная", chance = 0.002, mult = 10, color = Color3.fromRGB(255, 120, 230) }, + { id = "Golden", name = "Золотая", chance = 0.010, mult = 5, color = Color3.fromRGB(255, 205, 60) }, + { id = "Shiny", name = "Блестящая", chance = 0.040, mult = 2, color = Color3.fromRGB(170, 240, 255) }, +} + +---------------------------------------------------------------- рыба +-- shape: classic, long, tall, flat, ray, puffer, shark, eel, sword, angler, jelly, sturgeon +-- color2 = второй цвет (плавники/узор); stripes/spots/whiskers/spikes/glow — украшения модели +local function F(t) + return t +end + +Config.Zones = { + World1 = { + fish = { + F({ id = "Karas", name = "Карась", rarity = "Common", price = 5, xp = 8, minW = 0.2, maxW = 1.2, size = 1.0, shape = "tall", color = Color3.fromRGB(205, 170, 75), color2 = Color3.fromRGB(170, 120, 50) }), + F({ id = "Plotva", name = "Плотва", rarity = "Common", price = 6, xp = 8, minW = 0.1, maxW = 0.8, size = 0.9, shape = "classic", color = Color3.fromRGB(195, 200, 210), color2 = Color3.fromRGB(220, 80, 60) }), + F({ id = "Ersh", name = "Ёрш", rarity = "Common", price = 7, xp = 9, minW = 0.1, maxW = 0.4, size = 0.8, shape = "classic", color = Color3.fromRGB(135, 125, 75), color2 = Color3.fromRGB(95, 85, 50), spikes = true, spots = 6 }), + F({ id = "Okun", name = "Окунь", rarity = "Uncommon", price = 15, xp = 18, minW = 0.3, maxW = 1.5, size = 1.0, shape = "classic", color = Color3.fromRGB(150, 180, 70), color2 = Color3.fromRGB(230, 90, 40), stripes = 5, spikes = true }), + F({ id = "Lesh", name = "Лещ", rarity = "Uncommon", price = 18, xp = 20, minW = 0.5, maxW = 3.0, size = 1.2, shape = "tall", color = Color3.fromRGB(175, 145, 95), color2 = Color3.fromRGB(120, 95, 60) }), + F({ id = "Lin", name = "Линь", rarity = "Uncommon", price = 20, xp = 22, minW = 0.4, maxW = 2.5, size = 1.1, shape = "classic", color = Color3.fromRGB(95, 125, 55), color2 = Color3.fromRGB(60, 85, 35) }), + F({ id = "Shuka", name = "Щука", rarity = "Rare", price = 45, xp = 45, minW = 1.0, maxW = 8.0, size = 1.5, shape = "long", color = Color3.fromRGB(110, 140, 85), color2 = Color3.fromRGB(200, 210, 150), spots = 12 }), + F({ id = "Sudak", name = "Судак", rarity = "Rare", price = 50, xp = 48, minW = 1.0, maxW = 6.0, size = 1.4, shape = "long", color = Color3.fromRGB(165, 165, 135), color2 = Color3.fromRGB(80, 80, 70), stripes = 6, spikes = true }), + F({ id = "Som", name = "Сом", rarity = "Epic", price = 130, xp = 110, minW = 5.0, maxW = 40, size = 2.0, shape = "long", color = Color3.fromRGB(75, 75, 90), color2 = Color3.fromRGB(180, 175, 160), whiskers = true }), + F({ id = "Koi", name = "Карп кои", rarity = "Epic", price = 150, xp = 120, minW = 2.0, maxW = 9.0, size = 1.4, shape = "classic", color = Color3.fromRGB(250, 245, 240), color2 = Color3.fromRGB(240, 110, 40), spots = 7, whiskers = true }), + F({ id = "Gold", name = "Золотая рыбка", rarity = "Legendary", price = 500, xp = 350, minW = 0.1, maxW = 0.5, size = 0.9, shape = "classic", color = Color3.fromRGB(255, 195, 40), color2 = Color3.fromRGB(255, 120, 30), glow = true, bigTail = true }), + F({ id = "Crystal", name = "Хрустальный осётр", rarity = "Mythic", price = 2000, xp = 900, minW = 10, maxW = 60, size = 2.0, shape = "sturgeon", color = Color3.fromRGB(150, 230, 255), color2 = Color3.fromRGB(230, 250, 255), glow = true, glass = true }), + }, + }, + World2 = { + fish = { + F({ id = "Clown", name = "Рыба-клоун", rarity = "Common", price = 18, xp = 18, minW = 0.1, maxW = 0.4, size = 0.8, shape = "classic", color = Color3.fromRGB(255, 120, 30), color2 = Color3.fromRGB(255, 255, 255), stripes = 3 }), + F({ id = "Sergeant", name = "Рыба-сержант", rarity = "Common", price = 20, xp = 18, minW = 0.2, maxW = 0.9, size = 0.9, shape = "tall", color = Color3.fromRGB(240, 230, 110), color2 = Color3.fromRGB(40, 40, 45), stripes = 5 }), + F({ id = "Mullet", name = "Барабулька", rarity = "Common", price = 22, xp = 20, minW = 0.1, maxW = 0.6, size = 0.9, shape = "classic", color = Color3.fromRGB(235, 110, 100), color2 = Color3.fromRGB(255, 220, 120), whiskers = true }), + F({ id = "Angel", name = "Рыба-ангел", rarity = "Uncommon", price = 45, xp = 40, minW = 0.3, maxW = 1.5, size = 1.0, shape = "tall", color = Color3.fromRGB(60, 120, 230), color2 = Color3.fromRGB(255, 220, 40), stripes = 4, bigFins = true }), + F({ id = "Puffer", name = "Иглобрюх", rarity = "Uncommon", price = 50, xp = 42, minW = 0.3, maxW = 2.0, size = 1.0, shape = "puffer", color = Color3.fromRGB(230, 205, 140), color2 = Color3.fromRGB(110, 90, 60), spots = 10 }), + F({ id = "Parrot", name = "Рыба-попугай", rarity = "Uncommon", price = 55, xp = 45, minW = 1.0, maxW = 5.0, size = 1.2, shape = "classic", color = Color3.fromRGB(60, 210, 190), color2 = Color3.fromRGB(240, 90, 180), spots = 5 }), + F({ id = "Ray", name = "Скат", rarity = "Rare", price = 120, xp = 90, minW = 3.0, maxW = 25, size = 1.6, shape = "ray", color = Color3.fromRGB(110, 115, 140), color2 = Color3.fromRGB(230, 230, 240), spots = 14 }), + F({ id = "Barracuda", name = "Барракуда", rarity = "Rare", price = 130, xp = 95, minW = 2.0, maxW = 20, size = 1.7, shape = "long", color = Color3.fromRGB(175, 185, 200), color2 = Color3.fromRGB(60, 70, 85), stripes = 8 }), + F({ id = "Swordfish", name = "Рыба-меч", rarity = "Epic", price = 350, xp = 220, minW = 30, maxW = 200, size = 2.0, shape = "sword", color = Color3.fromRGB(55, 75, 130), color2 = Color3.fromRGB(200, 210, 230) }), + F({ id = "Moray", name = "Мурена", rarity = "Epic", price = 320, xp = 210, minW = 2.0, maxW = 15, size = 1.8, shape = "eel", color = Color3.fromRGB(80, 140, 60), color2 = Color3.fromRGB(230, 220, 90), spots = 12 }), + F({ id = "Shark", name = "Рифовая акула", rarity = "Legendary", price = 1200, xp = 700, minW = 40, maxW = 180, size = 2.4, shape = "shark", color = Color3.fromRGB(110, 125, 145), color2 = Color3.fromRGB(235, 235, 240) }), + F({ id = "SunJelly", name = "Солнечная медуза", rarity = "Mythic", price = 5000, xp = 2000, minW = 1.0, maxW = 8.0, size = 1.8, shape = "jelly", color = Color3.fromRGB(255, 200, 80), color2 = Color3.fromRGB(255, 120, 200), glow = true, glass = true }), + }, + }, + World3 = { + fish = { + F({ id = "Cod", name = "Треска", rarity = "Common", price = 55, xp = 40, minW = 1.0, maxW = 10, size = 1.2, shape = "classic", color = Color3.fromRGB(150, 150, 110), color2 = Color3.fromRGB(230, 225, 200), spots = 14, whiskers = true }), + F({ id = "Herring", name = "Сельдь", rarity = "Common", price = 50, xp = 38, minW = 0.2, maxW = 0.8, size = 0.9, shape = "long", color = Color3.fromRGB(150, 175, 205), color2 = Color3.fromRGB(70, 100, 140) }), + F({ id = "Capelin", name = "Мойва", rarity = "Common", price = 48, xp = 36, minW = 0.05, maxW = 0.2, size = 0.7, shape = "classic", color = Color3.fromRGB(170, 200, 190), color2 = Color3.fromRGB(80, 120, 110) }), + F({ id = "Flounder", name = "Камбала", rarity = "Uncommon", price = 140, xp = 90, minW = 0.5, maxW = 4.0, size = 1.2, shape = "flat", color = Color3.fromRGB(150, 125, 90), color2 = Color3.fromRGB(230, 120, 60), spots = 10 }), + F({ id = "Redfish", name = "Морской окунь", rarity = "Uncommon", price = 150, xp = 92, minW = 0.5, maxW = 5.0, size = 1.1, shape = "classic", color = Color3.fromRGB(225, 70, 60), color2 = Color3.fromRGB(255, 160, 120), spikes = true }), + F({ id = "Char", name = "Арктический голец", rarity = "Uncommon", price = 160, xp = 95, minW = 0.5, maxW = 6.0, size = 1.2, shape = "long", color = Color3.fromRGB(120, 130, 150), color2 = Color3.fromRGB(255, 130, 150), spots = 12 }), + F({ id = "Halibut", name = "Палтус", rarity = "Rare", price = 380, xp = 200, minW = 5.0, maxW = 90, size = 1.9, shape = "flat", color = Color3.fromRGB(90, 95, 80), color2 = Color3.fromRGB(150, 150, 130), spots = 16 }), + F({ id = "Wolffish", name = "Морской волк", rarity = "Rare", price = 400, xp = 210, minW = 3.0, maxW = 20, size = 1.7, shape = "long", color = Color3.fromRGB(110, 120, 140), color2 = Color3.fromRGB(60, 65, 80), stripes = 7, teeth = true }), + F({ id = "Angler", name = "Удильщик", rarity = "Epic", price = 1100, xp = 500, minW = 5.0, maxW = 50, size = 1.6, shape = "angler", color = Color3.fromRGB(60, 50, 70), color2 = Color3.fromRGB(120, 255, 230), glow = true }), + F({ id = "IceEel", name = "Ледяная мурена", rarity = "Epic", price = 1000, xp = 480, minW = 3.0, maxW = 25, size = 1.9, shape = "eel", color = Color3.fromRGB(150, 210, 245), color2 = Color3.fromRGB(240, 250, 255), glass = true }), + F({ id = "Greenland", name = "Полярная акула", rarity = "Legendary", price = 3500, xp = 1500, minW = 200, maxW = 900, size = 2.6, shape = "shark", color = Color3.fromRGB(80, 90, 100), color2 = Color3.fromRGB(160, 170, 180) }), + F({ id = "Leviathan", name = "Ледяной левиафан", rarity = "Mythic", price = 15000, xp = 4000, minW = 500, maxW = 3000, size = 2.4, shape = "eel", color = Color3.fromRGB(110, 230, 255), color2 = Color3.fromRGB(200, 120, 255), glow = true, spikes = true }), + }, + }, +} + +---------------------------------------------------------------- удочки +-- luck = бонус удачи, speed = множитель ожидания клёва (меньше = быстрее), zone = ширина зелёной зоны, +-- icon = картинка удочки в хотбаре (Tool.TextureId) +Config.Rods = { + { id = "Basic", name = "Старая удочка", price = 0, level = 1, luck = 0.00, speed = 1.00, zone = 0.22, upgradeCost = 40, style = "wood", icon = "rbxassetid://83350883185349" }, + { id = "Bamboo", name = "Бамбуковая удочка", price = 150, level = 3, luck = 0.15, speed = 0.88, zone = 0.25, upgradeCost = 120, style = "bamboo", icon = "rbxassetid://98615001898640" }, + { id = "Fiberglass", name = "Стеклопластиковая", price = 600, level = 5, luck = 0.30, speed = 0.78, zone = 0.27, upgradeCost = 300, style = "glass", icon = "rbxassetid://100031752289540" }, + { id = "Carbon", name = "Карбоновая удочка", price = 1800, level = 8, luck = 0.55, speed = 0.68, zone = 0.29, upgradeCost = 700, style = "carbon", icon = "rbxassetid://71788597596034" }, + { id = "Coral", name = "Коралловая удочка", price = 4500, level = 10, luck = 0.80, speed = 0.62, zone = 0.31, upgradeCost = 1300, style = "coral", icon = "rbxassetid://139114393074237" }, + { id = "Golden", name = "Золотая удочка", price = 9000, level = 13, luck = 1.00, speed = 0.56, zone = 0.33, upgradeCost = 2200, style = "gold", icon = "rbxassetid://83212298735071" }, + { id = "Frost", name = "Ледяная удочка", price = 25000, level = 18, luck = 1.40, speed = 0.50, zone = 0.35, upgradeCost = 5000, style = "frost", icon = "rbxassetid://134579643216329" }, + { id = "Legend", name = "Удочка Легенды", price = 75000, level = 25, luck = 2.00, speed = 0.42, zone = 0.38, upgradeCost = 12000, style = "legend", icon = "rbxassetid://84863811378769" }, +} + +Config.RodUpgrade = { maxLevel = 5, luckPerLevel = 0.08, zonePerLevel = 0.012, speedPerLevel = 0.96 } +function Config.UpgradeCost(rod, currentLevel) + return math.floor(rod.upgradeCost * (currentLevel + 1) ^ 1.5) +end + +---------------------------------------------------------------- сумки +Config.Bags = { + { id = "Pouch", name = "Холщовая сумка", price = 0, level = 1, capacity = 12, color = Color3.fromRGB(170, 140, 95) }, + { id = "Satchel", name = "Сумка рыбака", price = 150, level = 2, capacity = 25, color = Color3.fromRGB(110, 140, 80) }, + { id = "Backpack", name = "Туристический рюкзак", price = 700, level = 4, capacity = 45, color = Color3.fromRGB(60, 110, 180) }, + { id = "BigNet", name = "Огромный садок", price = 2500, level = 7, capacity = 80, color = Color3.fromRGB(200, 80, 50) }, + { id = "Chest", name = "Сундук за спиной", price = 9000, level = 12, capacity = 140, color = Color3.fromRGB(140, 90, 50) }, + { id = "Magic", name = "Магический мешок", price = 30000, level = 20, capacity = 250, color = Color3.fromRGB(120, 60, 200) }, +} + +---------------------------------------------------------------- удача +Config.LuckPerPlayerLevel = 0.02 -- +2% за уровень игрока +Config.MasteryLuck = 0.10 -- +10% навсегда за полностью собранный мир +Config.Potions = { + { id = "Luck1", name = "Зелье удачи", price = 120, bonus = 0.5, duration = 300, color = Color3.fromRGB(90, 230, 120) }, + { id = "Luck2", name = "Большое зелье удачи", price = 450, bonus = 1.0, duration = 600, color = Color3.fromRGB(255, 200, 60), level = 5 }, + { id = "Luck3", name = "Эликсир фортуны", price = 2500, bonus = 2.0, duration = 600, color = Color3.fromRGB(200, 120, 255), level = 12 }, +} + +---------------------------------------------------------------- коллекция +-- награда за то, что поймал ВСЕ виды одной редкости в мире (умножается на mult мира) +Config.CollectionRewards = { + Common = { coins = 50, xp = 40 }, + Uncommon = { coins = 120, xp = 100 }, + Rare = { coins = 300, xp = 250 }, + Epic = { coins = 800, xp = 600 }, + Legendary = { coins = 2000, xp = 1500 }, + Mythic = { coins = 6000, xp = 4000 }, +} +Config.MasteryCoins = 5000 -- за весь мир (тоже умножается на mult) + +---------------------------------------------------------------- цепочки заданий +-- короткие задания идут по очереди: награда сразу, следующее появляется мгновенно. +-- после последнего шага — бонус цепочки и следующая цепочка; каждый новый круг цели растут +-- coins/xp = награда за 1 единицу цели (умножается на цель и уровень игрока); +-- max — потолок цели, byLevel — цель растёт с уровнем игрока; +-- forms — слово после числа для 1 / 2–4 / 5+ (подставляется вместо второго %s) +local FISH, TIMES = { "рыбу", "рыбы", "рыб" }, { "раз", "раза", "раз" } +Config.QuestKinds = { + catch = { text = "Поймай %d %s", forms = FISH, coins = 5, xp = 4 }, + uncommon = { text = "Поймай %d %s «Необычная» или реже", forms = FISH, coins = 18, xp = 14 }, + rare = { text = "Поймай %d %s «Редкая» или реже", forms = FISH, coins = 60, xp = 50 }, + perfect = { text = "Подсеки %d %s без промаха", forms = TIMES, coins = 10, xp = 8 }, + perfectCast = { text = "Забрось в зелёную зону %d %s", forms = TIMES, coins = 8, xp = 6 }, + combo = { text = "Набери серию из %d рыб", coins = 12, xp = 10, max = 15 }, + sell = { text = "Продай %d %s", forms = FISH, coins = 3, xp = 3 }, + earn = { text = "Заработай %d ⚪ на продаже", coins = 0.25, xp = 0.2, byLevel = true }, + buy = { text = "Купи что-нибудь в магазине", coins = 40, xp = 30, max = 1 }, + boss = { text = "Нанеси боссу %d урона", coins = 15, xp = 12 }, +} +Config.QuestChains = { + { name = "🎣 Утренний клёв", steps = { { "catch", 3 }, { "perfectCast", 2 }, { "sell", 3 }, { "catch", 5 }, { "uncommon", 1 } } }, + { name = "🔥 Без промаха", steps = { { "perfect", 3 }, { "combo", 3 }, { "catch", 6 }, { "earn", 80 }, { "combo", 5 } } }, + { name = "💎 Охота за редкостью", steps = { { "uncommon", 3 }, { "perfectCast", 3 }, { "rare", 1 }, { "sell", 8 }, { "buy", 1 } } }, + { name = "🏆 Мастер озера", steps = { { "combo", 6 }, { "catch", 10 }, { "perfect", 6 }, { "rare", 2 }, { "earn", 300 } } }, +} +Config.QuestTierGrowth = 0.5 -- каждый следующий круг цепочек: цели ×(1 + 0.5 · номер круга) +Config.ChainBonus = { coins = 120, xp = 100, potion = "Luck1" } -- за всю цепочку (растёт с уровнем и кругом) + +---------------------------------------------------------------- серия улова +-- каждая рыба подряд без срыва: +10% к цене и опыту следующей, до ×2; +-- срыв, ушедшая рыба или timeout секунд без улова — серия сгорает +Config.Combo = { step = 0.1, max = 2.0, timeout = 90 } + +---------------------------------------------------------------- босс озера +-- раз в interval секунд в мир, где больше всего игроков, приплывает босс. Его ловят всем сервером: +-- каждая пойманная там рыба наносит урон = ранг редкости (+1 за подсечку без промаха). +-- Если за duration секунд урона хватило — награда всем, кто помог (× mult мира, минимум 40% за малый вклад) +Config.Boss = { + firstDelay = 240, interval = 600, duration = 180, + hpPerPlayer = 12, + reward = { coins = 300, xp = 250, potion = "Luck1" }, + worlds = { + World1 = { name = "Сом-великан", fish = "Som", mutation = "Golden", scale = 5 }, + World2 = { name = "Королевская акула", fish = "Shark", mutation = "Golden", scale = 3 }, + World3 = { name = "Ледяной левиафан", fish = "Leviathan", mutation = "Rainbow", scale = 2.5 }, + }, +} + +-- ежедневная награда (7 дней по кругу), серебро растёт с уровнем +Config.DailyRewards = { + { coins = 100 }, + { coins = 200 }, + { coins = 300, potion = "Luck1" }, + { coins = 450 }, + { coins = 600, potion = "Luck1" }, + { coins = 800 }, + { coins = 1500, potion = "Luck2" }, +} + +---------------------------------------------------------------- события на сервере +Config.Events = { + { id = "Bite", name = "⚡ Клёвый час", desc = "Рыба клюёт в 2 раза быстрее", duration = 180, speed = 0.5 }, + { id = "Luck", name = "🍀 Удачный ветер", desc = "Удача +50% для всех", duration = 180, luck = 0.5 }, + { id = "Stars", name = "🌟 Звездопад", desc = "Мутации в 3 раза чаще", duration = 180, mutation = 3 }, + { id = "Fair", name = "🐟 Рыбная ярмарка", desc = "Рыба продаётся на 50% дороже", duration = 180, sell = 1.5 }, +} +Config.EventFirstDelay = 120 +Config.EventGapMin = 420 +Config.EventGapMax = 720 + +---------------------------------------------------------------- время суток +-- одни сутки длятся length секунд реального времени; время общее для всего сервера +Config.DayNight = { + enabled = true, + length = 1200, -- 20 минут на сутки + startClock = 9, -- во сколько начинается день при запуске сервера + nightLuck = 0.10, -- ночью удача +10% +} + +-- время на часах в момент serverTime (workspace:GetServerTimeNow()), dayStart — атрибут workspace "DayStart" +function Config.ClockAt(serverTime, dayStart) + local d = Config.DayNight + return (d.startClock + (serverTime - (dayStart or serverTime)) / d.length * 24) % 24 +end + +-- 0 днём, 1 глубокой ночью, плавно на рассвете и закате +function Config.Nightness(clock) + if clock >= 7 and clock <= 17.5 then + return 0 + elseif clock > 17.5 and clock < 20 then + return (clock - 17.5) / 2.5 + elseif clock >= 5 and clock < 7 then + return 1 - (clock - 5) / 2 + end + return 1 +end + +function Config.IsNight(clock) + return Config.Nightness(clock) >= 0.5 +end + +---------------------------------------------------------------- погода +-- меняется на всём сервере; weight — как часто выпадает, duration — сколько длится (секунды) +-- luck / speed / mutation — бонусы к рыбалке, пока погода держится +-- names — как погода называется в отдельных мирах (во фьорде вместо дождя снег) +Config.Weathers = { + { id = "Clear", name = "Ясно", icon = "☀", weight = 40, duration = { 240, 420 } }, + { id = "Cloudy", name = "Пасмурно", icon = "☁", weight = 25, duration = { 180, 360 }, luck = 0.05, desc = "Удача +5%" }, + { id = "Rain", name = "Дождь", icon = "🌧", weight = 20, duration = { 150, 300 }, speed = 0.85, desc = "Клюёт на 15% быстрее", + names = { World3 = "Снегопад" } }, + { id = "Storm", name = "Гроза", icon = "⛈", weight = 8, duration = { 120, 240 }, luck = 0.25, speed = 0.9, desc = "Удача +25%", + names = { World3 = "Метель" } }, + { id = "Fog", name = "Туман", icon = "🌫", weight = 7, duration = { 150, 300 }, mutation = 1.5, desc = "Мутации ×1.5" }, +} + +function Config.WeatherById(id) + for _, w in ipairs(Config.Weathers) do + if w.id == id then + return w + end + end + return Config.Weathers[1] +end + +---------------------------------------------------------------- звуки +-- ID из Creator Store: эффекты — Pro Sound Effects (официальная библиотека Roblox), +-- музыка — APM и DistroKid (лицензированы для Roblox). volume — громкость, pitch — разброс высоты +local function S(id, volume, extra) + local t = extra or {} + t.id = "rbxassetid://" .. id + t.volume = volume + return t +end +Config.Sounds = { + -- музыка + musicLobby = S(137023744071437, 0.35), -- The Ancient Lutes | Medieval Tavern Music + musicLobby2 = S(116079409060113, 0.35), -- The Lute Lament | Medieval Tavern Music + musicLake = S(1838853377, 0.3), -- Harp Fantasy + musicLake2 = S(86472274853159, 0.3), -- Calm Fantasy Atmosphere + musicNight = S(140195397978848, 0.3), -- Moonlit Meadow Whisper + -- окружение (петли) + birdsLake = S(9112877174, 0.35), -- Squam Lake 1 + birdsPark = S(9113444360, 0.25), -- Birds Park 2 + birdsJungle = S(9114892930, 0.3), -- Jungle Birds Ambience 3 + crickets = S(9112764573, 0.3), -- Crickets Night 3 + lakeWater = S(9116203162, 0.25), -- Lake Lap Water Movement 2 + wind = S(9113286782, 0.18), -- Barstow Wind Light Blustery Low Howl 1 + rainLight = S(9112852668, 0.45), -- Rain Continuous Drizzle 1 + rainHeavy = S(9112853287, 0.55), -- Rain Heavy 1 + fire = S(9112780193, 0.6, { roll = 30 }), -- Fireplace Constant Burning Flame 1 (слышно у костра) + thunder = { "rbxassetid://9116282875", "rbxassetid://9116282646", "rbxassetid://9116282791", "rbxassetid://9116282544" }, + -- рыбалка + cast = S(9120718279, 0.5, { pitch = { 0.9, 1.1 } }), -- Whoosh Fast Swish By 1 + bite = S(9112751536, 0.7, { pitch = { 0.9, 1.15 } }), -- Bubble Bloop High Pitched Cute 1 + reel = S(9114454019, 0.4), -- Fishing Reel 4 (петля, пока тянешь) + catchSplash = S(9119293555, 0.6), -- Small Splash Shallow Water + catch = S(9126073001, 0.5), -- Bell Tone Ding + fanfare = S(1836473422, 0.45), -- Victory Fanfare Sting (редкая рыба) + sparkle = S(9114369623, 0.5), -- Fairy Dust 1 (мутация) + escape = S(9117944976, 0.5), -- Puddle Splash 2 (сорвалась) + -- интерфейс + click = S(15675032796, 0.5), -- Roblox_UI_Small_Click + open = S(9117231552, 0.45), -- Paper Scroll Unroll Handle 4 + coins = S(9113849306, 0.6), -- Coins Or Keys Jingle 1 + chestHop = S(9120718279, 0.35, { pitch = { 0.7, 0.8 } }), -- Whoosh Fast Swish By 1 (сундук награды подпрыгивает) + chestLand = S(9113769181, 0.7, { pitch = { 0.95, 1.05 } }), -- Chair Drop 2: тяжёлый деревянный удар о землю + levelUp = S(1840525342, 0.5), -- Harp Glissando (A) + quest = S(9126073318, 0.5), -- Bell Tone Ding 2 +} +Config.DefaultVolume = { music = 0.6, sfx = 0.8 } + +---------------------------------------------------------------- донат (Robux) +-- Все товары — Developer Products игры (create.roblox.com → Monetization → Developer Products); +-- id — Product ID оттуда, robux — цена для кнопки (должна совпадать с ценой в Roblox). +-- Пропуска тоже Developer Products: покупаются один раз, сервер запоминает их в данных игрока навсегда. +-- Пока id = 0, кнопка покупки покажет подсказку, что товар не настроен. +Config.GamePasses = { + { key = "VIP", id = 3728143641, robux = 199, icon = "👑", name = "VIP", desc = "+25% удачи и серебра, корона над головой" }, + { key = "DoubleCoins", id = 3728143692, robux = 299, icon = "⚪", name = "x2 Серебро", desc = "Вся рыба продаётся в 2 раза дороже" }, + { key = "LuckyCharm", id = 3728143735, robux = 349, icon = "🍀", name = "Талисман удачи", desc = "+50% удачи навсегда" }, + { key = "BigBag", id = 3728143773, robux = 149, icon = "🎒", name = "Бездонная сумка", desc = "+100 мест в любой сумке" }, +} +Config.Products = { + { key = "Coins1", id = 3728142264, robux = 49, icon = "👝", name = "Кошель серебра", desc = "+1 000 серебра (больше с уровнем)", coins = 1000 }, + { key = "Coins2", id = 3728142848, robux = 199, icon = "⚪", name = "Сундук серебра", desc = "+5 000 серебра (больше с уровнем)", coins = 5000 }, + { key = "Coins3", id = 3728142885, robux = 599, icon = "🏆", name = "Гора золота", desc = "+20 000 серебра (больше с уровнем)", coins = 20000 }, + { key = "Luck", id = 3728142916, robux = 99, icon = "🧪", name = "Супер-зелье удачи", desc = "+200% удачи на 15 минут", boost = 2.0, duration = 900 }, +} + +---------------------------------------------------------------- рыбалка +Config.BiteTimeMin = 3 +Config.BiteTimeMax = 7 +Config.BiteTimeout = 12 +Config.MaxMisses = 2 +-- заброс: держишь ЛКМ — сила ездит 0 → 1 → 0 → …; от силы в момент отпускания зависит дальность +Config.CastChargeTime = 1.3 -- секунд на проход шкалы в одну сторону +Config.CastMinDist, Config.CastMaxDist = 6, 28 +Config.CastReach = 7 -- закидывать можно не дальше ~2 м (7 studs) от воды +Config.CastPerfect = { 0.72, 0.86 } -- зелёная зона шкалы +Config.CastPerfectLuck = 1.2 -- множитель удачи за попадание в зелёную зону + +-- обучение: линия-подсказка ведёт по шагам 0 → 1 → 2 → 3, на 4 обучение пройдено +-- 0 — табличка «Как играть», 1 — портал в Мир 1, 2 — причал (поймать рыбу), 3 — скупка (продать) +Config.TutorialDone = 4 +function Config.HitsNeeded(rank) + return math.ceil(rank / 2) +end +-- опыт до следующего уровня: до 8-го ≈ 3 600 (1,5–2 часа вместе с заказами гильдии); +-- у старых сохранений уровень не понижается — копится только опыт внутри уровня +function Config.XPForLevel(level) + return math.floor(50 * level ^ 1.6) +end + +---------------------------------------------------------------- гильдия рыбаков +-- три валюты: серебро (coins в данных), жемчуг (pearls), печати гильдии (seals — копятся для ранга) +Config.Pearls = { + mutation = { Shiny = 1, Golden = 3, Rainbow = 10 }, -- за пойманную рыбу с мутацией + boss = 5, -- за победу над боссом + daily7 = 5, -- 7-й день ежедневной награды + rankUp = 10, -- за новый ранг +} + +-- ранги: seals — сколько печатей нужно накопить, trial — испытание у Старейшины, +-- orders — заказов на доске, traps — ловушек, discount — скидка у торговцев +-- trial.kind: deliver (сдать рыбу из сумки), catch (поймать с условием), bossWin (участие в победе над боссом), +-- dex (собрать коллекцию мира) +Config.Guild = { + elder = "Старейшина Ворон", + ranks = { + { id = "F", name = "Ученик", seals = 0, orders = 3, color = Color3.fromRGB(150, 150, 150), + unlocks = "Мир 1, доска заказов" }, + { id = "E", name = "Подмастерье", seals = 30, orders = 4, color = Color3.fromRGB(90, 190, 90), auto = true, + trial = { kind = "deliver", fish = "Okun", count = 5, text = "Сдать 5 окуней" }, + unlocks = "🎣 Автоловля, 4-й заказ на доске" }, + { id = "D", name = "Рыбак", seals = 120, orders = 4, color = Color3.fromRGB(70, 130, 230), auto = true, traps = 1, + trial = { kind = "catch", minRank = 3, weathers = { Rain = true, Storm = true }, count = 1, text = "Поймать «Редкую» рыбу в дождь или грозу" }, + unlocks = "🏝 Мир 2 (и ур. 8), 🧺 ловушка" }, + { id = "C", name = "Опытный рыбак", seals = 350, orders = 4, color = Color3.fromRGB(150, 80, 200), auto = true, traps = 2, discount = 0.05, + trial = { kind = "bossWin", count = 1, text = "Помочь одолеть босса озера" }, + unlocks = "🧺 2 ловушки, скидка у торговцев 5%" }, + { id = "B", name = "Мастер", seals = 900, orders = 4, color = Color3.fromRGB(200, 50, 45), auto = true, traps = 3, discount = 0.05, + trial = { kind = "dex", world = "World1", text = "Собрать всю коллекцию «Тихого озера»" }, + unlocks = "❄ Мир 3 (и ур. 18), 🧺 3 ловушки" }, + { id = "A", name = "Магистр", seals = 2000, orders = 4, color = Color3.fromRGB(230, 180, 60), auto = true, traps = 3, discount = 0.10, + trial = { kind = "catch", minRank = 4, night = true, count = 1, text = "Поймать «Эпическую» рыбу ночью" }, + unlocks = "Титул «Магистр», скидка 10%" }, + { id = "S", name = "Легенда", seals = 4500, orders = 4, color = Color3.fromRGB(255, 120, 200), auto = true, traps = 3, discount = 0.10, autoNoCap = true, + trial = { kind = "catch", minRank = 6, count = 1, text = "Поймать «Мифическую» рыбу" }, + unlocks = "Золотой жетон, автоловля без ограничения редкости" }, + }, + -- миры требуют и уровень, и ранг (номер в списке ranks) + worldRank = { World2 = 3, World3 = 5 }, + elderDistance = 22, -- взять испытание / сдать рыбу — рядом со Старейшиной или доской +} + +-- заказы гильдии: личные, обновляются каждые period секунд (окно floor(os.time()/period)), +-- один заказ можно перебросить за rerollPearls жемчуга. Награда растёт с рангом +Config.Orders = { + period = 10800, + rerollPearls = 2, + pearlChance = 0.2, pearlsMin = 1, pearlsMax = 3, + coinsPerSeal = 12, -- серебро за заказ = печати × это × (1 + 0.5 · (ранг − 1)) + -- weight — как часто выпадает; seals — печати {мин, макс} + kinds = { + deliver = { weight = 3, seals = { 5, 12 } }, + heavy = { weight = 2, seals = { 8, 16 } }, + weather = { weight = 1, seals = { 10, 20 } }, + night = { weight = 1, seals = { 10, 22 } }, + combo = { weight = 2, seals = { 8, 18 } }, + perfect = { weight = 2, seals = { 6, 14 } }, + }, +} + +-- наживка: 1 слот, 1 штука тратится на заброс. price — за пачку из pack штук; currency = "pearls" — за жемчуг +Config.Baits = { + { id = "Worm", name = "Червь", icon = "🐛", price = 40, pack = 10, speed = 0.9, desc = "Клюёт на 10% быстрее" }, + { id = "Larva", name = "Мотыль", icon = "🦐", price = 90, pack = 10, luck = 0.15, desc = "Удача +15%" }, + { id = "Firefly", name = "Светлячок", icon = "✨", price = 120, pack = 10, nightLuck = 0.30, desc = "Ночью удача +30% (вместо +10%)" }, + { id = "Blood", name = "Кровавая приманка", icon = "🩸", price = 400, pack = 10, rareWeight = 1.5, rank = 3, desc = "Редкие и выше попадаются в 1,5 раза чаще" }, + { id = "Pearl", name = "Жемчужная блесна", icon = "🦪", price = 5, pack = 5, mutation = 2, currency = "pearls", desc = "Шанс мутаций ×2" }, +} + +-- автоловля (с ранга E): сервер сам забрасывает и вытаскивает, но со штрафами +Config.AutoFish = { + luck = 0.6, -- удача ×0.6 + maxRarity = 3, -- не выше «Редкой» (ранг S снимает) + slower = 1.5, -- каждая поимка на 50% дольше + reel = 2.5, -- секунд «вываживания» вместо мини-игры +} + +-- ловушки-вентери (с ранга D): 1 рыба Мира 1 каждые every секунд, не больше max, копятся и офлайн +Config.Traps = { + every = 900, max = 16, + world = "World1", rarities = { Common = 3, Uncommon = 1 }, -- вес редкостей +} + +-- отдых: пока игрока нет, копится двойной опыт — 1 минута за каждые perOffline минут офлайн, не больше max +Config.Rest = { perOffline = 4, max = 3600, mult = 2 } + +function Config.RankById(id) + for i, r in ipairs(Config.Guild.ranks) do + if r.id == id then + return r, i + end + end + return nil +end + +---------------------------------------------------------------- помощники +function Config.Find(list, id) + for _, item in ipairs(list) do + if item.id == id or item.key == id then + return item + end + end + return nil +end + +function Config.FindFish(fishId) + for zoneId, zone in pairs(Config.Zones) do + for _, f in ipairs(zone.fish) do + if f.id == fishId then + return f, zoneId + end + end + end + return nil +end + +function Config.RodStats(rodId, upgradeLevel) + local rod = Config.Find(Config.Rods, rodId) or Config.Rods[1] + local u = Config.RodUpgrade + upgradeLevel = upgradeLevel or 0 + return { + luck = rod.luck + u.luckPerLevel * upgradeLevel, + speed = rod.speed * (u.speedPerLevel ^ upgradeLevel), + zone = rod.zone + u.zonePerLevel * upgradeLevel, + } +end + +return Config diff --git a/tools/economy_model.py b/tools/economy_model.py new file mode 100644 index 0000000..53fb8d3 --- /dev/null +++ b/tools/economy_model.py @@ -0,0 +1,463 @@ +"""Модель баланса экономики v2 (только чтение конфига, игру не меняет). Стандартная библиотека Python. + +Запуск из любой папки: py -3 tools/economy_model.py +Читает src/ReplicatedStorage/FishConfig.lua (текущий баланс) и tools/baseline/FishConfig_v1.lua (баланс +до v2), пишет docs/economy-balance.md (таблицы) и docs/economy-model-results.json (все числа). + +Это МАТЕМАТИЧЕСКАЯ модель ожиданий, а не замер игроков: + * темп — «успешных ручных поимок за минуту эффективной игры» (с продажей и переходами, без AFK); + его нужно измерить телеметрией (CareerXP / LevelUp / economy events) и подставить сюда; + * доход рыбы — точное ожидание по формулам сервера (rollFish), без случайных хвостов; + * задания, босс, заказы, ежедневка — средние оценки по допущениям ниже (ASSUMPTIONS); + * покупки — жадный маршрут: следующая удочка, когда позволяет уровень и серебро; сумки и улучшения — + когда на них хватает без задержки ближайшей удочки. +""" +import json +import math +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CUR = (ROOT / 'src/ReplicatedStorage/FishConfig.lua').read_text(encoding='utf-8-sig') +OLD = (ROOT / 'tools/baseline/FishConfig_v1.lua').read_text(encoding='utf-8-sig') + +RAR = ['Common', 'Uncommon', 'Rare', 'Epic', 'Legendary', 'Mythic'] +WORLDS = ['World1', 'World2', 'World3'] + +ASSUMPTIONS = { + 'fail_rate': 0.12, # доля сорвавшихся поклёвок (серия сгорает) + 'perfect_cast_share': 0.45, # доля забросов в зелёную зону (удача x1.2) + 'night_share': 0.35, # доля ночи (удача +10%) + 'weather_luck': 0.05 * 0.25 + 0.25 * 0.08, # пасмурно 25% времени +5%, гроза 8% +25% + 'event_share_each': 180 / (180 + 570) / 4, # каждое из 4 событий ~6% времени + 'boss_win_rate': 0.7, 'boss_share': 0.8, # победа над боссом и доля участия + 'orders_per_hour': 1.5, # заказов гильдии за час игры (3-4 заказа в окне 3 ч) + 'order_seals_avg': 13, + 'daily_session_min': 90, # ежедневка делится на столько минут игры в день + 'consumables_per_min': {'World1': 2, 'World2': 6, 'World3': 12}, # обычные траты: наживка, иногда зелье + 'quest_rates': {'perfect': 0.6, 'perfectCast': 0.45, 'buy_min': 2.0, 'boss_min': 6.0}, +} + + +def num(pattern, text, cast=float, default=None): + m = re.search(pattern, text, re.S) + return cast(m.group(1)) if m else default + + +def block(text, head): + i = text.index(head) + depth, j = 0, text.index('{', i) + for k in range(j, len(text)): + if text[k] == '{': + depth += 1 + elif text[k] == '}': + depth -= 1 + if depth == 0: + return text[j:k + 1] + raise ValueError(head) + + +def parse(text, legacy=False): + c = {} + zones = block(text, 'Config.Zones = {') + if legacy: + rows = re.findall(r'id = "(\w+)",\s*name = "[^"]*",\s*rarity = "(\w+)",\s*price = (\d+),\s*xp = (\d+)', zones) + c['fish'] = [dict(id=a, rarity=b, price=int(p), xp=int(x)) for a, b, p, x in rows] + else: + rows = re.findall(r'id = "(\w+)",\s*name = "[^"]*",\s*rarity = "(\w+)",\s*price = (\d+)', zones) + c['fish'] = [dict(id=a, rarity=b, price=int(p)) for a, b, p in rows] + assert len(c['fish']) == 36, len(c['fish']) + rods = re.findall(r'\{ id = "(\w+)",\s*name = "[^"]*",\s*price = (\d+),\s*level = (\d+),\s*luck = ([\d.]+),\s*speed = ([\d.]+),\s*zone = ([\d.]+),\s*upgradeCost = (\d+)', block(text, 'Config.Rods = {')) + c['rods'] = [dict(id=a, price=int(p), level=int(l), luck=float(lu), speed=float(s), upgradeCost=int(u)) for a, p, l, lu, s, z, u in rods] + bags = re.findall(r'\{ id = "(\w+)",\s*name = "[^"]*",\s*price = (\d+),\s*level = (\d+),\s*capacity = (\d+)', block(text, 'Config.Bags = {')) + c['bags'] = [dict(id=a, price=int(p), level=int(l), capacity=int(cap)) for a, p, l, cap in bags] + up = block(text, 'Config.RodUpgrade = {') + c['up'] = dict(max=num(r'maxLevel = (\d+)', up, int), luck=num(r'luckPerLevel = ([\d.]+)', up), speed=num(r'speedPerLevel = ([\d.]+)', up)) + c['luck_per_level'] = num(r'Config.LuckPerPlayerLevel = ([\d.]+)', text) + rr = block(text, 'Config.Rarities = {') + c['weights'] = {r: float(re.search(r + r'\s*= \{[^}]*weight = ([\d.]+)', rr).group(1)) for r in RAR} + c['mutations'] = [(float(ch), int(m)) for ch, m in re.findall(r'chance = ([\d.]+), mult = (\d+)', block(text, 'Config.Mutations = {'))] + cb = re.search(r'Config.Combo = \{ step = ([\d.]+), max = ([\d.]+)', text) + c['combo'] = (float(cb.group(1)), float(cb.group(2))) + qk = block(text, 'Config.QuestKinds = {') + c['quest_kinds'] = {} + for name, body in re.findall(r'(\w+)\s*= \{ (text = [^}]*)\}', qk): + c['quest_kinds'][name] = dict(coins=float(re.search(r'coins = ([\d.]+)', body).group(1)), + xp=float(num(r'xp = ([\d.]+)', body, float, 0)), + max=num(r'max = (\d+)', body, int), byLevel='byLevel' in body) + c['chains'] = [re.findall(r'\{ "(\w+)", (\d+) \}', line) for line in re.findall(r'steps = \{(.*?)\} \}', block(text, 'Config.QuestChains = {'))] + c['tier_growth'] = num(r'Config.QuestTierGrowth = ([\d.]+)', text) + c['chain_coins'] = num(r'Config.ChainBonus = \{ coins = (\d+)', text) + c['chain_xp'] = num(r'Config.ChainBonus = \{[^}]*xp = (\d+)', text, float, 0) + c['quest_min'] = num(r'Config.QuestMinCoins = (\d+)', text, float, 10) + boss = block(text, 'Config.Boss = {') + c['boss'] = dict(coins=num(r'reward = \{ coins = (\d+)', boss), xp=num(r'reward = \{[^}]*xp = (\d+)', boss, float, 0), + cycle=num(r'interval = (\d+)', boss) + num(r'duration = (\d+)', boss)) + c['daily'] = [int(x) for x in re.findall(r'coins = (\d+)', block(text, 'Config.DailyRewards = {'))] + c['coins_per_seal'] = num(r'coinsPerSeal = (\d+)', text) + c['bite'] = (num(r'Config.BiteTimeMin = ([\d.]+)', text), num(r'Config.BiteTimeMax = ([\d.]+)', text)) + events = block(text, 'Config.Events = {') + c['fair'] = num(r'id = "Fair".*?sell = ([\d.]+)', events) + if not legacy: + e = block(text, 'Config.Economy = {') + c['career'] = {w: int(x) for w, x in re.findall(r'(World\d) = (\d+)', block(e, 'careerXP = {'))} + c['rarity_luck'] = {r: float(x) for r, x in re.findall(r'(\w+) = ([\d.]+)', block(e, 'rarityLuck = {'))} + for key in ['luckCap', 'mutationLuck', 'mutationCap', 'waitFloor', 'minBite', 'reelPerHit', 'valueBonusCap', 'restSilver', 'autoValue', 'autoMinCycle']: + c[key] = num(key + r' = ([\d.]+)', e) + c['level_xp'] = [int(x) for x in re.findall(r'\d+', re.sub(r'--[^\n]*', '', block(text, 'Config.LevelXP = {')))] + after = block(text, 'Config.LevelXPAfter = {') + c['level_after'] = dict(per=num(r'perMinute = (\d+)', after), minutes=num(r'minutes = (\d+)', after), step=num(r'step = (\d+)', after)) + c['potions'] = re.findall(r'id = "(\w+)",\s*name = "[^"]*",\s*icon = "[^"]*",\s*price = (\d+), level = (\d+), charges = (\d+)', block(text, 'Config.Potions = {')) + c['tier'] = {w: int(x) for w, x in re.findall(r'id = "(World\d)",[^\n]*tier = (\d+)', text)} + m = block(text, 'Config.Market = {') + c['market'] = dict(fee=num(r'fee = ([\d.]+)', m), minLevel=num(r'minLevel = (\d+)', m, int), minPrice=num(r'minPriceMult = ([\d.]+)', m)) + return c + + +NEW, BASE = parse(CUR), parse(OLD, legacy=True) + + +# ---------------------------------------------------------------- улов: ожидания (как rollFish на сервере) + +def eff_luck(c, luck): + b = luck - 1 + if b <= 0: + return max(-0.8, b) + return c['luckCap'] * (1 - math.exp(-b / c['luckCap'])) + + +def fish_dist(c, world, luck, legacy=False, max_rank=None): + rows = c['fish'][WORLDS.index(world) * 12:(WORLDS.index(world) + 1) * 12] + ws = [] + for f in rows: + rank = RAR.index(f['rarity']) + 1 + base = c['weights'][f['rarity']] + if legacy: + w = base / max(1, luck) if rank == 1 else base * max(0.2, 1 + (luck - 1) * (rank - 1)) + else: + be = eff_luck(c, luck) + k = c['rarity_luck'][f['rarity']] + w = base / max(0.2, 1 + be * k) if rank == 1 else base * max(0.2, 1 + be * k) + if max_rank and rank > max_rank: + w = 0 + ws.append(w) + t = sum(ws) + return [(f, w / t) for f, w in zip(rows, ws)] + + +def mutation_value(c, luck, legacy=False, other=1.0): + if legacy: + mm = luck * other + else: + be = eff_luck(c, luck) + mm = min(c['mutationCap'], max(0.2, 1 + be * c['mutationLuck']) * other) + rem, vm, p_any = 1.0, 0.0, 0.0 + for ch, mult in c['mutations']: + p = rem * min(1, ch * mm) + vm += p * mult + p_any += p + rem -= p + return vm + rem, p_any + + +WEIGHT_FACTOR = 0.75 + 0.9 / 3.2 # E[0.75 + 0.9 u^2.2] + + +def fish_ev(c, world, luck, legacy=False, max_rank=None): + d = fish_dist(c, world, luck, legacy, max_rank) + vm, p_mut = mutation_value(c, luck, legacy) + value = sum(p * f['price'] for f, p in d) * WEIGHT_FACTOR * vm + xp = sum(p * f.get('xp', 0) for f, p in d) * (1 + p_mut) if legacy else 0 + p_rank = {r: sum(p for f, p in d if RAR.index(f['rarity']) >= RAR.index(r)) for r in RAR} + return value, xp, p_rank + + +def blended_ev(c, world, luck, legacy=False): + s = ASSUMPTIONS['perfect_cast_share'] + a = fish_ev(c, world, luck, legacy) + b = fish_ev(c, world, luck * 1.2, legacy) + return a[0] * (1 - s) + b[0] * s, a[1] * (1 - s) + b[1] * s, {k: a[2][k] * (1 - s) + b[2][k] * s for k in a[2]} + + +def combo_bonus(c, legacy=False): + """E[надбавка серии]: серия до поимки ~ геометрическая (срыв с вероятностью fail_rate)""" + p = ASSUMPTIONS['fail_rate'] + step, cap = c['combo'] + e = 0.0 + for k in range(0, 200): + pk = (1 - p) ** k * p + e += pk * (min(cap, 1 + step * k) - 1 if legacy else min(cap, step * k)) + return e + + +# ---------------------------------------------------------------- прочие источники серебра + +def quest_income(c, world, catches, ev, p_rank, tier, legacy=False, level=1): + """серебро (и опыт для старой версии) в минуту от цепочек заданий: шаги идут по очереди""" + q = ASSUMPTIONS['quest_rates'] + coins_total = xp_total = minutes = 0.0 + for tier_round in range(2): + for chain in c['chains']: + for kind, base in chain: + k = c['quest_kinds'][kind] + goal = int(base) * (1 + c['tier_growth'] * tier_round) + if k['byLevel']: + goal *= (1 + (level - 1) * 0.25) if legacy else tier + goal = math.ceil(goal) + if k['max']: + goal = min(goal, k['max']) + rate = {'catch': catches, 'sell': catches, 'uncommon': catches * p_rank['Uncommon'], 'rare': catches * p_rank['Rare'], + 'perfect': catches * q['perfect'], 'perfectCast': catches * q['perfectCast'], 'earn': catches * ev}.get(kind) + if kind == 'combo': + t = goal / catches / ((1 - ASSUMPTIONS['fail_rate']) ** goal) + elif kind == 'buy': + t = q['buy_min'] + elif kind == 'boss': + t = q['boss_min'] + else: + t = goal / rate + m = (1 + (level - 1) * 0.25) if legacy else tier + minimum = 10 if legacy else c['quest_min'] * tier + coins_total += max(minimum, math.floor(k['coins'] * goal * m)) + xp_total += max(10, math.floor(k['xp'] * goal * m)) if legacy else 0 + minutes += t + bm = ((1 + (level - 1) * 0.25) if legacy else tier) * (1 + c['tier_growth'] * tier_round) + coins_total += c['chain_coins'] * bm + xp_total += c['chain_xp'] * bm if legacy else 0 + return coins_total / minutes, xp_total / minutes + + +def other_income(c, world, tier, legacy=False, level=1, world_mult=1): + a = ASSUMPTIONS + if legacy: + boss = c['boss']['coins'] * world_mult * a['boss_share'] * (1 + (level - 1) * 0.25) * a['boss_win_rate'] / (c['boss']['cycle'] / 60) + order = a['order_seals_avg'] * c['coins_per_seal'] * (1 + 0.5 * min(6, level // 4)) * a['orders_per_hour'] / 60 + daily = sum(c['daily']) / len(c['daily']) * (1 + (level - 1) * 0.2) / a['daily_session_min'] + boss_xp = c['boss']['xp'] * world_mult * a['boss_share'] * a['boss_win_rate'] / (c['boss']['cycle'] / 60) + return dict(boss=boss, orders=order, daily=daily), boss_xp + boss = c['boss']['coins'] * tier * a['boss_share'] * a['boss_win_rate'] / (c['boss']['cycle'] / 60) + order = a['order_seals_avg'] * c['coins_per_seal'] * tier * a['orders_per_hour'] / 60 + daily = sum(c['daily']) / len(c['daily']) * tier / a['daily_session_min'] + return dict(boss=boss, orders=order, daily=daily), 0 + + +def ambient_luck(): + return ASSUMPTIONS['night_share'] * 0.10 + ASSUMPTIONS['weather_luck'] + ASSUMPTIONS['event_share_each'] * 0.5 + + +# ---------------------------------------------------------------- уровни + +def xp_for(c, level, legacy=False): + if legacy: + return math.floor(50 * level ** 1.6) + if level <= len(c['level_xp']): + return c['level_xp'][level - 1] + a = c['level_after'] + return a['per'] * (a['minutes'] + a['step'] * (level - len(c['level_xp']))) + + +def world_for(level): + return 'World3' if level >= 18 else 'World2' if level >= 8 else 'World1' + + +def level_minutes(c, catches, upto): + t = 0.0 + out = {} + for lvl in range(1, upto): + t += xp_for(c, lvl) / (catches * c['career'][world_for(lvl)]) + out[lvl + 1] = round(t, 1) + return out + + +# ---------------------------------------------------------------- поминутная симуляция покупок + +def simulate(c, catches, minutes=1500, paid=False, legacy=False): + st = dict(level=1, xp=0.0, coins=0.0, rod=0, rodlv={}, bag=0, t=0) + events, income_by_world = [], {w: [] for w in WORLDS} + rods, bags = c['rods'], c['bags'] + combo = combo_bonus(c, legacy) + fair = 1 + ASSUMPTIONS['event_share_each'] * (c['fair'] - 1) + for minute in range(1, minutes + 1): + world = world_for(st['level']) + tier = c['tier'][world] if not legacy else 1 + rod = rods[st['rod']] + up = st['rodlv'].get(st['rod'], 0) + luck = 1 + rod['luck'] + up * c['up']['luck'] + (st['level'] - 1) * c['luck_per_level'] + ambient_luck() + (0.75 if paid else 0) + ev, xp_catch, p_rank = blended_ev(c, world, luck, legacy) + sale = fair * ((1.25 * 2) if paid else 1) + if legacy: + fish = catches * ev * (1 + combo) * sale + else: + fish = catches * ev * (1 + min(c['valueBonusCap'], combo)) * sale + q_coins, q_xp = quest_income(c, world, catches, ev, p_rank, tier, legacy, st['level']) + other, boss_xp = other_income(c, world, tier, legacy, st['level'], {'World1': 1, 'World2': 4, 'World3': 12}[world]) + cons = 0 if legacy else ASSUMPTIONS['consumables_per_min'][world] + gain = fish + q_coins + sum(other.values()) - cons + income_by_world[world].append(dict(fish=fish, quests=q_coins, cons=cons, **other)) + st['coins'] += gain + if legacy: + st['xp'] += catches * xp_catch * (1 + combo) + q_xp + boss_xp + else: + st['xp'] += catches * c['career'][world] + while st['xp'] >= xp_for(c, st['level'], legacy): + st['xp'] -= xp_for(c, st['level'], legacy) + st['level'] += 1 + events.append((minute, 'level', st['level'])) + # покупки: следующая удочка → сумка → улучшение + bought = True + while bought: + bought = False + nxt = st['rod'] + 1 + if nxt < len(rods) and st['level'] >= rods[nxt]['level'] and st['coins'] >= rods[nxt]['price']: + st['coins'] -= rods[nxt]['price'] + st['rod'] = nxt + events.append((minute, 'rod', rods[nxt]['id'])) + bought = True + continue + reserve = rods[nxt]['price'] if nxt < len(rods) and st['level'] >= rods[nxt]['level'] - 1 else 0 + nb = st['bag'] + 1 + if nb < len(bags) and st['level'] >= bags[nb]['level'] and st['coins'] - reserve >= bags[nb]['price']: + st['coins'] -= bags[nb]['price'] + st['bag'] = nb + events.append((minute, 'bag', bags[nb]['id'])) + bought = True + continue + lv = st['rodlv'].get(st['rod'], 0) + cost = math.floor(rods[st['rod']]['upgradeCost'] * (lv + 1) ** 1.5) + if lv < c['up']['max'] and st['coins'] - reserve >= cost * 2: + st['coins'] -= cost + st['rodlv'][st['rod']] = lv + 1 + events.append((minute, 'upgrade', f"{rods[st['rod']]['id']}+{lv + 1}")) + bought = True + avg = {} + for w, rows in income_by_world.items(): + if rows: + keys = rows[0].keys() + avg[w] = {k: round(sum(r[k] for r in rows) / len(rows), 1) for k in keys} + avg[w]['net'] = round(sum(sum(v for k, v in r.items() if k != 'cons') - r['cons'] for r in rows) / len(rows), 1) + avg[w]['minutes'] = len(rows) + return events, avg, st + + +def first(events, kind, value=None): + for m, k, v in events: + if k == kind and (value is None or v == value): + return m + return None + + +# ---------------------------------------------------------------- отчёт + +def main(): + res = {'assumptions': ASSUMPTIONS} + scen = {'Новичок / телефон': 3, 'Обычный активный': 4, 'Опытный': 5, 'Оптимизированный (снасти + зелья)': 6, 'Предел механики': 7.5} + res['levels'] = {name: {k: v for k, v in level_minutes(NEW, cpm, 26).items() if k in (3, 5, 8, 10, 13, 18, 25)} for name, cpm in scen.items()} + # до v2: опыт за поимку с серией, первой поимкой и мутациями; плюс задания и босс + old = {} + for cpm in (3, 4, 5): + ev_old, _, st = simulate(BASE, cpm, minutes=1300, legacy=True) + old[cpm] = {k: first(ev_old, 'level', k) for k in (3, 5, 8, 10, 13, 18, 25)} + res['levels_before'] = old + sims = {} + for name, cpm, paid in [('Новичок 3/мин', 3, False), ('Обычный 4/мин', 4, False), ('Опытный 5/мин', 5, False), ('Платные пропуска 4/мин', 4, True)]: + evs, avg, st = simulate(NEW, cpm, minutes=1400, paid=paid) + sims[name] = dict( + purchases=[(m, k, v) for m, k, v in evs if k != 'level'], + first_purchase=min([m for m, k, v in evs if k in ('rod', 'bag')] or [None]), + rods={r['id']: first(evs, 'rod', r['id']) for r in NEW['rods'][1:]}, + income=avg, coins_left=round(st['coins'])) + res['simulations'] = sims + evs_old, avg_old, _ = simulate(BASE, 4, minutes=1300, legacy=True) + res['income_before_4cpm'] = avg_old + res['rods_before_4cpm'] = {r['id']: first(evs_old, 'rod', r['id']) for r in BASE['rods'][1:]} + # ожидания одной поимки по снаряжению + gear = [] + for world, rod_ids in [('World1', ['Basic', 'Bamboo', 'Fiberglass']), ('World2', ['Carbon', 'Coral', 'Golden']), ('World3', ['Frost', 'Legend'])]: + for rid in rod_ids: + rod = next(r for r in NEW['rods'] if r['id'] == rid) + lvl = {'World1': 4, 'World2': 12, 'World3': 22}[world] + luck = 1 + rod['luck'] + (lvl - 1) * NEW['luck_per_level'] + ambient_luck() + v, _, pr = blended_ev(NEW, world, luck) + gear.append(dict(world=world, rod=rid, luck=round(luck, 2), silver_per_catch=round(v, 1), epic_plus=round(pr['Epic'] * 100, 2), mythic=round((pr['Mythic']) * 100, 3))) + res['per_catch'] = gear + # скорость клёва: множитель ожидания лучшей снасти до/после + old_best = BASE['rods'][-1]['speed'] * BASE['up']['speed'] ** BASE['up']['max'] * 0.5 * 0.85 * 0.9 + new_best = max(NEW['waitFloor'], NEW['rods'][-1]['speed'] * NEW['up']['speed'] ** NEW['up']['max'] * 0.85 * 0.92 * 0.93 * 0.9) + res['wait_mult'] = dict(before=round(old_best, 3), after=round(new_best, 3)) + # автоловля против ручной (мир, снаряжение середины) + autos = [] + for world, rid, lvl in [('World1', 'Fiberglass', 6), ('World2', 'Golden', 15), ('World3', 'Legend', 25)]: + rod = next(r for r in NEW['rods'] if r['id'] == rid) + luck = 1 + rod['luck'] + (lvl - 1) * NEW['luck_per_level'] + ambient_luck() + manual = blended_ev(NEW, world, luck)[0] * 4 + auto_rate = 60 / NEW['autoMinCycle'] + auto = fish_ev(NEW, world, luck * 0.6, max_rank=3)[0] * NEW['autoValue'] * auto_rate + autos.append(dict(world=world, manual_fish_silver_min=round(manual, 1), auto_silver_min=round(auto, 1), auto_catches_min=round(auto_rate, 2), auto_xp_min=0, + manual_xp_min=4 * NEW['career'][world])) + res['auto'] = autos + out = ROOT / 'docs' / 'economy-model-results.json' + out.write_text(json.dumps(res, ensure_ascii=False, indent=1) + '\n', encoding='utf-8') + write_md(res) + print(json.dumps({k: res[k] for k in ('levels', 'levels_before', 'wait_mult')}, ensure_ascii=False, indent=1)) + for name, s in sims.items(): + print(name, 'first purchase', s['first_purchase'], 'rods', s['rods']) + for w, a in s['income'].items(): + print(' ', w, a) + print('before income', avg_old) + print('per catch', gear) + print('auto', autos) + + +def hm(m): + if m is None: + return '—' + return f"{int(m // 60)} ч {int(m % 60):02d} мин" if m >= 60 else f"{int(round(m))} мин" + + +def write_md(res): + L = ['# Экономика v2 — расчёт баланса', '', + 'Сгенерировано `py -3 tools/economy_model.py`. Это математическая модель ожиданий по формулам сервера ' + 'и допущениям ниже, **не замер игроков**. Цели по времени считаются подтверждёнными только после ' + 'телеметрии (события CareerXP, LevelUp, economy events) и плейтестов.', '', + '## Время до уровней (эффективная игра, без AFK)', '', + '| Сценарий | ур. 3 | ур. 5 | ур. 8 (Мир 2) | ур. 10 | ур. 13 | ур. 18 (Мир 3) | ур. 25 |', '|---|---:|---:|---:|---:|---:|---:|---:|'] + scen_cpm = {'Новичок / телефон': 3, 'Обычный активный': 4, 'Опытный': 5, 'Оптимизированный (снасти + зелья)': 6, 'Предел механики': 7.5} + for name, lv in res['levels'].items(): + L.append(f"| {name} — {scen_cpm[name]} рыб/мин | " + ' | '.join(hm(lv[k]) for k in (3, 5, 8, 10, 13, 18, 25)) + ' |') + L += ['', 'До v2 (та же модель, опыт с серией ×2, первой поимкой, мутациями, заданиями и боссом):', '', + '| Темп | ур. 3 | ур. 5 | ур. 8 | ур. 10 | ур. 13 | ур. 18 | ур. 25 |', '|---|---:|---:|---:|---:|---:|---:|---:|'] + for cpm, lv in res['levels_before'].items(): + L.append(f"| {cpm} рыб/мин | " + ' | '.join(hm(lv[k]) for k in (3, 5, 8, 10, 13, 18, 25)) + ' |') + L += ['', 'Опыт карьеры зависит только от темпа ручной ловли: снасти, удача, редкость, зелья и пропуска его не ускоряют. ' + 'Разброс между игроками — это разброс темпа (3–6 рыб/мин), а не случайные скачки.', '', + f"Ускорение клёва: лучшая снасть со всеми бонусами раньше давала множитель ожидания ×{res['wait_mult']['before']}, теперь не меньше ×{res['wait_mult']['after']}.", '', + '## Доход серебра, ⚪ в минуту (обычный игрок, 4 рыбы/мин)', '', + '| Мир | рыба | задания | босс | заказы | ежедневка | расходники | итого | цель |', '|---|---:|---:|---:|---:|---:|---:|---:|---:|'] + target = {'World1': 60, 'World2': 120, 'World3': 240} + for w, a in res['simulations']['Обычный 4/мин']['income'].items(): + L.append(f"| {w} | {a['fish']} | {a['quests']} | {a['boss']} | {a['orders']} | {a['daily']} | −{a['cons']} | **{a['net']}** | {target[w]} |") + L += ['', 'До v2, та же модель (4 рыбы/мин): ' + ', '.join(f"{w}: {a['net']} ⚪/мин" for w, a in res['income_before_4cpm'].items()), '', + '## Серебро за одну поимку по снаряжению', '', '| Мир | Удочка | Удача | ⚪ за рыбу | Эпическая+ % | Мифическая % |', '|---|---|---:|---:|---:|---:|'] + for g in res['per_catch']: + L.append(f"| {g['world']} | {g['rod']} | {g['luck']} | {g['silver_per_catch']} | {g['epic_plus']} | {g['mythic']} |") + L += ['', '## Маршрут покупок (жадный, модель)', '', '| Сценарий | первая покупка | ' + ' | '.join(r['id'] for r in NEW['rods'][1:]) + ' |', + '|---|---:|' + '---:|' * (len(NEW['rods']) - 1)] + for name, s in res['simulations'].items(): + L.append(f"| {name} | {hm(s['first_purchase'])} | " + ' | '.join(hm(s['rods'][r['id']]) for r in NEW['rods'][1:]) + ' |') + L.append('| До v2, 4/мин | — | ' + ' | '.join(hm(res['rods_before_4cpm'].get(r['id'])) for r in BASE['rods'][1:]) + ' |') + L += ['', 'Удочку можно купить не раньше её уровня; задержка после уровня — время накопить. ' + 'Платные пропуска (VIP + x2 серебро + талисман) ускоряют покупки, но не уровни.', '', + '## Автоловля против ручной ловли', '', '| Мир | ручная: ⚪/мин (рыба) | авто: ⚪/мин | авто: рыб/мин | опыт/мин ручная | опыт/мин авто |', '|---|---:|---:|---:|---:|---:|'] + for a in res['auto']: + L.append(f"| {a['world']} | {a['manual_fish_silver_min']} | {a['auto_silver_min']} | {a['auto_catches_min']} | {a['manual_xp_min']} | {a['auto_xp_min']} |") + L += ['', '## Допущения', ''] + for k, v in ASSUMPTIONS.items(): + L.append(f"- `{k}` = {v}") + L += ['', 'Ограничения: модель не воспроизводит случайные хвосты (мифическая рыба, серия удачных мутаций), ' + 'поведение реальных игроков, очереди к скупщику, рынок игроков и пропуски заданий. ' + 'Темп в рыбах/мин — главная неизвестная: замерить его до выводов о времени прохождения.', ''] + (ROOT / 'docs' / 'economy-balance.md').write_text('\n'.join(L), encoding='utf-8') + + +if __name__ == '__main__': + main() diff --git a/tools/progression_budget.py b/tools/progression_budget.py new file mode 100644 index 0000000..21a2f76 --- /dev/null +++ b/tools/progression_budget.py @@ -0,0 +1,76 @@ +"""Read-only balance analysis; no game files modified. Python standard library only. +Expected-value budgets, NOT a full gameplay simulation. Run from any directory. +""" +import json +import math +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +# баланс ДО экономики v2 (снимок); текущий баланс считает tools/economy_model.py +source = (ROOT / 'tools/baseline/FishConfig_v1.lua').read_text(encoding='utf-8-sig') +fish_section = source.split('Config.Zones = {', 1)[1].split('Config.Rods = {', 1)[0] +fish = re.findall(r'rarity = "(\w+)",\s+price = (\d+),\s+xp = (\d+)', fish_section) +assert len(fish) == 36 +rarities = ['Common', 'Uncommon', 'Rare', 'Epic', 'Legendary', 'Mythic'] +base_weights = [55, 27, 11, 4.5, 1.2, .25] + +def old_expectation(world, luck): + rows = fish[(world-1)*12:world*12] + weights = [] + for rarity, _, _ in rows: + rank = rarities.index(rarity) + weights.append(base_weights[rank] / max(1, luck) if rank == 0 + else base_weights[rank] * max(.2, 1 + (luck-1)*rank)) + ps = [w / sum(weights) for w in weights] + # Sequential independent mutation rolls, no weather/event/bait mutation multipliers. + remaining, mutation_p, value_mult = 1., 0., 0. + for chance, mult in [(.002, 10), (.01, 5), (.04, 2)]: + p = remaining * min(1, chance*luck) + mutation_p += p + value_mult += p * mult + remaining -= p + value_mult += remaining + xp = sum(p*int(row[2]) for p, row in zip(ps, rows)) * (1 + mutation_p) + value = sum(p*int(row[1]) for p, row in zip(ps, rows)) * (0.75 + .9/3.2) * value_mult + return dict(world=world, luck=luck, xp_per_catch=round(xp, 3), + silver_per_catch_before_combo_sale=round(value, 3), + xp_per_min_4_catches_combo2=round(xp*8, 2)) + +minutes = [5,8,12,15,20,25,35,35,40,45,45,50,55,60,65,70,75,75,80,85,90,95,100,115] +rows, elapsed = [], 0 +for level, target in enumerate(minutes, 1): + world = 1 if level < 8 else 2 if level < 18 else 3 + rate = {1:20, 2:28, 3:36}[world] + elapsed += target + rows.append(dict(from_level=level, to_level=level+1, world=world, + xp_required=target*rate, target_minutes=target, + cumulative_minutes=elapsed)) +milestones = [r for r in rows if r['to_level'] in [3,5,8,10,13,18,25]] +# Proposed career XP = fixed 5/7/9 per successful manual catch by world. +# Other rewards move to silver/materials/research, not career XP. +scenarios = [] +for catches in [3,4,5]: + rates = {w:catches*base for w,base in [(1,5),(2,7),(3,9)]} + for milestone in [8,18,25]: + t = sum(r['xp_required']/rates[r['world']] for r in rows if r['to_level'] <= milestone) + scenarios.append(dict(catches_per_effective_minute=catches,to_level=milestone,minutes=round(t,1))) +result = dict( + assumptions='Current: stationary catch expectations, excludes quests, first discoveries, collection rewards and catch timing. Proposed: budget model, 4 successful manual catches/effective minute, fixed career XP 5/7/9 per world; no other career XP sources or multipliers. Proposed world access exactly at levels 8/18; guild must not add delays. Effective minutes include normal travel/selling, exclude AFK.', + current_xp_to_level={str(l):sum(math.floor(50*k**1.6) for k in range(1,l)) for l in [3,5,8,18,25]}, + current_expectations=[old_expectation(w,luck) for w,luck in [(1,1),(1,1.8),(2,2.5),(3,4)]], + proposed_levels=rows, milestones=milestones, sensitivity=scenarios) +out = ROOT/'docs'/'progression-budget-results.json' +out.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') +table = ['| Переход | Мир | XP на переход | Минут на переход | Минут всего |', + '|---|---:|---:|---:|---:|'] +for r in rows: + table.append(f"| {r['from_level']} → {r['to_level']} | {r['world']} | {r['xp_required']} | {r['target_minutes']} | {r['cumulative_minutes']} |") +(ROOT/'docs'/'progression-level-table.md').write_text( + '# Предлагаемая кривая уровней\n\n' + 'Расчёт бюджета, не замер живых игроков и не симуляция клиента. ' + '4 успешные ручные поимки за минуту эффективной игры, включая обычные перемещения и продажу, без AFK. ' + 'Опыт карьеры: 5/7/9 за рыбу миров 1/2/3. Других источников и множителей XP карьеры нет. ' + 'Доступ к мирам на уровнях 8/18; ранг не добавляет ожидания. ' + 'Таблица не применена к игре.\n\n'+'\n'.join(table)+'\n',encoding='utf-8') +print(json.dumps({k:v for k,v in result.items() if k not in ['proposed_levels','assumptions']}, ensure_ascii=False,indent=2)) diff --git a/tools/run-tests.js b/tools/run-tests.js new file mode 100644 index 0000000..83c8c73 --- /dev/null +++ b/tools/run-tests.js @@ -0,0 +1,28 @@ +// Тесты экономики в открытом Studio (Rojo подключён): node tools/run-tests.js [имя] +// Каждый tests/*.spec.lua выполняется в Edit-режиме через Studio MCP вместе с tests/lib.lua. +// Код плейса не меняется: модули клонируются во временную папку ServerStorage и удаляются после прогона. +const { execFileSync } = require('child_process'); +const fs = require('fs'); +const path = require('path'); +const root = path.resolve(__dirname, '..'); +const tests = path.join(root, 'tests'); +const only = process.argv[2]; +const lib = fs.readFileSync(path.join(tests, 'lib.lua'), 'utf8').replace(/^/, ''); +const specs = fs.readdirSync(tests).filter(f => f.endsWith('.spec.lua') && (!only || f.includes(only))); +const outDir = path.join(tests, '.out'); +fs.mkdirSync(outDir, { recursive: true }); +const steps = specs.map(f => ({ + tool: 'execute_luau', + args: { + datamodel_type: 'Edit', + code: 'local T = (function()\n' + lib + '\nend)()\n' + fs.readFileSync(path.join(tests, f), 'utf8').replace(/^/, ''), + }, +})); +const stepsFile = path.join(outDir, 'steps.json'); +fs.writeFileSync(stepsFile, JSON.stringify(steps)); +const out = execFileSync('node', [path.join(__dirname, 'mcp', 'run.js'), stepsFile], { maxBuffer: 1 << 26 }).toString('utf8'); +process.stdout.write(out + '\n'); +const failed = [...out.matchAll(/(\d+) passed, (\d+) failed/g)]; +const bad = failed.length < specs.length || failed.some(m => m[2] !== '0') || /\(ERROR\)/.test(out); +console.log(bad ? 'TESTS FAILED' : `ALL ${specs.length} SUITES PASSED`); +process.exit(bad ? 1 : 0);