null nil WorkspaceBaseplatetrue0-80100010001512165124284193356128000 SpawnLocationtrue00.50100010001616429134868025600 ReplicatedStorageGameConfig= 1000 and index < #SUFFIXES do n /= 1000 index += 1 end -- "1.50K" -> "1.5K", "2.00M" -> "2M" local text = string.format("%.2f%s", n, SUFFIXES[index]) return (text:gsub("%.?0+([%a]+)$", "%1")) end return GameConfig ]]> RemotesClickButton PurchaseUpgrade UpdateStats Notify ServerScriptServiceDataManager таблица данных или nil (ещё не загружено) -- DataManager.SendStats(player) -> отправить актуальную статистику клиенту -- DataManager.Notify(player, text, kind) -> всплывающее уведомление -- Модуль сам подключается к PlayerAdded/PlayerRemoving при первом require. local Players = game:GetService("Players") local DataStoreService = game:GetService("DataStoreService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig")) local DataManager = {} ------------------------------------------------------------------ -- RemoteEvents: создаём папку Remotes и события, если их нет -- (при сборке через Rojo они уже есть — тогда просто берём готовые) ------------------------------------------------------------------ local remotesFolder = ReplicatedStorage:FindFirstChild("Remotes") if not remotesFolder then remotesFolder = Instance.new("Folder") remotesFolder.Name = "Remotes" remotesFolder.Parent = ReplicatedStorage end DataManager.Remotes = {} for _, remoteName in GameConfig.RemoteNames do local remote = remotesFolder:FindFirstChild(remoteName) if not remote then remote = Instance.new("RemoteEvent") remote.Name = remoteName remote.Parent = remotesFolder end DataManager.Remotes[remoteName] = remote end local Remotes = DataManager.Remotes ------------------------------------------------------------------ -- DataStore (в Studio без "Enable Studio Access to API Services" упадёт — -- тогда игра работает, но без сохранений) ------------------------------------------------------------------ local dataStore = nil local storeOk, storeErr = pcall(function() dataStore = DataStoreService:GetDataStore(GameConfig.DataStoreName) end) if not storeOk then warn("[DataManager] DataStore недоступен, сохранения отключены: " .. tostring(storeErr)) end -- [Player] = { Data = {...}, SaveEnabled = bool, IsSaving = bool } local profiles = {} ------------------------------------------------------------------ -- Вспомогательные функции ------------------------------------------------------------------ local function deepCopy(value) if type(value) ~= "table" then return value end local copy = {} for k, v in value do copy[k] = deepCopy(v) end return copy end -- Дополняет старые сохранения новыми полями из шаблона local function reconcile(data, template) for key, templateValue in template do if type(templateValue) == "table" then if type(data[key]) ~= "table" then data[key] = deepCopy(templateValue) else reconcile(data[key], templateValue) end elseif data[key] == nil then data[key] = templateValue end end end -- Защита от битых данных: NaN, отрицательные числа, неверные типы local function sanitizeNumber(value) if type(value) ~= "number" or value ~= value or value < 0 or value == math.huge then return 0 end return math.floor(value) end local function sanitize(data) data.Coins = sanitizeNumber(data.Coins) data.Clicks = sanitizeNumber(data.Clicks) for upgradeId, upgrade in GameConfig.Upgrades do data.Upgrades[upgradeId] = math.clamp(sanitizeNumber(data.Upgrades[upgradeId]), 0, upgrade.MaxLevel) end -- Множитель всегда пересчитываем из уровня, а не верим сохранённому значению data.Multiplier = GameConfig.GetMultiplier(data.Upgrades.ClickPower) end -- Выполняет fn с повторами и растущей задержкой local function withRetry(actionName, playerName, fn) local lastError for attempt = 1, GameConfig.MaxRetries do local success, result = pcall(fn) if success then return true, result end lastError = result warn(string.format("[DataManager] %s (%s): попытка %d/%d не удалась: %s", actionName, playerName, attempt, GameConfig.MaxRetries, tostring(result))) if attempt < GameConfig.MaxRetries then task.wait(GameConfig.RetryDelay * attempt) end end return false, lastError end local function getKey(player) return "Player_" .. player.UserId end -- Таблица лидеров (Tab) — дополнительно к нашему UI local function createLeaderstats(player) local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" local coins = Instance.new("IntValue") coins.Name = "Coins" coins.Parent = leaderstats local clicks = Instance.new("IntValue") clicks.Name = "Clicks" clicks.Parent = leaderstats leaderstats.Parent = player end ------------------------------------------------------------------ -- Публичное API ------------------------------------------------------------------ function DataManager.GetData(player) local profile = profiles[player] return profile and profile.Data end function DataManager.Notify(player, text, kind) Remotes.Notify:FireClient(player, text, kind or "Info") end -- Отправляет клиенту актуальные данные и обновляет leaderstats function DataManager.SendStats(player) local profile = profiles[player] if not profile then return end local data = profile.Data local leaderstats = player:FindFirstChild("leaderstats") if leaderstats then local coins = leaderstats:FindFirstChild("Coins") local clicks = leaderstats:FindFirstChild("Clicks") if coins then coins.Value = data.Coins end if clicks then clicks.Value = data.Clicks end end Remotes.UpdateStats:FireClient(player, { Coins = data.Coins, Clicks = data.Clicks, Multiplier = data.Multiplier, Upgrades = deepCopy(data.Upgrades), }) end ------------------------------------------------------------------ -- Загрузка / сохранение ------------------------------------------------------------------ local function loadPlayer(player) local data = nil local saveEnabled = false if dataStore then local success, result = withRetry("Загрузка", player.Name, function() return dataStore:GetAsync(getKey(player)) end) if success then -- result == nil -> новый игрок data = if type(result) == "table" then result else deepCopy(GameConfig.DefaultData) saveEnabled = true end end if not data then -- Загрузить не удалось: играем на стандартных данных, но НЕ сохраняем, -- чтобы не перезаписать настоящий прогресс игрока пустым data = deepCopy(GameConfig.DefaultData) saveEnabled = false end reconcile(data, GameConfig.DefaultData) sanitize(data) -- Игрок мог выйти, пока шла загрузка if player.Parent ~= Players then return end profiles[player] = { Data = data, SaveEnabled = saveEnabled, IsSaving = false } createLeaderstats(player) DataManager.SendStats(player) if not saveEnabled then DataManager.Notify(player, "⚠️ Сохранения недоступны — прогресс не сохранится", "Error") end end local function saveProfile(player, profile) if not profile or not profile.SaveEnabled or not dataStore then return end -- Не запускаем два сохранения одного игрока одновременно while profile.IsSaving do task.wait(0.1) end profile.IsSaving = true local snapshot = deepCopy(profile.Data) local success, err = withRetry("Сохранение", player.Name, function() dataStore:UpdateAsync(getKey(player), function() return snapshot end) end) if not success then warn("[DataManager] Не удалось сохранить " .. player.Name .. ": " .. tostring(err)) end profile.IsSaving = false end ------------------------------------------------------------------ -- События игроков ------------------------------------------------------------------ Players.PlayerAdded:Connect(loadPlayer) for _, player in Players:GetPlayers() do task.spawn(loadPlayer, player) end Players.PlayerRemoving:Connect(function(player) local profile = profiles[player] if profile then saveProfile(player, profile) profiles[player] = nil end end) -- Клиент может попросить данные заново (например, UI загрузился позже) Remotes.UpdateStats.OnServerEvent:Connect(function(player) DataManager.SendStats(player) end) -- Автосейв task.spawn(function() while true do task.wait(GameConfig.AutoSaveInterval) for player, profile in profiles do task.spawn(saveProfile, player, profile) end end end) -- Сохранение всех при выключении сервера (до 30 сек у Roblox) game:BindToClose(function() local pending = 0 for player, profile in profiles do pending += 1 task.spawn(function() saveProfile(player, profile) pending -= 1 end) end local started = os.clock() while pending > 0 and os.clock() - started < 25 do task.wait(0.1) end end) return DataManager ]]> MapBuilder вверх) local function makePart(name, size, cframe, color, material, parent, shape) local part = Instance.new("Part") part.Name = name part.Size = size part.CFrame = cframe part.Color = color part.Material = material or Enum.Material.SmoothPlastic part.Anchored = true part.TopSurface = Enum.SurfaceType.Smooth part.BottomSurface = Enum.SurfaceType.Smooth if shape then part.Shape = shape end part.Parent = parent return part end -- Вертикальный цилиндр: height — высота, diameter — диаметр, centerY — высота центра local function makeCylinder(name, height, diameter, centerY, color, material, parent) return makePart( name, Vector3.new(height, diameter, diameter), CFrame.new(STAND_POSITION + Vector3.new(0, centerY, 0)) * VERTICAL, color, material, parent, Enum.PartType.Cylinder ) end ------------------------------------------------------------------ -- Baseplate и точка появления ------------------------------------------------------------------ if not workspace:FindFirstChild("Baseplate") then makePart("Baseplate", Vector3.new(512, 16, 512), CFrame.new(0, -8, 0), Color3.fromRGB(91, 154, 76), Enum.Material.Grass, workspace) end if not workspace:FindFirstChildWhichIsA("SpawnLocation", true) then local spawn = Instance.new("SpawnLocation") spawn.Name = "SpawnLocation" spawn.Size = Vector3.new(6, 1, 6) spawn.CFrame = CFrame.new(0, 0.5, 0) spawn.Anchored = true spawn.Neutral = true spawn.Color = Color3.fromRGB(200, 200, 200) spawn.Parent = workspace end ------------------------------------------------------------------ -- Стенд с кнопкой ------------------------------------------------------------------ local function buildStand() local stand = Instance.new("Model") stand.Name = "ClickerStand" -- Основание и стойка makeCylinder("GlowRing", 0.1, 16.6, 0.05, Color3.fromRGB(255, 200, 40), Enum.Material.Neon, stand) makeCylinder("Floor", 0.2, 16, 0.1, Color3.fromRGB(45, 45, 55), Enum.Material.Slate, stand) makeCylinder("Base", 1, 10, 0.7, Color3.fromRGB(60, 60, 70), Enum.Material.Slate, stand) -- верх на 1.2 makeCylinder("Pillar", 4, 3, 3.2, Color3.fromRGB(230, 230, 235), Enum.Material.Marble, stand) -- 1.2 .. 5.2 -- Верхняя платформа (верх на высоте 6.2) local platform = makeCylinder("Platform", 1, 7, 5.7, Color3.fromRGB(240, 240, 245), Enum.Material.Marble, stand) makeCylinder("PlatformRim", 0.4, 7.4, 5.7, Color3.fromRGB(255, 200, 40), Enum.Material.Metal, stand) makeCylinder("ButtonRing", 0.3, 4.8, 6.35, Color3.fromRGB(255, 200, 40), Enum.Material.Metal, stand) -- верх на 6.5 -- Сама кнопка local button = makeCylinder("ClickButton", 1, 4, 7.0, Color3.fromRGB(235, 50, 50), Enum.Material.SmoothPlastic, stand) local clickDetector = Instance.new("ClickDetector") clickDetector.MaxActivationDistance = GameConfig.ClickDetectorDistance clickDetector.Parent = button local light = Instance.new("PointLight") light.Color = Color3.fromRGB(255, 90, 90) light.Brightness = 2 light.Range = 10 light.Parent = button -- Частицы: Rate = 0, клиент вызывает :Emit() при клике local particles = Instance.new("ParticleEmitter") particles.Name = "ClickParticles" particles.Texture = "rbxasset://textures/particles/sparkles_main.dds" particles.Rate = 0 particles.EmissionDirection = Enum.NormalId.Right -- у повёрнутого цилиндра "Right" смотрит вверх particles.Lifetime = NumberRange.new(0.4, 0.8) particles.Speed = NumberRange.new(10, 16) particles.SpreadAngle = Vector2.new(45, 45) particles.Acceleration = Vector3.new(0, -25, 0) particles.LightEmission = 1 particles.Color = ColorSequence.new(Color3.fromRGB(255, 220, 60), Color3.fromRGB(255, 120, 40)) particles.Size = NumberSequence.new({ NumberSequenceKeypoint.new(0, 0.5), NumberSequenceKeypoint.new(1, 0), }) particles.Parent = button -- Табло над стендом local billboard = Instance.new("BillboardGui") billboard.Name = "StandBillboard" billboard.Size = UDim2.new(10, 0, 3.5, 0) -- в studs, масштабируется с расстоянием billboard.StudsOffsetWorldSpace = Vector3.new(0, 5.5, 0) billboard.LightInfluence = 0 billboard.MaxDistance = 150 billboard.Parent = platform local title = Instance.new("TextLabel") title.Name = "Title" title.Size = UDim2.fromScale(1, 0.6) title.BackgroundTransparency = 1 title.Font = Enum.Font.FredokaOne title.TextScaled = true title.TextColor3 = Color3.fromRGB(255, 220, 60) title.TextStrokeTransparency = 0 title.Text = "Нажми меня!" title.Parent = billboard local counter = Instance.new("TextLabel") counter.Name = "Counter" counter.Position = UDim2.fromScale(0, 0.6) counter.Size = UDim2.fromScale(1, 0.4) counter.BackgroundTransparency = 1 counter.Font = Enum.Font.GothamBold counter.TextScaled = true counter.TextColor3 = Color3.new(1, 1, 1) counter.TextStrokeTransparency = 0 counter.Text = "Кликов на сервере: 0" counter.Parent = billboard -- Стенд всегда есть у клиента (иначе при StreamingEnabled кнопка может выгрузиться) pcall(function() stand.ModelStreamingMode = Enum.ModelStreamingMode.Persistent end) stand.PrimaryPart = platform stand.Parent = workspace end ------------------------------------------------------------------ -- Декор: деревья и фонари ------------------------------------------------------------------ local function buildTree(position) local tree = Instance.new("Model") tree.Name = "Tree" makePart("Trunk", Vector3.new(2, 8, 2), CFrame.new(position + Vector3.new(0, 4, 0)), Color3.fromRGB(105, 64, 40), Enum.Material.Wood, tree) makePart("Leaves", Vector3.new(9, 9, 9), CFrame.new(position + Vector3.new(0, 11, 0)), Color3.fromRGB(60, 140, 60), Enum.Material.Grass, tree, Enum.PartType.Ball) return tree end local function buildLamp(position) local lamp = Instance.new("Model") lamp.Name = "Lamp" makePart("Pole", Vector3.new(0.6, 10, 0.6), CFrame.new(position + Vector3.new(0, 5, 0)), Color3.fromRGB(30, 30, 35), Enum.Material.Metal, lamp) local head = makePart("Head", Vector3.new(1.6, 1.6, 1.6), CFrame.new(position + Vector3.new(0, 10.6, 0)), Color3.fromRGB(255, 230, 160), Enum.Material.Neon, lamp, Enum.PartType.Ball) local light = Instance.new("PointLight") light.Range = 18 light.Brightness = 1.5 light.Color = Color3.fromRGB(255, 220, 160) light.Parent = head return lamp end local function buildDecorations() local decorations = Instance.new("Folder") decorations.Name = "Decorations" for _, offset in { Vector3.new(-22, 0, -30), Vector3.new(22, 0, -30), Vector3.new(-30, 0, -6), Vector3.new(30, 0, -6), Vector3.new(-18, 0, 16), Vector3.new(18, 0, 16) } do buildTree(offset).Parent = decorations end for _, offset in { Vector3.new(-9, 0, -5), Vector3.new(9, 0, -5), Vector3.new(-9, 0, -23), Vector3.new(9, 0, -23) } do buildLamp(offset).Parent = decorations end decorations.Parent = workspace end if not workspace:FindFirstChild("ClickerStand") then buildStand() end if not workspace:FindFirstChild("Decorations") then buildDecorations() end ]]> ClickHandler ShopHandler= upgrade.MaxLevel then DataManager.Notify(player, "Достигнут максимальный уровень", "Error") return end local price = GameConfig.GetUpgradePrice(upgradeId, level) if data.Coins < price then DataManager.Notify(player, "Не хватает монет: нужно " .. GameConfig.FormatNumber(price), "Error") return end -- Покупка data.Coins -= price data.Upgrades[upgradeId] = level + 1 data.Multiplier = GameConfig.GetMultiplier(data.Upgrades.ClickPower) DataManager.SendStats(player) DataManager.Notify(player, string.format("%s %s — уровень %d!", upgrade.Icon, upgrade.Name, level + 1), "Success") end) Players.PlayerRemoving:Connect(function(player) lastPurchaseTime[player] = nil end) ]]> AutoClicker 0 then local gain = clicks * data.Multiplier data.Clicks += clicks data.Coins += gain DataManager.SendStats(player) ClickRemote:FireClient(player, gain, true) -- true = это доход автокликера end end end end ]]> StarterPlayerStarterPlayerScriptsUIController после покупки" local function getEffectText(upgradeId, level) if upgradeId == "ClickPower" then return string.format("Монет за клик: x%s → x%s", GameConfig.FormatNumber(GameConfig.GetMultiplier(level)), GameConfig.FormatNumber(GameConfig.GetMultiplier(level + 1))) elseif upgradeId == "AutoClicker" then return string.format("Авто-кликов каждые %d сек: %d → %d", GameConfig.AutoClickInterval, GameConfig.GetAutoClicks(level), GameConfig.GetAutoClicks(level + 1)) end return "" end -- Сортируем улучшения по Order из GameConfig local upgradeIds = {} for upgradeId in GameConfig.Upgrades do table.insert(upgradeIds, upgradeId) end table.sort(upgradeIds, function(a, b) return GameConfig.Upgrades[a].Order < GameConfig.Upgrades[b].Order end) local currentStats = nil local shopItems = {} -- [upgradeId] = { Name, Effect, Button, Enabled } local function setButtonEnabled(item, enabled) item.Enabled = enabled item.Button.Active = enabled item.Button.AutoButtonColor = enabled item.Button.BackgroundColor3 = if enabled then COLORS.Buy else COLORS.Disabled item.Button.TextTransparency = if enabled then 0 else 0.35 end local function refreshShop() if not currentStats then return end for upgradeId, item in shopItems do local upgrade = GameConfig.Upgrades[upgradeId] local level = currentStats.Upgrades[upgradeId] or 0 item.Name.Text = string.format("%s %s (ур. %d)", upgrade.Icon, upgrade.Name, level) if level >= upgrade.MaxLevel then item.Effect.Text = "Максимальный уровень" item.Button.Text = "МАКС" setButtonEnabled(item, false) else local price = GameConfig.GetUpgradePrice(upgradeId, level) item.Effect.Text = getEffectText(upgradeId, level) item.Button.Text = "Купить: " .. GameConfig.FormatNumber(price) .. " 💰" setButtonEnabled(item, currentStats.Coins >= price) end end end for index, upgradeId in upgradeIds do local frame = create("Frame", { Name = upgradeId, LayoutOrder = index, Size = UDim2.new(1, -8, 0, 100), BackgroundColor3 = COLORS.Item, Parent = itemList, }, { corner(10) }) local nameLabel = create("TextLabel", { Name = "UpgradeName", Position = UDim2.fromOffset(12, 8), Size = UDim2.new(1, -24, 0, 26), BackgroundTransparency = 1, Font = Enum.Font.GothamBold, TextSize = 20, TextColor3 = COLORS.Text, TextXAlignment = Enum.TextXAlignment.Left, TextTruncate = Enum.TextTruncate.AtEnd, Parent = frame, }) local effectLabel = create("TextLabel", { Name = "Effect", Position = UDim2.fromOffset(12, 38), Size = UDim2.new(0.55, -12, 0, 52), BackgroundTransparency = 1, Font = Enum.Font.Gotham, TextSize = 16, TextWrapped = true, TextColor3 = COLORS.SubText, TextXAlignment = Enum.TextXAlignment.Left, TextYAlignment = Enum.TextYAlignment.Top, Parent = frame, }) local buyButton = create("TextButton", { Name = "Buy", AnchorPoint = Vector2.new(1, 1), Position = UDim2.new(1, -12, 1, -12), Size = UDim2.new(0.42, 0, 0, 44), BackgroundColor3 = COLORS.Disabled, Font = Enum.Font.GothamBold, TextSize = 17, TextColor3 = COLORS.Text, Text = "...", Parent = frame, }, { corner(8), create("UIScale") }) local item = { Name = nameLabel, Effect = effectLabel, Button = buyButton, Enabled = false } shopItems[upgradeId] = item buyButton.Activated:Connect(function() if not item.Enabled then return -- не хватает денег / макс. уровень end pop(buyButton, 0.9) PurchaseUpgrade:FireServer(upgradeId) -- окончательное решение примет сервер end) end -- Открытие / закрытие с анимацией local shopOpen = false local function setShopOpen(open) shopOpen = open if open then refreshShop() shopFrame.Visible = true shopScale.Scale = 0.85 TweenService:Create(shopScale, TweenInfo.new(0.25, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Scale = 1 }):Play() else local tween = TweenService:Create(shopScale, TweenInfo.new(0.12, Enum.EasingStyle.Quad, Enum.EasingDirection.In), { Scale = 0.85 }) tween.Completed:Once(function() if not shopOpen then shopFrame.Visible = false end end) tween:Play() end end shopButton.Activated:Connect(function() pop(shopButton, 0.9) setShopOpen(not shopOpen) end) closeButton.Activated:Connect(function() setShopOpen(false) end) ------------------------------------------------------------------ -- Уведомления (сверху по центру) ------------------------------------------------------------------ local toastHolder = create("Frame", { Name = "Toasts", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 12), Size = UDim2.fromOffset(420, 0), AutomaticSize = Enum.AutomaticSize.Y, BackgroundTransparency = 1, Parent = screenGui, }, { create("UIListLayout", { Padding = UDim.new(0, 6), HorizontalAlignment = Enum.HorizontalAlignment.Center, SortOrder = Enum.SortOrder.LayoutOrder, }), }) local toastCounter = 0 local function showToast(text, kind) toastCounter += 1 local toast = create("TextLabel", { LayoutOrder = toastCounter, Size = UDim2.fromOffset(0, 0), AutomaticSize = Enum.AutomaticSize.XY, BackgroundColor3 = COLORS[kind] or COLORS.Info, BackgroundTransparency = 0.1, Font = Enum.Font.GothamBold, TextSize = 18, TextColor3 = COLORS.Text, Text = text, Parent = toastHolder, }, { corner(8), padding(8), create("UIScale") }) pop(toast, 0.8) task.delay(2.5, function() local info = TweenInfo.new(0.4) TweenService:Create(toast, info, { BackgroundTransparency = 1, TextTransparency = 1 }):Play() task.wait(0.4) toast:Destroy() end) end ------------------------------------------------------------------ -- События с сервера ------------------------------------------------------------------ UpdateStats.OnClientEvent:Connect(function(stats) if type(stats) ~= "table" then return end currentStats = stats setStat("Coins", stats.Coins) setStat("Clicks", stats.Clicks) setStat("Multiplier", stats.Multiplier) refreshShop() end) Notify.OnClientEvent:Connect(function(text, kind) if type(text) == "string" then showToast(text, kind) end end) -- Запрашиваем данные на случай, если сервер отправил их до подключения UI UpdateStats:FireServer() ]]> ClickInput