diff --git a/ClickerGame.rbxlx b/ClickerGame.rbxlx
new file mode 100644
index 0000000..d1850c4
--- /dev/null
+++ b/ClickerGame.rbxlx
@@ -0,0 +1,1378 @@
+
+null
+nil
+- Workspace
- Baseplatetrue0-80100010001512165124284193356128000
+- SpawnLocationtrue00.50100010001616429134868025600
+- ReplicatedStorage
- GameConfig= 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
+]]>
+- Remotes
- ClickButton
+- PurchaseUpgrade
+- UpdateStats
+- Notify
+- ServerScriptService
- DataManager таблица данных или 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
+]]>
+- StarterPlayer
- StarterPlayerScripts
- UIController после покупки"
+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
+
\ No newline at end of file
diff --git a/README.md b/README.md
index 5ddc66e..a57bd72 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,115 @@
-# RobloxClicker
+# ClickerGame — кликер для Roblox
+## Быстрый старт
+
+1. Откройте **`ClickerGame.rbxlx`** двойным кликом (или Roblox Studio → **File → Open from File…**).
+ Все скрипты и RemoteEvent'ы уже лежат на своих местах.
+2. Нажмите **Play** (F5). Стенд, кнопка и декор строятся скриптом `MapBuilder` при запуске,
+ поэтому в режиме редактирования вы увидите только землю и точку появления.
+3. Чтобы работали сохранения: **File → Publish to Roblox**, затем
+ **Game Settings → Security → Enable Studio Access to API Services**.
+
+Если вы поменяли код в папке `src`, пересоберите place-файл:
+
+```bash
+powershell -ExecutionPolicy Bypass -File build.ps1
+```
+
+Правки, сделанные прямо в Studio, в `src` не попадают. Выберите, где вы правите код: в Studio
+(тогда сохраняйте `.rbxlx` через Ctrl+S) или в `src` с пересборкой.
+
+## Архитектура
+
+Сервер — единственный источник правды. `DataManager` загружает данные игрока из DataStore
+(с повторами), держит их в памяти, сохраняет каждые 60 сек, при выходе игрока и при выключении
+сервера. Клиент (`ClickInput`) только сообщает «я кликнул» через `ClickButton`. `ClickHandler` проверяет
+интервал между кликами и расстояние до кнопки, начисляет `Multiplier` монет и отправляет статистику
+через `UpdateStats`. `ShopHandler` сам считает цену и проверяет баланс, `AutoClicker` начисляет
+пассивный доход. Все числа и формулы лежат в `GameConfig`, его читают и сервер, и клиент.
+`UIController` строит интерфейс кодом и только отображает то, что прислал сервер. `MapBuilder`
+автоматически строит стенд, кнопку и декор, если их нет в Workspace.
+
+## Файлы → Explorer
+
+| Файл | Куда в Studio | Тип |
+|---|---|---|
+| `src/shared/GameConfig.luau` | ReplicatedStorage → **GameConfig** | ModuleScript |
+| *(создаётся автоматически)* | ReplicatedStorage → **Remotes** (Folder) → ClickButton, PurchaseUpgrade, UpdateStats, Notify | RemoteEvent |
+| `src/server/DataManager.luau` | ServerScriptService → **DataManager** | ModuleScript |
+| `src/server/ClickHandler.server.luau` | ServerScriptService → **ClickHandler** | Script |
+| `src/server/ShopHandler.server.luau` | ServerScriptService → **ShopHandler** | Script |
+| `src/server/AutoClicker.server.luau` | ServerScriptService → **AutoClicker** | Script |
+| `src/server/MapBuilder.server.luau` | ServerScriptService → **MapBuilder** | Script |
+| `src/client/UIController.client.luau` | StarterPlayer → StarterPlayerScripts → **UIController** | LocalScript |
+| `src/client/ClickInput.client.luau` | StarterPlayer → StarterPlayerScripts → **ClickInput** | LocalScript |
+
+ScreenGui `ClickerUI` создаётся кодом `UIController` в PlayerGui, поэтому в StarterGui ничего добавлять не нужно.
+
+## Сборка вручную (копипаст в Studio)
+
+1. Откройте Roblox Studio → **New → Baseplate**.
+2. **File → Game Settings → Security**: включите **Enable Studio Access to API Services**
+ (без этого DataStore в Studio не работает: игра запустится, но прогресс не сохранится,
+ и игрок увидит предупреждение).
+ Перед этим игру нужно опубликовать: **File → Publish to Roblox**.
+3. В **ReplicatedStorage** создайте ModuleScript и назовите его `GameConfig`. Вставьте код из `GameConfig.luau`.
+4. В **ServerScriptService** создайте:
+ - ModuleScript `DataManager`;
+ - Script `ClickHandler`, `ShopHandler`, `AutoClicker`, `MapBuilder`.
+
+ Вставьте в каждый код из соответствующего файла.
+5. В **StarterPlayer → StarterPlayerScripts** создайте LocalScript `UIController` и `ClickInput`.
+6. Нажмите **Play** (F5).
+
+Имена должны совпадать в точности, потому что скрипты ищут друг друга по имени.
+
+### Если хотите собрать стенд руками (необязательно)
+
+`MapBuilder` строит стенд сам. Если в Workspace уже есть Model `ClickerStand`, он его не трогает.
+Минимальная структура, которую ждут скрипты:
+
+```
+Workspace
+└── ClickerStand (Model, ModelStreamingMode = Persistent)
+ ├── Pillar (Part, Anchored, стойка, например 3×4×3)
+ ├── Platform (Part, Anchored, верхняя платформа, например 7×1×7)
+ │ └── StandBillboard (BillboardGui: Size {10,0},{3.5,0}, StudsOffsetWorldSpace 0,5.5,0, LightInfluence 0)
+ │ ├── Title (TextLabel, Text "Нажми меня!", TextScaled, BackgroundTransparency 1)
+ │ └── Counter (TextLabel, TextScaled, BackgroundTransparency 1)
+ └── ClickButton (Part, Anchored, Shape Cylinder, Size 1×4×4, Orientation 0,0,90, лежит на платформе)
+ ├── ClickDetector (MaxActivationDistance 20)
+ └── ClickParticles (ParticleEmitter: Rate 0, EmissionDirection Right,
+ Texture rbxasset://textures/particles/sparkles_main.dds,
+ Speed 10–16, Lifetime 0.4–0.8)
+```
+
+Пошагово:
+1. **Model → Part**: стойка. Включите Anchored, задайте размер и цвет, назовите `Pillar`.
+2. Ещё одна Part сверху: `Platform`.
+3. Part → Shape = **Cylinder**, Orientation = `0, 0, 90` (цилиндр «стоит»), положите на платформу и назовите `ClickButton`. Включите Anchored.
+4. В `ClickButton`: **+ → ClickDetector** и **+ → ParticleEmitter** (назовите `ClickParticles`, выставьте свойства как выше).
+5. В `Platform`: **+ → BillboardGui** `StandBillboard`, внутри два TextLabel: `Title` и `Counter`.
+6. Выделите все части → **Ctrl+G** (Group) → назовите модель `ClickerStand`. В её свойствах поставьте ModelStreamingMode = **Persistent**.
+
+## Сборка через Rojo (удобно для VS Code)
+
+```bash
+rojo serve
+```
+В Studio подключитесь плагином Rojo. `default.project.json` уже раскладывает файлы по нужным местам
+и создаёт папку Remotes.
+
+## Тест
+
+- **Play** (F5): подойдите к стенду и кликайте по красной кнопке. Должны появиться «+1», искры
+ и звук, кнопка пружинит, цифры слева сверху растут.
+- Наберите 10 монет → **🛒 Магазин** → «Улучшить силу клика». Теперь за клик дают x2.
+- Купите «Автокликер»: каждые 5 сек появляется голубой «🤖 +X».
+- Сохранения: выйдите (Stop), снова Play, и прогресс должен остаться (нужен доступ к API, см. шаг 2).
+- Мультиплеер: **Test → Clients and Servers → 2 Players → Start**.
+
+## Настройка
+
+Всё меняется в `GameConfig`: цены (`BasePrice`, `PriceGrowth`), лимиты античита
+(`MinClickInterval`, `MaxClickDistance`), интервалы (`AutoClickInterval`, `AutoSaveInterval`),
+эффекты и звук (`Effects.ClickSoundId`: можно поставить любой `rbxassetid://` из Toolbox).
diff --git a/build.ps1 b/build.ps1
new file mode 100644
index 0000000..811abcd
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,103 @@
+# build.ps1 — собирает ClickerGame.rbxlx из папки src без Rojo.
+# Запуск: powershell -ExecutionPolicy Bypass -File build.ps1
+# Затем откройте ClickerGame.rbxlx двойным кликом (или File -> Open в Roblox Studio).
+
+$ErrorActionPreference = 'Stop'
+$root = $PSScriptRoot
+$outFile = Join-Path $root 'ClickerGame.rbxlx'
+$utf8 = New-Object System.Text.UTF8Encoding($false)
+
+$script:ref = 0
+function Next-Ref { $script:ref++; return "RBX$($script:ref)" }
+
+function Escape-Xml([string]$text) { return [System.Security.SecurityElement]::Escape($text) }
+
+# CDATA не может содержать "]]>" — разбиваем такие места
+function To-CData([string]$text) { return '', ']]]]>') + ']]>' }
+
+function Script-Item([string]$className, [string]$name, [string]$path) {
+ $source = [System.IO.File]::ReadAllText((Join-Path $root $path), $utf8)
+ return "- " +
+ "$(Escape-Xml $name)" +
+ "$(To-CData $source)" +
+ "
"
+}
+
+function Container([string]$className, [string]$name, [string[]]$children) {
+ return "- " +
+ "$(Escape-Xml $name)" +
+ ($children -join "`n") + "
"
+}
+
+function CFrame-Xml($x, $y, $z) {
+ return "$x$y$z" +
+ "100010" +
+ "001"
+}
+
+# Цвет в формате Color3uint8: 0xFFRRGGBB
+function Color-Xml($r, $g, $b) {
+ $value = [uint32]4278190080 + [uint32]($r * 65536 + $g * 256 + $b)
+ return "$value"
+}
+
+function Part-Item([string]$className, [string]$name, $pos, $size, $color, [int]$material) {
+ return "- " +
+ "$name" +
+ "true" +
+ (CFrame-Xml $pos[0] $pos[1] $pos[2]) +
+ "$($size[0])$($size[1])$($size[2])" +
+ (Color-Xml $color[0] $color[1] $color[2]) +
+ "$material" +
+ "00" +
+ "
"
+}
+
+# --- Workspace: земля и точка появления (стенд и декор строит MapBuilder при запуске) ---
+$workspace = Container 'Workspace' 'Workspace' @(
+ (Part-Item 'Part' 'Baseplate' @(0, -8, 0) @(512, 16, 512) @(91, 154, 76) 1280), # Grass
+ (Part-Item 'SpawnLocation' 'SpawnLocation' @(0, 0.5, 0) @(6, 1, 6) @(200, 200, 200) 256) # Plastic
+)
+
+# --- ReplicatedStorage ---
+$remotes = Container 'Folder' 'Remotes' @(
+ (Container 'RemoteEvent' 'ClickButton' @()),
+ (Container 'RemoteEvent' 'PurchaseUpgrade' @()),
+ (Container 'RemoteEvent' 'UpdateStats' @()),
+ (Container 'RemoteEvent' 'Notify' @())
+)
+$replicated = Container 'ReplicatedStorage' 'ReplicatedStorage' @(
+ (Script-Item 'ModuleScript' 'GameConfig' 'src/shared/GameConfig.luau'),
+ $remotes
+)
+
+# --- ServerScriptService ---
+$server = Container 'ServerScriptService' 'ServerScriptService' @(
+ (Script-Item 'ModuleScript' 'DataManager' 'src/server/DataManager.luau'),
+ (Script-Item 'Script' 'MapBuilder' 'src/server/MapBuilder.server.luau'),
+ (Script-Item 'Script' 'ClickHandler' 'src/server/ClickHandler.server.luau'),
+ (Script-Item 'Script' 'ShopHandler' 'src/server/ShopHandler.server.luau'),
+ (Script-Item 'Script' 'AutoClicker' 'src/server/AutoClicker.server.luau')
+)
+
+# --- StarterPlayer.StarterPlayerScripts ---
+$starterPlayer = Container 'StarterPlayer' 'StarterPlayer' @(
+ (Container 'StarterPlayerScripts' 'StarterPlayerScripts' @(
+ (Script-Item 'LocalScript' 'UIController' 'src/client/UIController.client.luau'),
+ (Script-Item 'LocalScript' 'ClickInput' 'src/client/ClickInput.client.luau')
+ ))
+)
+
+$xml = @"
+
+null
+nil
+$workspace
+$replicated
+$server
+$starterPlayer
+
+"@
+
+[System.IO.File]::WriteAllText($outFile, $xml, $utf8)
+Write-Host "Built: $outFile"
diff --git a/default.project.json b/default.project.json
new file mode 100644
index 0000000..8c1c7fe
--- /dev/null
+++ b/default.project.json
@@ -0,0 +1,26 @@
+{
+ "name": "ClickerGame",
+ "tree": {
+ "$className": "DataModel",
+ "ReplicatedStorage": {
+ "GameConfig": {
+ "$path": "src/shared/GameConfig.luau"
+ },
+ "Remotes": {
+ "$className": "Folder",
+ "ClickButton": { "$className": "RemoteEvent" },
+ "PurchaseUpgrade": { "$className": "RemoteEvent" },
+ "UpdateStats": { "$className": "RemoteEvent" },
+ "Notify": { "$className": "RemoteEvent" }
+ }
+ },
+ "ServerScriptService": {
+ "$path": "src/server"
+ },
+ "StarterPlayer": {
+ "StarterPlayerScripts": {
+ "$path": "src/client"
+ }
+ }
+ }
+}
diff --git a/src/client/ClickInput.client.luau b/src/client/ClickInput.client.luau
new file mode 100644
index 0000000..cebdf29
--- /dev/null
+++ b/src/client/ClickInput.client.luau
@@ -0,0 +1,137 @@
+-- ClickInput (LocalScript) — StarterPlayer.StarterPlayerScripts.ClickInput
+-- Ловит клик по кнопке, сразу проигрывает локальные эффекты (нажатие, звук,
+-- частицы) и сообщает серверу. Текст "+X" показывается только после
+-- подтверждения сервера — с реальной суммой, которую начислил сервер.
+
+local Players = game:GetService("Players")
+local ReplicatedStorage = game:GetService("ReplicatedStorage")
+local TweenService = game:GetService("TweenService")
+local SoundService = game:GetService("SoundService")
+local Debris = game:GetService("Debris")
+
+local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig"))
+local Effects = GameConfig.Effects
+local ClickRemote = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("ClickButton")
+
+local player = Players.LocalPlayer
+local playerGui = player:WaitForChild("PlayerGui")
+
+local stand = workspace:WaitForChild("ClickerStand")
+local button = stand:WaitForChild("ClickButton")
+local clickDetector = button:WaitForChild("ClickDetector")
+local particles = button:WaitForChild("ClickParticles", 5)
+
+-- Исходное положение и размер кнопки (анимация всегда возвращает к ним)
+local originalCFrame = button.CFrame
+local originalSize = button.Size
+
+-- Шаблон звука клика
+local clickSound = Instance.new("Sound")
+clickSound.Name = "ClickSound"
+clickSound.SoundId = Effects.ClickSoundId
+clickSound.Volume = Effects.ClickSoundVolume
+clickSound.Parent = SoundService
+
+------------------------------------------------------------------
+-- Эффекты
+------------------------------------------------------------------
+local pressTween, releaseTween
+
+-- Кнопка опускается и сплющивается, через ButtonPressTime "пружинит" обратно
+local function animatePress()
+ if pressTween then
+ pressTween:Cancel()
+ end
+ if releaseTween then
+ releaseTween:Cancel()
+ end
+
+ -- У повёрнутого цилиндра высота — это ось X размера
+ local pressedSize = Vector3.new(originalSize.X * 0.7, originalSize.Y * 1.08, originalSize.Z * 1.08)
+ pressTween = TweenService:Create(button, TweenInfo.new(Effects.ButtonPressTime, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
+ CFrame = originalCFrame - Vector3.new(0, Effects.ButtonPressDepth, 0),
+ Size = pressedSize,
+ })
+ releaseTween = TweenService:Create(button, TweenInfo.new(Effects.ButtonReleaseTime, Enum.EasingStyle.Back, Enum.EasingDirection.Out), {
+ CFrame = originalCFrame,
+ Size = originalSize,
+ })
+
+ local thisRelease = releaseTween
+ pressTween.Completed:Once(function(state)
+ if state == Enum.PlaybackState.Completed then
+ thisRelease:Play()
+ end
+ end)
+ pressTween:Play()
+end
+
+local function playClickSound()
+ local sound = clickSound:Clone()
+ sound.PlaybackSpeed = 0.95 + math.random() * 0.1 -- лёгкий разброс, чтобы не надоедало
+ sound.Parent = SoundService
+ sound:Play()
+ Debris:AddItem(sound, 2)
+end
+
+local function emitParticles()
+ if particles then
+ particles:Emit(Effects.ParticleCount)
+ end
+end
+
+-- Всплывающий "+X": летит вверх и растворяется
+local function showPopup(amount, isAuto)
+ local startOffset = Vector3.new((math.random() - 0.5) * 3, 1.5, (math.random() - 0.5) * 3)
+
+ local gui = Instance.new("BillboardGui")
+ gui.Name = "ClickPopup"
+ gui.Adornee = button
+ gui.Size = UDim2.fromOffset(160, 50)
+ gui.StudsOffsetWorldSpace = startOffset
+ gui.AlwaysOnTop = true
+ gui.LightInfluence = 0
+
+ local label = Instance.new("TextLabel")
+ label.Size = UDim2.fromScale(1, 1)
+ label.BackgroundTransparency = 1
+ label.Font = Enum.Font.FredokaOne
+ label.TextScaled = true
+ label.TextStrokeTransparency = 0
+ label.TextColor3 = if isAuto then Color3.fromRGB(110, 220, 255) else Color3.fromRGB(255, 220, 60)
+ label.Text = (if isAuto then "🤖 +" else "+") .. GameConfig.FormatNumber(amount)
+ label.Parent = gui
+
+ gui.Parent = playerGui
+
+ local info = TweenInfo.new(Effects.PopupDuration, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
+ TweenService:Create(gui, info, { StudsOffsetWorldSpace = startOffset + Vector3.new(0, Effects.PopupRise, 0) }):Play()
+ TweenService:Create(label, info, { TextTransparency = 1, TextStrokeTransparency = 1 }):Play()
+ Debris:AddItem(gui, Effects.PopupDuration + 0.1)
+end
+
+------------------------------------------------------------------
+-- Клик
+------------------------------------------------------------------
+local lastLocalClick = 0
+
+clickDetector.MouseClick:Connect(function()
+ -- Локальный лимит, чтобы не слать лишнего (сервер всё равно проверит сам)
+ local now = os.clock()
+ if now - lastLocalClick < GameConfig.MinClickInterval then
+ return
+ end
+ lastLocalClick = now
+
+ animatePress()
+ playClickSound()
+ emitParticles()
+ ClickRemote:FireServer()
+end)
+
+-- Сервер подтвердил начисление (обычный клик или автокликер)
+ClickRemote.OnClientEvent:Connect(function(amount, isAuto)
+ if typeof(amount) == "number" then
+ showPopup(amount, isAuto == true)
+ end
+end)
diff --git a/src/client/UIController.client.luau b/src/client/UIController.client.luau
new file mode 100644
index 0000000..7af1f32
--- /dev/null
+++ b/src/client/UIController.client.luau
@@ -0,0 +1,447 @@
+-- UIController (LocalScript) — StarterPlayer.StarterPlayerScripts.UIController
+-- Создаёт ScreenGui "ClickerUI" (статистика, магазин, уведомления) и обновляет его
+-- по данным с сервера. UI строится кодом, поэтому в StarterGui ничего
+-- настраивать руками не нужно.
+
+local Players = game:GetService("Players")
+local ReplicatedStorage = game:GetService("ReplicatedStorage")
+local TweenService = game:GetService("TweenService")
+
+local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig"))
+local Remotes = ReplicatedStorage:WaitForChild("Remotes")
+local UpdateStats = Remotes:WaitForChild("UpdateStats")
+local PurchaseUpgrade = Remotes:WaitForChild("PurchaseUpgrade")
+local Notify = Remotes:WaitForChild("Notify")
+
+local player = Players.LocalPlayer
+local playerGui = player:WaitForChild("PlayerGui")
+
+local COLORS = {
+ Panel = Color3.fromRGB(25, 25, 35),
+ Item = Color3.fromRGB(42, 42, 58),
+ Accent = Color3.fromRGB(255, 200, 40),
+ Buy = Color3.fromRGB(60, 180, 75),
+ Disabled = Color3.fromRGB(110, 110, 110),
+ Text = Color3.new(1, 1, 1),
+ SubText = Color3.fromRGB(190, 190, 205),
+ Success = Color3.fromRGB(50, 160, 70),
+ Error = Color3.fromRGB(200, 55, 55),
+ Info = Color3.fromRGB(60, 110, 200),
+}
+
+------------------------------------------------------------------
+-- Помощники для создания UI
+------------------------------------------------------------------
+local function create(className, props, children)
+ local instance = Instance.new(className)
+ for key, value in props or {} do
+ if key ~= "Parent" then
+ instance[key] = value
+ end
+ end
+ for _, child in children or {} do
+ child.Parent = instance
+ end
+ if props and props.Parent then
+ instance.Parent = props.Parent
+ end
+ return instance
+end
+
+local function corner(radius)
+ return create("UICorner", { CornerRadius = UDim.new(0, radius) })
+end
+
+local function padding(px)
+ return create("UIPadding", {
+ PaddingTop = UDim.new(0, px),
+ PaddingBottom = UDim.new(0, px),
+ PaddingLeft = UDim.new(0, px + 4),
+ PaddingRight = UDim.new(0, px + 4),
+ })
+end
+
+-- "Пульс" масштаба при изменении значения
+local function pop(guiObject, amount)
+ local scale = guiObject:FindFirstChildOfClass("UIScale")
+ if not scale then
+ return
+ end
+ scale.Scale = amount or 1.15
+ TweenService:Create(scale, TweenInfo.new(0.25, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Scale = 1 }):Play()
+end
+
+------------------------------------------------------------------
+-- ScreenGui
+------------------------------------------------------------------
+local screenGui = create("ScreenGui", {
+ Name = "ClickerUI",
+ ResetOnSpawn = false,
+ ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
+ Parent = playerGui,
+})
+
+------------------------------------------------------------------
+-- Левый верхний угол: статистика + кнопка магазина
+------------------------------------------------------------------
+local statsFrame = create("Frame", {
+ Name = "Stats",
+ Position = UDim2.fromOffset(12, 12),
+ Size = UDim2.fromOffset(250, 0),
+ AutomaticSize = Enum.AutomaticSize.Y,
+ BackgroundColor3 = COLORS.Panel,
+ BackgroundTransparency = 0.25,
+ Parent = screenGui,
+}, {
+ corner(12),
+ padding(8),
+ create("UIStroke", { Color = COLORS.Accent, Thickness = 2, Transparency = 0.3 }),
+ create("UIListLayout", { Padding = UDim.new(0, 4), SortOrder = Enum.SortOrder.LayoutOrder }),
+})
+
+local function makeStatLabel(name, order, color)
+ return create("TextLabel", {
+ Name = name,
+ LayoutOrder = order,
+ Size = UDim2.new(1, 0, 0, 32),
+ BackgroundTransparency = 1,
+ Font = Enum.Font.GothamBold,
+ TextSize = 24,
+ TextColor3 = color,
+ TextXAlignment = Enum.TextXAlignment.Left,
+ TextStrokeTransparency = 0.6,
+ Text = "",
+ Parent = statsFrame,
+ }, { create("UIScale") })
+end
+
+local coinsLabel = makeStatLabel("Coins", 1, COLORS.Accent)
+local clicksLabel = makeStatLabel("Clicks", 2, COLORS.Text)
+local multiplierLabel = makeStatLabel("Multiplier", 3, Color3.fromRGB(130, 210, 255))
+
+local shopButton = create("TextButton", {
+ Name = "ShopButton",
+ LayoutOrder = 4,
+ Size = UDim2.new(1, 0, 0, 42),
+ BackgroundColor3 = COLORS.Accent,
+ Font = Enum.Font.GothamBold,
+ TextSize = 22,
+ TextColor3 = COLORS.Panel,
+ Text = "🛒 Магазин",
+ Parent = statsFrame,
+}, { corner(10), create("UIScale") })
+
+------------------------------------------------------------------
+-- Плавные цифры: NumberValue твинится, а текст обновляется по Changed
+------------------------------------------------------------------
+local animatedStats = {}
+
+local function bindStat(statName, label, formatter)
+ local value = Instance.new("NumberValue")
+ value.Name = statName .. "Display"
+ value.Parent = script
+ value.Changed:Connect(function(v)
+ label.Text = formatter(v)
+ end)
+ label.Text = formatter(0)
+ animatedStats[statName] = { Value = value, Label = label, Target = nil }
+end
+
+bindStat("Coins", coinsLabel, function(v)
+ return "💰 Монеты: " .. GameConfig.FormatNumber(v)
+end)
+bindStat("Clicks", clicksLabel, function(v)
+ return "👆 Клики: " .. GameConfig.FormatNumber(v)
+end)
+bindStat("Multiplier", multiplierLabel, function(v)
+ return "⚡ x" .. GameConfig.FormatNumber(v)
+end)
+
+local function setStat(statName, newValue)
+ local stat = animatedStats[statName]
+ if stat.Target == newValue then
+ return
+ end
+ local isFirst = stat.Target == nil
+ stat.Target = newValue
+
+ if isFirst then
+ stat.Value.Value = newValue -- первую загрузку показываем сразу
+ return
+ end
+ TweenService:Create(stat.Value, TweenInfo.new(0.2, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), { Value = newValue }):Play()
+ pop(stat.Label)
+end
+
+------------------------------------------------------------------
+-- Магазин
+------------------------------------------------------------------
+local shopFrame = create("Frame", {
+ Name = "Shop",
+ AnchorPoint = Vector2.new(0.5, 0.5),
+ Position = UDim2.fromScale(0.5, 0.5),
+ Size = UDim2.fromScale(0.9, 0.7),
+ BackgroundColor3 = COLORS.Panel,
+ BackgroundTransparency = 0.05,
+ Visible = false,
+ Parent = screenGui,
+}, {
+ corner(16),
+ create("UIStroke", { Color = COLORS.Accent, Thickness = 2 }),
+ create("UISizeConstraint", { MaxSize = Vector2.new(460, 380) }),
+})
+local shopScale = create("UIScale", { Parent = shopFrame })
+
+create("TextLabel", {
+ Name = "Title",
+ Position = UDim2.fromOffset(16, 10),
+ Size = UDim2.new(1, -70, 0, 40),
+ BackgroundTransparency = 1,
+ Font = Enum.Font.GothamBold,
+ TextSize = 26,
+ TextColor3 = COLORS.Accent,
+ TextXAlignment = Enum.TextXAlignment.Left,
+ Text = "Магазин улучшений",
+ Parent = shopFrame,
+})
+
+local closeButton = create("TextButton", {
+ Name = "Close",
+ AnchorPoint = Vector2.new(1, 0),
+ Position = UDim2.new(1, -12, 0, 12),
+ Size = UDim2.fromOffset(36, 36),
+ BackgroundColor3 = COLORS.Error,
+ Font = Enum.Font.GothamBold,
+ TextSize = 20,
+ TextColor3 = COLORS.Text,
+ Text = "✕",
+ Parent = shopFrame,
+}, { corner(8) })
+
+local itemList = create("ScrollingFrame", {
+ Name = "Items",
+ Position = UDim2.fromOffset(16, 60),
+ Size = UDim2.new(1, -32, 1, -76),
+ BackgroundTransparency = 1,
+ BorderSizePixel = 0,
+ ScrollBarThickness = 6,
+ CanvasSize = UDim2.new(),
+ AutomaticCanvasSize = Enum.AutomaticSize.Y,
+ Parent = shopFrame,
+}, {
+ create("UIListLayout", { Padding = UDim.new(0, 10), SortOrder = Enum.SortOrder.LayoutOrder }),
+})
+
+-- Текст эффекта: "сейчас -> после покупки"
+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()
diff --git a/src/server/AutoClicker.server.luau b/src/server/AutoClicker.server.luau
new file mode 100644
index 0000000..e61b6dd
--- /dev/null
+++ b/src/server/AutoClicker.server.luau
@@ -0,0 +1,30 @@
+-- AutoClicker (Script) — ServerScriptService.AutoClicker
+-- Пассивный доход: каждые AutoClickInterval секунд добавляет игроку
+-- клики по уровню улучшения "Автокликер". Каждый авто-клик даёт Multiplier монет.
+
+local Players = game:GetService("Players")
+local ReplicatedStorage = game:GetService("ReplicatedStorage")
+
+local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig"))
+local DataManager = require(script.Parent:WaitForChild("DataManager"))
+
+local ClickRemote = DataManager.Remotes.ClickButton
+
+while true do
+ task.wait(GameConfig.AutoClickInterval)
+
+ for _, player in Players:GetPlayers() do
+ local data = DataManager.GetData(player)
+ if data then
+ local clicks = GameConfig.GetAutoClicks(data.Upgrades.AutoClicker or 0)
+ if clicks > 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
diff --git a/src/server/ClickHandler.server.luau b/src/server/ClickHandler.server.luau
new file mode 100644
index 0000000..62a0165
--- /dev/null
+++ b/src/server/ClickHandler.server.luau
@@ -0,0 +1,68 @@
+-- ClickHandler (Script) — ServerScriptService.ClickHandler
+-- Принимает клики от клиентов, проверяет их и начисляет монеты.
+-- Клиент присылает ТОЛЬКО факт клика — сколько начислить, решает сервер.
+
+local Players = game:GetService("Players")
+local ReplicatedStorage = game:GetService("ReplicatedStorage")
+
+local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig"))
+local DataManager = require(script.Parent:WaitForChild("DataManager"))
+
+local ClickRemote = DataManager.Remotes.ClickButton
+
+local stand = workspace:WaitForChild("ClickerStand")
+local button = stand:WaitForChild("ClickButton")
+local counterLabel = stand:WaitForChild("Platform"):WaitForChild("StandBillboard"):WaitForChild("Counter")
+
+local lastClickTime = {} -- [Player] = os.clock() последнего засчитанного клика
+local serverClicks = 0 -- все клики на этом сервере (для табло над стендом)
+
+local function updateBillboard()
+ counterLabel.Text = "Кликов на сервере: " .. GameConfig.FormatNumber(serverClicks)
+end
+updateBillboard()
+
+-- Игрок должен стоять рядом с кнопкой
+local function isNearButton(player)
+ local character = player.Character
+ local root = character and character:FindFirstChild("HumanoidRootPart")
+ if not root then
+ return false
+ end
+ return (root.Position - button.Position).Magnitude <= GameConfig.MaxClickDistance
+end
+
+ClickRemote.OnServerEvent:Connect(function(player)
+ -- Любые аргументы от клиента игнорируем
+ local data = DataManager.GetData(player)
+ if not data then
+ return -- данные ещё не загружены
+ end
+
+ -- Защита от спама / автокликеров-читов
+ local now = os.clock()
+ local last = lastClickTime[player]
+ if last and now - last < GameConfig.MinClickInterval then
+ return
+ end
+
+ if not isNearButton(player) then
+ return
+ end
+
+ lastClickTime[player] = now
+
+ local gain = data.Multiplier
+ data.Coins += gain
+ data.Clicks += 1
+
+ DataManager.SendStats(player)
+ ClickRemote:FireClient(player, gain, false) -- подтверждение для "+X" над кнопкой
+
+ serverClicks += 1
+ updateBillboard()
+end)
+
+Players.PlayerRemoving:Connect(function(player)
+ lastClickTime[player] = nil
+end)
diff --git a/src/server/DataManager.luau b/src/server/DataManager.luau
new file mode 100644
index 0000000..1abf777
--- /dev/null
+++ b/src/server/DataManager.luau
@@ -0,0 +1,293 @@
+-- DataManager (ModuleScript) — ServerScriptService.DataManager
+-- Загрузка, хранение в памяти и сохранение данных игроков через DataStoreService.
+-- Остальные серверные скрипты работают с данными ТОЛЬКО через этот модуль:
+-- DataManager.GetData(player) -> таблица данных или 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
diff --git a/src/server/MapBuilder.server.luau b/src/server/MapBuilder.server.luau
new file mode 100644
index 0000000..0a1c5b4
--- /dev/null
+++ b/src/server/MapBuilder.server.luau
@@ -0,0 +1,199 @@
+-- MapBuilder (Script) — ServerScriptService.MapBuilder
+-- Автоматически строит карту: Baseplate, точку появления, стенд с кнопкой и декор.
+-- Если в Workspace уже есть Model "ClickerStand" (например, вы собрали его
+-- вручную по инструкции из README) — стенд не создаётся заново.
+
+local GameConfig = require(game:GetService("ReplicatedStorage"):WaitForChild("GameConfig"))
+
+local STAND_POSITION = Vector3.new(0, 0, -14) -- центр стенда на земле (y = 0 — верх Baseplate)
+local VERTICAL = CFrame.Angles(0, 0, math.rad(90)) -- поворот цилиндра "стоя" (ось X -> вверх)
+
+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
diff --git a/src/server/ShopHandler.server.luau b/src/server/ShopHandler.server.luau
new file mode 100644
index 0000000..2f8043e
--- /dev/null
+++ b/src/server/ShopHandler.server.luau
@@ -0,0 +1,61 @@
+-- ShopHandler (Script) — ServerScriptService.ShopHandler
+-- Покупка улучшений. Цена, наличие денег и максимальный уровень
+-- проверяются на сервере — клиент присылает только id улучшения.
+
+local Players = game:GetService("Players")
+local ReplicatedStorage = game:GetService("ReplicatedStorage")
+
+local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig"))
+local DataManager = require(script.Parent:WaitForChild("DataManager"))
+
+local PurchaseRemote = DataManager.Remotes.PurchaseUpgrade
+
+local lastPurchaseTime = {} -- [Player] = os.clock()
+
+PurchaseRemote.OnServerEvent:Connect(function(player, upgradeId)
+ -- Проверяем тип аргумента и что такое улучшение существует
+ if typeof(upgradeId) ~= "string" then
+ return
+ end
+ local upgrade = GameConfig.Upgrades[upgradeId]
+ if not upgrade then
+ return
+ end
+
+ local data = DataManager.GetData(player)
+ if not data then
+ return
+ end
+
+ -- Анти-спам покупок
+ local now = os.clock()
+ local last = lastPurchaseTime[player]
+ if last and now - last < GameConfig.PurchaseCooldown then
+ return
+ end
+ lastPurchaseTime[player] = now
+
+ local level = data.Upgrades[upgradeId] or 0
+ if level >= 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)
diff --git a/src/shared/GameConfig.luau b/src/shared/GameConfig.luau
new file mode 100644
index 0000000..1c4f8e3
--- /dev/null
+++ b/src/shared/GameConfig.luau
@@ -0,0 +1,125 @@
+-- GameConfig (ModuleScript) — ReplicatedStorage.GameConfig
+-- Все настройки игры в одном месте. Меняйте значения здесь,
+-- чтобы настроить баланс, не трогая остальной код.
+-- Модуль общий: его читают и сервер, и клиент.
+
+local GameConfig = {}
+
+------------------------------------------------------------------
+-- Сохранения (DataStore)
+------------------------------------------------------------------
+-- Смените версию в имени, если хотите "обнулить" прогресс всех игроков
+GameConfig.DataStoreName = "ClickerData_v1"
+GameConfig.AutoSaveInterval = 60 -- автосейв, сек
+GameConfig.MaxRetries = 5 -- сколько раз повторять запрос к DataStore
+GameConfig.RetryDelay = 1 -- базовая задержка между повторами (растёт с каждой попыткой)
+
+-- Данные нового игрока
+GameConfig.DefaultData = {
+ Coins = 0,
+ Clicks = 0,
+ Multiplier = 1,
+ Upgrades = {
+ ClickPower = 0,
+ AutoClicker = 0,
+ },
+}
+
+------------------------------------------------------------------
+-- Клики и античит
+------------------------------------------------------------------
+GameConfig.BaseMultiplier = 1 -- сила клика без улучшений
+GameConfig.MinClickInterval = 0.05 -- минимум секунд между кликами (≈20 кликов/сек)
+GameConfig.MaxClickDistance = 25 -- макс. расстояние от игрока до кнопки (studs), проверяется на сервере
+GameConfig.ClickDetectorDistance = 20 -- MaxActivationDistance у ClickDetector
+GameConfig.PurchaseCooldown = 0.15 -- минимум секунд между покупками
+
+------------------------------------------------------------------
+-- Улучшения магазина
+-- Цена уровня = floor(BasePrice * PriceGrowth ^ текущий_уровень)
+------------------------------------------------------------------
+GameConfig.Upgrades = {
+ ClickPower = {
+ Order = 1, -- порядок в магазине
+ Name = "Улучшить силу клика",
+ Icon = "⚡",
+ BasePrice = 10,
+ PriceGrowth = 1.5,
+ MaxLevel = 200,
+ MultiplierPerLevel = 1, -- +1 к множителю за уровень
+ },
+ AutoClicker = {
+ Order = 2,
+ Name = "Автокликер",
+ Icon = "🤖",
+ BasePrice = 50,
+ PriceGrowth = 1.5,
+ MaxLevel = 100,
+ ClicksPerLevel = 1, -- авто-кликов за тик за каждый уровень
+ },
+}
+
+GameConfig.AutoClickInterval = 5 -- автокликер срабатывает каждые N секунд
+
+------------------------------------------------------------------
+-- Эффекты
+------------------------------------------------------------------
+GameConfig.Effects = {
+ -- Встроенный звук Roblox (есть всегда). Можно заменить на любой
+ -- звук из Toolbox, например "rbxassetid://1234567890"
+ ClickSoundId = "rbxasset://sounds/electronicpingshort.wav",
+ ClickSoundVolume = 0.5,
+ ParticleCount = 12, -- сколько частиц вылетает за клик
+ ButtonPressDepth = 0.4, -- насколько кнопка опускается (studs)
+ ButtonPressTime = 0.1, -- время нажатия, после него кнопка возвращается
+ ButtonReleaseTime = 0.3, -- время "пружинящего" возврата
+ PopupDuration = 0.9, -- время жизни текста "+X"
+ PopupRise = 4, -- на сколько studs текст "+X" улетает вверх
+}
+
+------------------------------------------------------------------
+-- Имена RemoteEvent'ов в ReplicatedStorage.Remotes
+------------------------------------------------------------------
+GameConfig.RemoteNames = { "ClickButton", "PurchaseUpgrade", "UpdateStats", "Notify" }
+
+------------------------------------------------------------------
+-- Формулы (используются и сервером, и клиентом)
+------------------------------------------------------------------
+
+-- Цена следующего уровня улучшения
+function GameConfig.GetUpgradePrice(upgradeId: string, level: number): number
+ local upgrade = GameConfig.Upgrades[upgradeId]
+ if not upgrade then
+ return math.huge
+ end
+ return math.floor(upgrade.BasePrice * upgrade.PriceGrowth ^ level)
+end
+
+-- Множитель клика по уровню "силы клика"
+function GameConfig.GetMultiplier(clickPowerLevel: number): number
+ return GameConfig.BaseMultiplier + clickPowerLevel * GameConfig.Upgrades.ClickPower.MultiplierPerLevel
+end
+
+-- Сколько кликов даёт автокликер за один тик
+function GameConfig.GetAutoClicks(autoClickerLevel: number): number
+ return autoClickerLevel * GameConfig.Upgrades.AutoClicker.ClicksPerLevel
+end
+
+-- Красивый вывод чисел: 950, 1.5K, 12.3M ...
+local SUFFIXES = { "", "K", "M", "B", "T", "Qa", "Qi" }
+function GameConfig.FormatNumber(n: number): string
+ n = math.floor(n)
+ if n < 1000 then
+ return tostring(n)
+ end
+ local index = 1
+ while n >= 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