Слияние с командой: экономика/рынок/зелья/Остров 2 + наш сад, площадь, Гильдия (карта соединена по объектам)
This commit is contained in:
commit
a9bc4207cb
31 files changed
+239767
-638
No files matched your search
@@ -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
|
||||
|
||||
@@ -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,23 @@ 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)
|
||||
-- неопубликованный плейс / Studio без доступа к API: GetDataStore проходит, но любой запрос падает.
|
||||
-- Тогда сразу играем без сохранения (иначе вход ждал бы повторов загрузки и интерфейс стоял пустым)
|
||||
if store and RunService:IsStudio() then
|
||||
local ok = pcall(function()
|
||||
store:GetAsync("probe")
|
||||
end)
|
||||
if not ok then
|
||||
store, marketStore = nil, nil
|
||||
end
|
||||
end
|
||||
-- замок сессии: профиль открыт только на одном сервере (без этого возможен дюп между серверами и на рынке)
|
||||
local playerStore = store and PlayerStore.new(store, { staleAfter = 600 }) or nil
|
||||
|
||||
local profiles = {}
|
||||
local loadedOk = {}
|
||||
@@ -88,7 +107,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 +118,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 +196,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 +243,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 +281,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 +291,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 +377,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 +406,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 +470,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 +505,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 +542,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 +879,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 +889,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 +922,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 +937,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 +1027,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 +1059,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 +1091,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 +1122,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 +1146,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 +1182,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 +1267,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 +1290,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 +1324,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 +1401,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 +1415,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 +1442,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 +1457,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 +1467,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 +1497,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 +1519,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 +1691,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 +1748,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 +1807,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 +1884,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 +1959,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 +2016,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 +2077,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 +2094,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
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,96 @@
|
||||
-- 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
|
||||
-- ошибка хранилища: не больше 3 попыток (игрок не ждёт долго); чужой замок — ждём дольше
|
||||
if not locked and attempt >= math.min(3, self.loadTries) then
|
||||
return "error", lastErr
|
||||
end
|
||||
if attempt == self.loadTries then
|
||||
return locked and "locked" or "error", lastErr
|
||||
end
|
||||
self.wait(locked and 5 or 1)
|
||||
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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 = ("<font color=\"%s\">%s</font>%s · %.2f кг"):format(
|
||||
hex(r.color), r.name, mut and (" · <font color=\"" .. hex(mut.color) .. "\">" .. mut.name .. " x" .. mut.mult .. "</font>") 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("🧪 Заменить зелье?", ("Сейчас действует <b>%s %s</b> — осталось <b>%s</b>.\nЕсли выпить <b>%s %s</b>, остаток прежнего зелья <font color=\"#FF8A7A\">пропадёт</font>.")
|
||||
: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Осталось: <b>%s</b>"):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 <font color=\"#FFD45A\">×%d</font>"):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, ("<font color=\"%s\">%s %.1f%%</font>"):format(hex(m.color), m.name, math.min(100, m.chance * total / 100 * ((event and event.mutation) or 1) * 100)))
|
||||
table.insert(mutLine, ("<font color=\"%s\">%s %.1f%%</font>"):format(hex(m.color), m.name, math.min(100, m.chance * mm * 100)))
|
||||
end
|
||||
local lines = {
|
||||
("<font size=\"24\" color=\"#7CFF9A\">🍀 Твоя удача: %d%%</font>"):format(total),
|
||||
("<font size=\"22\" color=\"#7CFF9A\">🍀 Твоя удача: %d%%</font>"):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, " · "),
|
||||
"<font color=\"#BBA98A\">Каждые следующие +100% удачи действуют слабее предыдущих.</font>",
|
||||
}
|
||||
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 = ("Удача <b>+%d%%</b> на <b>%d мин</b>.\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, ("<font color=\"%s\">%s</font> %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, ("<b>%s</b> · %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, ("<b>%s</b> · %s · %.2f кг%s%s"):format(it.name, r.name, it.weight, mut and (" · " .. mut.name) or "",
|
||||
it.bought and ("<br/>🛒 Куплена у %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 = ("Удача <b>%d%%</b>"):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
|
||||
@@ -3214,10 +3337,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
|
||||
@@ -3328,11 +3452,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))
|
||||
@@ -3348,7 +3472,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("🧪 Заменить зелье?", ("Сейчас действует <b>%s %s</b> — осталось <b>%s</b>.\nЕсли выпить <b>%s %s</b>, остаток прежнего зелья <font color=\"#FF8A7A\">пропадёт</font>.")
|
||||
: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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 ("<font color=\"%s\">%s</font>%s · %.2f кг"):format(hex(r.color), r.name, mut and (" · <font color=\"" .. hex(mut.color) .. "\">" .. mut.name .. "</font>") 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%%: <b>%s ⚪</b> · ты получишь <b><font color=\"#7CFF9A\">%s ⚪</font></b>\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, ("🔒 Рынок открывается с <b>%d уровня</b> (вместе с Миром 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Продаёт <b>%s</b>%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("🏪 Купить рыбу?", ("<b>%s</b> — %s\nПродавец: <b>%s</b>\nЦена: <b>%s ⚪</b> (продавец платит комиссию %s ⚪ и получит %s ⚪)\n"
|
||||
.. "<font color=\"#BBA98A\">Цена — решение продавца. Скупщик даст за эту рыбу ≈ %s ⚪. Купленная рыба придёт в «Посылки».</font>")
|
||||
: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 .. " <font color=\"#FFD45A\">" .. fmt(L.price) .. " ⚪</font>", 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")
|
||||
Reference in new issue
Block a user