ежедневная и крафты

This commit is contained in:
heyshawtyy committed 2026-11-19 13:46:05 +05:00
1 parent 828297cc6a
commit ce8184576e
31 files changed
+3371

No files matched your search

@@ -0,0 +1,618 @@
1→-- Economy + crafting settings of the ornament machine (shared by server and client).
2→-- Design: docs/economy_design.md. ONE resource: shards. A toy's worth = the shards the shredder gives for it.
3→-- Change numbers here, not in the logic.
4→local Config = {}
5→
6→---------------------------------------------------------------- admins (admin panel: AdminPanel / OrnamentAdminServer)
7→-- The game belongs to a group: every member of THAT group with rank >= ADMIN_GROUP.MinRank gets the panel
8→-- (group -> Configure -> Roles: the number next to a role is its rank; Owner = 255). Give the developers' role a
9→-- rank >= MinRank or lower MinRank to it. ADMIN_GROUP.Id = another group's id instead of the owning one.
10→-- ADMINS: extra single UserIds (anyone, also outside the group). In Studio every tester is an admin.
11→Config.ADMIN_GROUP = { MinRank = 254 }
12→Config.ADMINS = {
13→ [11925419606] = true,
14→}
15→
16→---------------------------------------------------------------- crafting grid
17→Config.GRID_SIZE = 4
18→Config.SLOT_COUNT = Config.GRID_SIZE * Config.GRID_SIZE
19→Config.MIN_SHARDS = 8 -- minimum CELLS in the grid (tier 1: 8 shards, tier 5: 8 x 2 = 16 shards)
20→Config.LUCK_PER_SHARD = 0.25 -- per extra cell: 8 cells = x1, 12 = x2, 16 = x3
21→Config.LUCK_TIER_EXP = 0.25 -- luck boosts higher rarities more: weight * luck^(k * (tier - 1))
22→
23→---------------------------------------------------------------- shards: free regeneration
24→Config.REGEN_SECONDS = 45 -- +1 shard every 45 s ...
25→Config.REGEN_CAP = 60 -- ... while the player has fewer than 60 (recycling can go above)
26→
27→-- TEST ONLY: every profile is topped up (once) to at least this many shards on load. nil = off (release).
28→Config.TEST_MIN_SHARDS = nil
29→
30→Config.STARTER = {
31→ Shards = 100, -- shards of a new player
32→ Boosters = { Luck2 = 2, Luck3 = 1 },
33→}
34→
35→---------------------------------------------------------------- rarities ("level" of a toy)
36→-- Shards = base worth of the rarity: what the shredder gives back (x toy multiplier x variant)
37→-- Xp = extra XP for rolling it
38→Config.RARITIES = {
39→ { Id = "Common", Name = "Common", Weight = 60, Shards = 2, Xp = 0, Color = Color3.fromRGB(205, 210, 220) },
40→ { Id = "Uncommon", Name = "Uncommon", Weight = 25, Shards = 4, Xp = 2, Color = Color3.fromRGB(95, 215, 115) },
41→ { Id = "Rare", Name = "Rare", Weight = 10, Shards = 9, Xp = 5, Color = Color3.fromRGB(75, 155, 255) },
42→ { Id = "Epic", Name = "Epic", Weight = 4, Shards = 22, Xp = 15, Color = Color3.fromRGB(180, 95, 255) },
43→ { Id = "Legendary", Name = "Legendary", Weight = 0.9, Shards = 70, Xp = 40, Color = Color3.fromRGB(255, 180, 45) },
44→ { Id = "Mythic", Name = "Mythic", Weight = 0.1, Shards = 300, Xp = 120, Color = Color3.fromRGB(255, 65, 95) },
45→}
46→-- a generated toy of these rarities is announced to everyone on the server
47→Config.ANNOUNCE_RARITIES = { Legendary = true, Mythic = true }
48→Config.RarityById = {}
49→for i, r in Config.RARITIES do
50→ r.Index = i
51→ Config.RarityById[r.Id] = r
52→end
53→
54→-- bad-luck protection: after N rolls without this tier (or better) the next roll is at least this tier
55→Config.PITY = {
56→ { Rarity = "Epic", Rolls = 40 },
57→ { Rarity = "Legendary", Rolls = 250 },
58→ { Rarity = "Mythic", Rolls = 1500 },
59→}
60→
61→-- rare variants on top of rarity (pure lottery, not affected by luck)
62→Config.VARIANTS = {
63→ { Id = "Golden", Name = "Golden", Chance = 1 / 1000, Mult = 10, Color = Color3.fromRGB(255, 205, 60) },
64→ { Id = "Shiny", Name = "Shiny", Chance = 1 / 50, Mult = 3, Color = Color3.fromRGB(170, 240, 255) },
65→ -- never rolled (Chance 0): only fusion gives it. Being a variant, it can not be fused again.
66→ { Id = "Fused", Name = "Fused", Chance = 0, Mult = 3, Color = Color3.fromRGB(255, 120, 220) },
67→}
68→Config.VariantById = {}
69→for _, v in Config.VARIANTS do Config.VariantById[v.Id] = v end
70→
71→Config.BOOSTERS = {
72→ Luck2 = { Name = "Luck x2", Luck = 2, Order = 1, Color = Color3.fromRGB(95, 215, 115) },
73→ Luck3 = { Name = "Luck x3", Luck = 3, Order = 2, Color = Color3.fromRGB(255, 180, 45) },
74→}
75→Config.BOOSTER_MIGRATE = { Luck5 = "Luck3" } -- old ids from the first prototype
76→
77→---------------------------------------------------------------- tiers ("farming levels") + toys
78→-- The generator works on ONE tier at a time (player picks it). Tier N+1 opens at player Level AND after
79→-- Need different toys of tier N were discovered (any rarity). Mult = value multiplier of its toys,
80→-- CellCost = shards per grid cell (min 8 cells: 8 / 10 / 12 / 14 / 16 shards). Add a tier = add a row + 50 toys.
81→Config.TOYS_PER_TIER = 50
82→Config.TIERS = {
83→ { Id = 1, Name = "Tier 1", Level = 1, Need = 0, Mult = 1, CellCost = 1, Color = Color3.fromRGB(120, 220, 140) },
84→ { Id = 2, Name = "Tier 2", Level = 12, Need = 20, Mult = 1.6, CellCost = 1.25, Color = Color3.fromRGB(90, 190, 255) },
85→ { Id = 3, Name = "Tier 3", Level = 20, Need = 25, Mult = 2.5, CellCost = 1.5, Color = Color3.fromRGB(190, 120, 255) },
86→ { Id = 4, Name = "Tier 4", Level = 30, Need = 30, Mult = 4, CellCost = 1.75, Color = Color3.fromRGB(255, 185, 60) },
87→ { Id = 5, Name = "Tier 5", Level = 40, Need = 35, Mult = 6, CellCost = 2, Color = Color3.fromRGB(255, 80, 110) },
88→}
89→Config.TOYS = {}
90→Config.ToyById = {}
91→Config.ToysByTier = {}
92→for i, row in require(script.Parent:WaitForChild("ToyCatalog")) do
93→ local tier = math.ceil(i / Config.TOYS_PER_TIER)
94→ if not Config.TIERS[tier] then break end
95→ local t = { Id = row[1], Name = row[2], Tier = tier, Index = i }
96→ Config.TOYS[i] = t
97→ Config.ToyById[t.Id] = t
98→ Config.ToysByTier[tier] = Config.ToysByTier[tier] or {}
99→ table.insert(Config.ToysByTier[tier], t)
100→end
101→
102→-- blinking pattern: every PATTERN_PERIOD seconds the generator flashes a reference pattern (same on server and
103→-- client: seeded by the period number of the server clock). Repeating it raises luck: match < MIN = x1,
104→-- full match = x PATTERN_MAX_LUCK (linear in between). The server accepts the current or previous period.
105→Config.PATTERN_PERIOD = 10
106→Config.PATTERN_CELLS = { 8, 12 }
107→Config.PATTERN_MIN_MATCH = 0.5
108→Config.PATTERN_MAX_LUCK = 1.5
109→
110→---------------------------------------------------------------- shredder
111→Config.MAX_ORNAMENTS = 300
112→Config.MAX_RECYCLE = 50
113→Config.BATCH_SIZE = 5 -- 5+ toys of the same kind in one run ...
114→Config.BATCH_BONUS = 0.2 -- ... give +20% shards for those toys
115→
116→---------------------------------------------------------------- player level
117→Config.MAX_LEVEL = 50
118→Config.XP = { Generate = 20, Recycle = 1, Discover = 25 }
119→function Config.XpToNext(level)
120→ return math.floor(25 * level ^ 1.5)
121→end
122→function Config.LevelReward(level)
123→ local r = { Shards = 15 + 5 * level, Boosters = {} }
124→ if level % 10 == 0 then
125→ r.Boosters.Luck3 = 1
126→ elseif level % 5 == 0 then
127→ r.Boosters.Luck2 = 1
128→ end
129→ return r
130→end
131→
132→---------------------------------------------------------------- phase 2: workshop (all paid in shards)
133→-- upgrades: cost of the next level = floor(Base * Growth ^ currentLevel)
134→Config.UPGRADES = {
135→ { Id = "Luck", Name = "Generator Luck", Max = 10, Base = 40, Growth = 1.6, Step = 0.08,
136→ Desc = "+8% luck on every generation" },
137→ { Id = "Regen", Name = "Shard Regen", Max = 10, Base = 30, Growth = 1.6, Step = 6,
138→ Desc = "+6 regen cap and 5% faster regen" },
139→ { Id = "Shredder", Name = "Shredder Power", Max = 10, Base = 50, Growth = 1.6, Step = 0.05,
140→ Desc = "+5% shards from recycling" },
141→ { Id = "Storage", Name = "Toy Storage", Max = 8, Base = 25, Growth = 1.6, Step = 50,
142→ Desc = "+50 inventory slots" },
143→}
144→Config.UpgradeById = {}
145→for i, u in Config.UPGRADES do
146→ u.Order = i
147→ Config.UpgradeById[u.Id] = u
148→end
149→function Config.UpgradeCost(id, level)
150→ local u = Config.UpgradeById[id]
151→ if not u or level >= u.Max then return nil end
152→ return math.floor(u.Base * u.Growth ^ level)
153→end
154→function Config.LuckMult(level) return 1 + Config.UpgradeById.Luck.Step * (level or 0) end
155→function Config.RegenCap(level) return Config.REGEN_CAP + Config.UpgradeById.Regen.Step * (level or 0) end
156→function Config.RegenSeconds(level) return Config.REGEN_SECONDS * (0.95 ^ (level or 0)) end
157→function Config.ShredderMult(level) return 1 + Config.UpgradeById.Shredder.Step * (level or 0) end
158→function Config.StorageCap(level) return Config.MAX_ORNAMENTS + Config.UpgradeById.Storage.Step * (level or 0) end
159→
160→-- fusion: FUSION_COUNT identical toys (same kind + rarity, no special variant) + shards -> 1 "Fused" toy one rarity
161→-- higher (variant Mult x4). Worth a bit MORE than its inputs (Ball: 5x2 + 4 = 14 -> 16, Rare 5x9 + 30 = 75 -> 88),
162→-- and a Fused toy is a variant, so it can never be fused again (no chain up to Mythic).
163→-- NEW: the result is a random toy of the NEXT tier with the same rarity (tag Fused). On the last tier the rarity
164→-- goes up instead. Fee = FUSION_COST[rarity] x tier Mult. Fused toys can be sold instantly on the market for
165→-- QUICK_SELL x the shards spent on them (Cost).
166→Config.FUSION_COUNT = 5
167→Config.FUSION_COST = { Common = 4, Uncommon = 10, Rare = 30, Epic = 120, Legendary = 600, Mythic = 2500 }
168→Config.QUICK_SELL = 1.01
169→Config.XP.Fuse = 10
170→
171→-- booster recipes
172→Config.BOOSTER_COST = { Luck2 = 60, Luck3 = 150 }
173→
174→---------------------------------------------------------------- phase 3: trading
175→Config.TRADE = {
176→ MIN_LEVEL = 5, -- both players
177→ MAX_ITEMS = 8, -- toys per side
178→ TAX = 0.05, -- shards passed in a trade lose 5% (sink)
179→ MIN_AGE = 600, -- toys younger than 10 minutes can not be traded (anti-dupe after a crash)
180→ COUNTDOWN = 5, -- seconds between "both ready" and "confirm"
181→ REQUEST_TTL = 15, -- seconds to accept a request
182→ COOLDOWN = 10, -- seconds between two trades of one player
183→ PER_HOUR = 20, -- trades per player per hour
184→ WARN_RATIO = 3, -- warn when one side is worth more than 3x the other
185→}
186→
187→---------------------------------------------------------------- phase 5: cross-server market
188→Config.MARKET = {
189→ MIN_LEVEL = 10, -- to list or buy
190→ MAX_LISTINGS = 10, -- active listings per player
191→ TAX = 0.10, -- the seller gets the price minus 10% (sink)
192→ DURATION = 3 * 24 * 3600, -- a listing lives 3 days, then the toy goes back to the seller
193→ MAX_PRICE = 1000000,
194→ PAGE = 60, -- listings shown per browse request
195→ -- NPC seller: keeps the market from looking empty. Its lots live only on this server (not in MemoryStore),
196→ -- fill the gap up to TARGET real+bot lots and give way to players as they list. Price is always above the
197→ -- shredder value (MARKUP x Value), so buying from the bot and shredding is never profitable.
198→ BOT = {
199→ TARGET = 14, -- visible lots the market aims for (real + bot)
200→ RESTOCK = 20, -- seconds between bot updates (one lot added/removed per tick)
201→ LIFE = { 10 * 60, 35 * 60 }, -- a bot lot lives this long (seconds), then disappears
202→ MARKUP = { 1.8, 3.2 }, -- price = shredder value x random markup
203→ RARITY = { Common = 42, Uncommon = 30, Rare = 18, Epic = 8, Legendary = 2 },
204→ TIER = { 55, 25, 12, 6, 2 }, -- weights of the tiers of bot lots
205→ SHINY = 0.04, -- chance of a Shiny variant
206→ NAMES = { "Santa's Stall", "Elf Trader", "Gingerbread Gnome", "Bob the Snowman", "Snow Maiden's Stall" },
207→ },
208→}
209→-- minimum price = what the shredder would pay (no point in selling cheaper)
210→function Config.MinPrice(item) return math.max(1, Config.Value(item)) end
211→
212→---------------------------------------------------------------- shop: decorations for the player's plot (paid in shards)
213→-- Model = ReplicatedStorage.OrnamentMachine.Decor/<Model>; Offset = position on the plot (plot space, +Z = front)
214→Config.SHOP = {
215→ { Id = "Tree", Name = "Christmas Tree", Price = 400, Model = "ChristmasTree", Offset = CFrame.new(-9, 0, -7),
216→ Desc = "A tall fluffy tree. Decorate it with your ornaments." },
217→ { Id = "PullUpBar", Name = "Pull-up Bar", Price = 150, Model = "PullUpBar", Offset = CFrame.new(9, 0, -8),
218→ Desc = "XP for every pull-up, +1 shard per 10 in a row. Up to 60 per set, then a 10 min rest." },
219→ { Id = "Bench", Name = "Bench Press", Price = 250, Model = "BenchPress", Offset = CFrame.new(9, 0, 4) * CFrame.Angles(0, math.rad(-90), 0),
220→ Desc = "A press bench and a loaded barbell." },
221→ { Id = "Fireworks", Name = "Fireworks", Price = 200, Model = "Fireworks", Offset = CFrame.new(-9, 0, 7),
222→ Desc = "A fireworks launcher. Walk up and launch it — everyone will see the show." },
223→ -- OnTree: not placed on the plot but strung on the player's placed tree by clicking points on it
224→ -- (Config.GARLAND limits; no footprint, follows the tree when it is moved, comes off when the tree is stored)
225→ { Id = "Garland", Name = "Tree Garland", Price = 250, Model = "TreeGarland", OnTree = true, Offset = CFrame.new(),
226→ Desc = "Colorful lights. Wrap the tree yourself — click on it point by point." },
227→ -- Craft: not sold in the shop, made in the Craft House (Config.CRAFTS). AroundTree: may stand centred on the tree
228→ -- (the ring goes round the trunk) — the only allowed overlap.
229→ { Id = "Train", Name = "Christmas Train", Price = 0, Model = "ChristmasTrain", Craft = true, AroundTree = true, Offset = CFrame.new(),
230→ Half = { 6.3, 6.3 }, -- footprint of the round track (the mesh boxes overestimate it)
231→ Desc = "A little steam train that runs round its track. Put it around your tree!" },
232→}
233→-- garland: the player clicks points on the tree, the wire goes through them (points stored in tree space)
234→Config.GARLAND = {
235→ MAX_POINTS = 60, -- clicks per garland
236→ MAX_LENGTH = 120, -- studs of wire
237→ BULB_STEP = 1.1, -- a bulb every N studs
238→ MAX_LIGHTS = 24, -- PointLights per garland (every 4th bulb)
239→ BOUNDS = { X = 7, YMIN = 0, YMAX = 27, Z = 7 }, -- points must be on / near the tree
240→}
241→Config.ShopById = {}
242→for k, it in Config.SHOP do it.Order = k; Config.ShopById[it.Id] = it end
243→
244→---------------------------------------------------------------- Craft House: plot items made from toys
245→-- (the UI groups lines of the same tier + rarity into one row)
246→-- Recipe line = one specific toy (Toy id) of a rarity, any variant (without Toy: any toy of that tier). The server takes the cheapest fitting
247→-- toys (by shredder value) that are not on the tree. Unlimited crafts: one stands on the plot, the rest wait in
248→-- the inventory or are sold on the market (min price = Value = the shredder value of the ingredients).
249→Config.CRAFTS = {
250→ { Id = "Train", Name = "Christmas Train", Icon = "🚂", Xp = 60,
251→ Desc = "A steam engine with two gift wagons. It runs round its track — put it around your Christmas tree!",
252→ Recipe = {
253→ { Toy = "001", Tier = 1, Rarity = "Epic", Count = 1 }, -- Red Bauble
254→ { Toy = "006", Tier = 1, Rarity = "Epic", Count = 1 }, -- Gold Star
255→ { Toy = "017", Tier = 1, Rarity = "Epic", Count = 1 }, -- Red Gift
256→ { Toy = "075", Tier = 2, Rarity = "Epic", Count = 1 }, -- Green Train
257→ { Toy = "059", Tier = 2, Rarity = "Epic", Count = 1 }, -- Green Gift
258→ { Toy = "030", Tier = 1, Rarity = "Legendary", Count = 1 }, -- Toy Train
259→ { Toy = "095", Tier = 2, Rarity = "Legendary", Count = 1 }, -- Sled
260→ } },
261→}
262→Config.CraftById = {}
263→for k, c in Config.CRAFTS do
264→ c.Order = k
265→ local v = 0
266→ for _, ing in c.Recipe do
267→ v += Config.RarityById[ing.Rarity].Shards * Config.TIERS[ing.Tier].Mult * ing.Count
268→ end
269→ c.Value = math.floor(v + 0.5)
270→ Config.CraftById[c.Id] = c
271→end
272→-- does a toy (item = { Toy, Rarity }) fit a recipe line?
273→function Config.CraftFits(ing, item)
274→ local t = Config.ToyById[item.Toy]
275→ if ing.Toy and item.Toy ~= ing.Toy then return false end
276→ return t ~= nil and t.Tier == ing.Tier and item.Rarity == ing.Rarity
277→end
278→-- picks the toys for a craft from `items` = { { uid, Toy, Rarity, Variant, OnTree } }: cheapest first, never toys
279→-- on the tree. Returns { [lineIndex] = { item, ... } }, complete (true when every line is filled)
280→function Config.CraftPick(craftId, items)
281→ local c = Config.CraftById[craftId]
282→ if not c then return {}, false end
283→ local used, out, complete = {}, {}, true
284→ for i, ing in c.Recipe do
285→ local list = {}
286→ for _, it in items do
287→ if not it.OnTree and not used[it.uid] and Config.CraftFits(ing, it) then table.insert(list, it) end
288→ end
289→ table.sort(list, function(a, b)
290→ local va, vb = Config.Value(a), Config.Value(b)
291→ if va ~= vb then return va < vb end
292→ return (tonumber(a.uid) or 0) < (tonumber(b.uid) or 0)
293→ end)
294→ out[i] = {}
295→ for k = 1, math.min(ing.Count, #list) do
296→ used[list[k].uid] = true
297→ table.insert(out[i], list[k])
298→ end
299→ if #out[i] < ing.Count then complete = false end
300→ end
301→ return out, complete
302→end
303→Config.FIREWORKS_COOLDOWN = 15
304→-- pull-up bar: one rep every RepSeconds gives XpPerRep experience (XP / level rewards like the generator);
305→-- every ShardEvery reps in a row (one session on the bar, without getting off) give ShardReward shards
306→-- MaxReps per session; after reaching it the bar is locked for that player for RestSeconds
307→Config.PULLUP = { RepSeconds = 1.6, XpPerRep = 1, ShardEvery = 10, ShardReward = 1, MaxReps = 60, RestSeconds = 600 }
308→-- placement on the plot (shared by server validation and the client's ghost preview)
309→-- half extents (x, z) of a decoration around its pivot, from the template in OrnamentMachine.Decor
310→local halfCache = {}
311→function Config.DecorHalf(id)
312→ if halfCache[id] then return halfCache[id][1], halfCache[id][2] end
313→ local item = Config.ShopById[id]
314→ if item and item.Half then return item.Half[1], item.Half[2] end
315→ local decor = script.Parent and script.Parent:FindFirstChild("Decor")
316→ local tpl = item and decor and decor:FindFirstChild(item.Model)
317→ if not tpl then return 2, 2 end
318→ local pivot = tpl:GetPivot()
319→ local hx, hz = 0.5, 0.5
320→ for _, p in tpl:GetDescendants() do
321→ if p:IsA("BasePart") and p.Name ~= "Base" then
322→ local cf = pivot:ToObjectSpace(p.CFrame)
323→ local s = p.Size
324→ local ex = math.abs(cf.RightVector.X) * s.X + math.abs(cf.UpVector.X) * s.Y + math.abs(cf.LookVector.X) * s.Z
325→ local ez = math.abs(cf.RightVector.Z) * s.X + math.abs(cf.UpVector.Z) * s.Y + math.abs(cf.LookVector.Z) * s.Z
326→ hx = math.max(hx, math.abs(cf.X) + ex / 2)
327→ hz = math.max(hz, math.abs(cf.Z) + ez / 2)
328→ end
329→ end
330→ halfCache[id] = { hx, hz }
331→ return hx, hz
332→end
333→
334→-- footprint half extents for a rotation step r (0..3 = 0/90/180/270 degrees)
335→function Config.DecorFootprint(id, r)
336→ local hx, hz = Config.DecorHalf(id)
337→ if (r or 0) % 2 == 1 then return hz, hx end
338→ return hx, hz
339→end
340→
341→-- can `id` stand at plot-space (x, z) with rotation r? placements = { [otherId] = { X, Z, R } }
342→-- AroundTree items (the train) may stand exactly centred on the tree: the ring goes round the trunk
343→function Config.AroundTreeOk(a, ax, az, b, bx, bz)
344→ local A, B = Config.ShopById[a], Config.ShopById[b]
345→ local pair = (A and A.AroundTree and b == "Tree") or (B and B.AroundTree and a == "Tree")
346→ return pair and math.abs(ax - bx) <= 0.5 and math.abs(az - bz) <= 0.5
347→end
348→-- placement area of a plot (plot space, x / z): the fenced plot itself + the snowy pad in front of the owner's name
349→-- board (NameBoard at x 12.7, z 19.9, facing +z). The SAME area on every plot: zones are handed out at random and
350→-- placements are saved in plot space, so a spot must be free on every zone. The pad stops at z 39.5 because zones 4
351→-- and 10 have a prebuilt house (shop / Craft House) further up their pad (house front at z ~41).
352→Config.PLOT_MARGIN = 0.25
353→Config.PLOT_PAD = { { 6.5, 21 }, { 28, 21 }, { 33.5, 30 }, { 31.5, 37 }, { 29.3, 39.5 }, { 6.5, 39.5 } }
354→function Config.PlotPad() return Config.PLOT_PAD end
355→local function inPolygon(poly, x, z)
356→ local inside, j = false, #poly
357→ for i = 1, #poly do
358→ local xi, zi, xj, zj = poly[i][1], poly[i][2], poly[j][1], poly[j][2]
359→ if (zi > z) ~= (zj > z) and x < (xj - xi) * (z - zi) / (zj - zi) + xi then inside = not inside end
360→ j = i
361→ end
362→ return inside
363→end
364→-- plot = the plot part or its Size
365→function Config.InPlotArea(plot, x, z)
366→ local size = typeof(plot) == "Instance" and plot.Size or plot
367→ local m = Config.PLOT_MARGIN
368→ if math.abs(x) <= size.X / 2 - m and math.abs(z) <= size.Z / 2 - m then return true end
369→ return inPolygon(Config.PLOT_PAD, x, z)
370→end
371→-- is the whole footprint (centre x, z, half extents fx, fz) inside the area? Samples the rectangle every ~1 stud
372→-- (edges + inside), so it can't straddle the gap between the plot and the pad.
373→function Config.FootprintInArea(plot, x, z, fx, fz)
374→ local nx, nz = math.max(1, math.ceil(fx * 2)), math.max(1, math.ceil(fz * 2))
375→ for i = 0, nx do
376→ for k = 0, nz do
377→ if not Config.InPlotArea(plot, x - fx + 2 * fx * i / nx, z - fz + 2 * fz * k / nz) then return false end
378→ end
379→ end
380→ return true
381→end
382→-- plot = the plot part or its Size
383→function Config.DecorFits(plot, placements, id, x, z, r)
384→ if Config.ShopById[id] and Config.ShopById[id].OnTree then return true end -- lives on the tree
385→ local fx, fz = Config.DecorFootprint(id, r)
386→ if not Config.FootprintInArea(plot, x, z, fx, fz) then
387→ return false, "Only inside the green area"
388→ end
389→ for other, pl in placements do
390→ if other ~= id and type(pl) == "table" and not (Config.ShopById[other] and Config.ShopById[other].OnTree)
391→ and not Config.AroundTreeOk(id, x, z, other, pl.X, pl.Z) then
392→ local ox, oz = Config.DecorFootprint(other, pl.R)
393→ if math.abs(x - pl.X) < fx + ox and math.abs(z - pl.Z) < fz + oz then
394→ return false, "Blocked by: " .. Config.ShopById[other].Name
395→ end
396→ end
397→ end
398→ return true
399→end
400→
401→---------------------------------------------------------------- premium shop (Robux, Developer Products)
402→-- ProductId = the Developer Product id from the Creator Dashboard (0 = not set up yet: the card shows "скоро").
403→-- Robux = fallback price only: the client shows the player's regional price from GetProductInfo (managed pricing).
404→-- Robux is only shown in the UI; the real price is the one set on the product itself.
405→Config.PREMIUM = {
406→ { Id = "Shards100", Kind = "Shards", Amount = 100, Name = "Handful of Shards", Robux = 30, ProductId = 3732431258 },
407→ { Id = "Shards500", Kind = "Shards", Amount = 500, Name = "Bag of Shards", Robux = 132, ProductId = 3732431774, Tag = "+25% value" },
408→ { Id = "Shards1200", Kind = "Shards", Amount = 1200, Name = "Chest of Shards", Robux = 271, ProductId = 3732432053, Tag = "+50% value" },
409→ { Id = "Shards3000", Kind = "Shards", Amount = 3000, Name = "Mountain of Shards", Robux = 620, ProductId = 3732432975, Tag = "best value" },
410→ { Id = "Luck2x3", Kind = "Booster", Booster = "Luck2", Amount = 3, Name = "3 × Luck x2", Robux = 63, ProductId = 3732434260 },
411→ { Id = "Luck3x3", Kind = "Booster", Booster = "Luck3", Amount = 3, Name = "3 × Luck x3", Robux = 132, ProductId = 3732434667 },
412→}
413→Config.PremiumById, Config.PremiumByProduct = {}, {}
414→for k, p in Config.PREMIUM do
415→ p.Order = k
416→ Config.PremiumById[p.Id] = p
417→ if p.ProductId ~= 0 then Config.PremiumByProduct[p.ProductId] = p end
418→end
419→
420→---------------------------------------------------------------- promo codes (OrnamentPromo, admin panel)
421→-- Codes are created in the admin panel and redeemed in Settings -> Codes. Everything is checked on the server.
422→Config.PROMO = {
423→ TRIES = 3, WINDOW = 300, -- a player may submit at most 3 codes per 5 minutes (any result counts)
424→ MAX_LEN = 20, -- code: 3..20 of A-Z 0-9 _ - (case-insensitive, stored in upper case)
425→ MAX_USES = 1000000,
426→ MAX_SHARDS = 1000000,
427→ MAX_BOOSTERS = 100,
428→}
429→
430→---------------------------------------------------------------- VIP game pass
431→-- PassId = the VIP Game Pass id from the Creator Dashboard (0 = not set up yet: nobody is VIP outside Studio tests).
432→-- The server sets the player attribute "VIP" = true; every bonus below is permanent while the pass is owned.
433→Config.VIP = {
434→ PassId = 2089673529,
435→ Price = 1000, -- fallback price only: the shop shows the regional price from GetProductInfo
436→ Luck = 1.5, -- generator luck multiplier (stacks with everything else)
437→ Shredder = 1.25, -- shards from the shredder
438→ XP = 1.5, -- all experience
439→}
440→function Config.VipMult(isVip, key) return isVip and Config.VIP[key] or 1 end
441→
442→---------------------------------------------------------------- formulas
443→-- luckLevel = the player's "Удача генератора" upgrade level
444→-- cells = filled grid cells, patternMult = Config.PatternLuck(match)
445→function Config.Luck(cells, boosterId, luckLevel, patternMult, isVip)
446→ if cells < Config.MIN_SHARDS then return 0 end
447→ local luck = (1 + (cells - Config.MIN_SHARDS) * Config.LUCK_PER_SHARD) * Config.LuckMult(luckLevel) * (patternMult or 1) * Config.VipMult(isVip, "Luck")
448→ local b = boosterId and Config.BOOSTERS[boosterId]
449→ if b then luck *= b.Luck end
450→ return luck
451→end
452→
453→-- shards for `cells` grid cells on a tier
454→function Config.GenCost(cells, tier)
455→ local t = Config.TIERS[tier] or Config.TIERS[1]
456→ return math.max(0, math.ceil(cells * t.CellCost - 1e-6))
457→end
458→
459→-- tiers: number of different toys of `tier` in a Discovered set ({ ["Toy|Rarity"] = true })
460→function Config.TierFound(discovered, tier)
461→ local seen, n = {}, 0
462→ for key in discovered or {} do
463→ local t = Config.ToyById[(tostring(key):match("^([^|]+)"))]
464→ if t and t.Tier == tier and not seen[t.Id] then seen[t.Id] = true; n += 1 end
465→ end
466→ return n
467→end
468→-- highest tier the player can generate
469→function Config.MaxTier(level, discovered)
470→ local max = 1
471→ for i = 2, #Config.TIERS do
472→ local t = Config.TIERS[i]
473→ if (level or 1) >= t.Level and Config.TierFound(discovered, i - 1) >= t.Need then max = i else break end
474→ end
475→ return max
476→end
477→
478→-- reference pattern of a period (16-char "0101.." mask)
479→function Config.PatternPeriod(serverTime) return math.floor(serverTime / Config.PATTERN_PERIOD) end
480→function Config.PatternAt(period)
481→ local r = Random.new(period * 7919 + 104729)
482→ local n = r:NextInteger(Config.PATTERN_CELLS[1], Config.PATTERN_CELLS[2])
483→ local cells = {}
484→ for i = 1, Config.SLOT_COUNT do cells[i] = i end
485→ local on = table.create(Config.SLOT_COUNT, "0")
486→ for k = 1, n do
487→ local j = r:NextInteger(k, Config.SLOT_COUNT)
488→ cells[k], cells[j] = cells[j], cells[k]
489→ on[cells[k]] = "1"
490→ end
491→ return table.concat(on)
492→end
493→function Config.Similarity(a, b)
494→ local inter, union = 0, 0
495→ for i = 1, math.min(#a, #b) do
496→ local x, y = a:sub(i, i) == "1", b:sub(i, i) == "1"
497→ if x and y then inter += 1 end
498→ if x or y then union += 1 end
499→ end
500→ return union == 0 and 0 or inter / union
501→end
502→function Config.PatternLuck(match)
503→ if match < Config.PATTERN_MIN_MATCH then return 1 end
504→ return 1 + (Config.PATTERN_MAX_LUCK - 1) * (match - Config.PATTERN_MIN_MATCH) / (1 - Config.PATTERN_MIN_MATCH)
505→end
506→-- best match of a grid against the pattern of this or the previous period
507→function Config.PatternMatch(slots, serverTime)
508→ local p = Config.PatternPeriod(serverTime)
509→ return math.max(Config.Similarity(slots, Config.PatternAt(p)), Config.Similarity(slots, Config.PatternAt(p - 1)))
510→end
511→
512→function Config.Chances(luck)
513→ luck = math.max(luck or 1, 1)
514→ local w, total = {}, 0
515→ for i, r in Config.RARITIES do
516→ w[i] = r.Weight * luck ^ (Config.LUCK_TIER_EXP * (i - 1))
517→ total += w[i]
518→ end
519→ for i in w do w[i] /= total end
520→ return w
521→end
522→
523→-- rolls a rarity; minIndex (pity) forces at least that tier (re-normalised over the allowed tiers)
524→function Config.Roll(luck, rng, minIndex)
525→ minIndex = minIndex or 1
526→ local ch = Config.Chances(luck)
527→ local total = 0
528→ for i = minIndex, #ch do total += ch[i] end
529→ local x = (rng or Random.new()):NextNumber() * total
530→ local acc = 0
531→ for i = minIndex, #ch do
532→ acc += ch[i]
533→ if x <= acc then return Config.RARITIES[i] end
534→ end
535→ return Config.RARITIES[#ch]
536→end
537→
538→function Config.RollVariant(rng)
539→ local x = (rng or Random.new()):NextNumber()
540→ local acc = 0
541→ for _, v in Config.VARIANTS do
542→ acc += v.Chance
543→ if x <= acc then return v end
544→ end
545→ return nil
546→end
547→
548→-- a random toy of a tier (all 50 equally likely)
549→function Config.RollToy(tier, rng)
550→ local list = Config.ToysByTier[tier] or Config.ToysByTier[1]
551→ return list[(rng or Random.new()):NextInteger(1, #list)]
552→end
553→
554→-- fusion of 5 x (toy, rarity): fee, result tier, result rarity (nil = can not be fused)
555→function Config.FusionInfo(toyId, rarityId)
556→ local t, r = Config.ToyById[toyId], Config.RarityById[rarityId]
557→ if not t or not r then return nil end
558→ local tier, rarity = t.Tier + 1, r
559→ if not Config.TIERS[tier] then
560→ tier, rarity = t.Tier, Config.RARITIES[r.Index + 1]
561→ if not rarity then return nil end
562→ end
563→ local fee = math.floor(Config.FUSION_COST[r.Id] * Config.TIERS[t.Tier].Mult + 0.5)
564→ return fee, tier, rarity
565→end
566→
567→-- instant system buyout on the market (Fused toys only): shards spent on it + 1%
568→function Config.QuickSellPrice(item)
569→ if item.Variant ~= "Fused" or type(item.Cost) ~= "number" or item.Cost <= 0 then return nil end
570→ return math.ceil(item.Cost * Config.QUICK_SELL)
571→end
572→
573→function Config.ToyTier(toyId)
574→ local t = Config.ToyById[toyId]
575→ return t and Config.TIERS[t.Tier]
576→end
577→
578→-- shards one toy is worth (item = { Toy, Rarity, Variant }); the shredder pays exactly this
579→function Config.Value(item)
580→ if item.Craft then
581→ local c = Config.CraftById[item.Craft]
582→ return c and c.Value or 0
583→ end
584→ local r, t = Config.RarityById[item.Rarity], Config.ToyById[item.Toy]
585→ if not r or not t then return 0 end
586→ local v = item.Variant and Config.VariantById[item.Variant]
587→ return math.max(1, math.floor(r.Shards * Config.TIERS[t.Tier].Mult * (v and v.Mult or 1) + 0.5))
588→end
589→
590→-- shredder output for a list of items (5+ toys of the same kind in one run get the batch bonus);
591→-- shredderLevel = the player's "Мощность шредера" upgrade level
592→function Config.RecycleYield(items, shredderLevel, isVip)
593→ local perToy = {}
594→ -- "same kind" = same tier
595→ local function kind(it) local t = Config.ToyById[it.Toy]; return t and t.Tier or 0 end
596→ for _, it in items do perToy[kind(it)] = (perToy[kind(it)] or 0) + 1 end
597→ local shards = 0
598→ for _, it in items do
599→ local s = Config.Value(it)
600→ if perToy[kind(it)] >= Config.BATCH_SIZE then s *= 1 + Config.BATCH_BONUS end
601→ shards += s
602→ end
603→ return math.floor(shards * Config.ShredderMult(shredderLevel) * Config.VipMult(isVip, "Shredder") + 0.5)
604→end
605→
606→-- Discord community reward (OrnamentDiscordServer + DiscordWindow). Fill GuildId and Invite after publishing.
607→-- The RoVer API key is NEVER stored here: put it into Creator Dashboard -> experience -> Secrets as "RoVerApiKey"
608→-- (domain registry.rover.link). The server checks "joined the server + verified with RoVer" through the RoVer API.
609→Config.DISCORD = {
610→ GuildId = "1571845376296886322", -- Discord server id (Discord: Developer Mode -> right-click the server -> Copy Server ID)
611→ Invite = "https://discord.gg/t8EDp4fss", -- shown to players as plain text, e.g. "discord.gg/abcd123" (no clickable links on Roblox)
612→ Reward = 500, -- shards, once per Roblox account and once per Discord account
613→ SecretName = "RoVerApiKey",
614→ PromptAfter = 180, -- seconds of play before the HUD button starts to glow for a player without the reward
615→}
616→
617→return Config
618→
@@ -0,0 +1,35 @@
1→-- Craft House: crafted plot items made from toys (Config.CRAFTS).
2→-- RemoteFunction "Crafting": Craft(id) -> { ok, msg, used = { { Toy, Rarity, Variant }, ... } }
3→-- The server picks the toys itself (Config.CraftPick: cheapest fitting toys, never ones on the tree), takes them and
4→-- adds the item (PlayerData.CraftItem). The item can then be placed on the plot (Shop "Place") or sold on the market.
5→local Players = game:GetService("Players")
6→local ReplicatedStorage = game:GetService("ReplicatedStorage")
7→local ServerStorage = game:GetService("ServerStorage")
8→
9→local folder = ReplicatedStorage:WaitForChild("OrnamentMachine")
10→local Config = require(folder:WaitForChild("Config"))
11→local PlayerData = require(script.Parent:WaitForChild("OrnamentPlayerData"))
12→local craftFn = folder:WaitForChild("Crafting")
13→local notify = folder:WaitForChild("Notify")
14→
15→local last = {}
16→craftFn.OnServerInvoke = function(player, action, id)
17→ local now = os.clock()
18→ if last[player] and now - last[player] < 0.5 then return { ok = false, msg = "Too fast" } end
19→ last[player] = now
20→ if not player:GetAttribute("DataLoaded") then return { ok = false, msg = "Your data is still loading" } end
21→ if action ~= "Craft" or type(id) ~= "string" or not Config.CraftById[id] then return { ok = false } end
22→ local c = Config.CraftById[id]
23→ local ok, taken = PlayerData.CraftItem(player, id)
24→ if not ok then return { ok = false, msg = taken } end
25→ if c.Xp and c.Xp > 0 then
26→ local giveXP = ServerStorage:FindFirstChild("OrnamentGiveXP")
27→ if giveXP then giveXP:Fire(player, c.Xp) end
28→ end
29→ task.spawn(PlayerData.Save, player)
30→ local used = {}
31→ for _, it in taken do table.insert(used, { Toy = it.Toy, Rarity = it.Rarity, Variant = it.Variant }) end
32→ return { ok = true, msg = c.Name .. " crafted! It's in your inventory", used = used }
33→end
34→Players.PlayerRemoving:Connect(function(p) last[p] = nil end)
35→
@@ -0,0 +1,874 @@
1→-- Player data of the ornament game (economy phase 1), saved in a DataStore. The server is the only writer.
2→-- Mirrored for the UI as player attributes:
3→-- Shards, Level, XP, XPNeed, Booster_<id>, Pity_<rarity>, Upg_<id> (upgrade levels), ShardCap,
4→-- ShardRegenAt (unix time of the next free shard, 0 = stock full), DataLoaded
5→-- Owned ornaments: player.OrnamentInventory/<uid> (Configuration; attributes Toy, Rarity, Variant, Order, Created,
6→-- OnTree = slot number while the toy hangs on the player's Christmas tree; such toys are locked for the
7→-- shredder / fusion / trading / market until they are taken off)
8→-- If loading fails the player gets defaults for this session and NOTHING is saved (an outage can never wipe data).
9→-- Session lock: the save holds Lock = { Job = JobId, Time }. A server only loads a profile whose lock is free or
10→-- stale (no heartbeat for LOCK_STALE s) and only writes while it owns the lock -> no duplication across servers
11→-- (required for trading). Autosave refreshes the lock, leaving releases it.
12→local DataStoreService = game:GetService("DataStoreService")
13→local HttpService = game:GetService("HttpService")
14→local ReplicatedStorage = game:GetService("ReplicatedStorage")
15→
16→local Config = require(ReplicatedStorage:WaitForChild("OrnamentMachine"):WaitForChild("Config"))
17→
18→local PlayerData = {}
19→local STORE_NAME = "OrnamentPlayerData_v1"
20→local VERSION = 3 -- 3: 250 new toys in 5 tiers -> old toys / listings / collection / pity are wiped
21→local JOB = (game.JobId ~= "" and game.JobId) or ("studio-" .. HttpService:GenerateGUID(false))
22→local LOCK_STALE = 300
23→local store
24→pcall(function() store = DataStoreService:GetDataStore(STORE_NAME) end)
25→
26→local profiles = {} -- [Player] = { data = table, canSave = bool, dirty = bool, released = bool }
27→local inflight = 0 -- saves running right now (BindToClose waits for them)
28→
29→local function keyOf(player) return "u_" .. player.UserId end
30→
31→local function defaults()
32→ return {
33→ Version = VERSION,
34→ Shards = Config.STARTER.Shards,
35→ Level = 1, XP = 0,
36→ Boosters = table.clone(Config.STARTER.Boosters),
37→ Ornaments = {}, NextId = 1,
38→ Pity = {}, Discovered = {}, Upgrades = {},
39→ Listings = {}, -- [listingId] = { Item = {...}, Price, Expires } (toys in market escrow)
40→ Decor = {}, -- [shopId] = true (bought, in the inventory) | { X, Z, R } (placed on the plot)
41→ Crafts = {}, -- [craftId] = number of EXTRA crafted items in the inventory (the first one lives in Decor)
42→ Receipts = {}, -- [purchaseId] = os.time() (Robux purchases already granted, newest ~100)
43→ RegenAt = os.time(),
44→ Stats = { Generated = 0, Recycled = 0 },
45→ TutorialDone = false, -- the first-time tutorial (TutorialGuide) was finished or skipped
46→ Promos = {}, -- [CODE] = os.time() of redeeming (each promo code once per player)
47→ VipGift = false, -- VIP given by a promo code (permanent, like the game pass)
48→ -- player settings (Settings window): volumes 0..1, background music on/off, interface language
49→ -- ("auto" = Roblox auto-translation to the device language, "en", "ru")
50→ Settings = { Master = 1, Music = 1, Effects = 1, UI = 1, MusicOn = true, Lang = "auto" },
51→ }
52→end
53→
54→local SETTING_VOLUMES = { "Master", "Music", "Effects", "UI" }
55→local SETTING_LANGS = { auto = true, en = true, ru = true }
56→-- settings attributes: Set_Master / Set_Music / Set_Effects / Set_UI (0..1), Set_MusicOn, Set_Lang.
57→-- Published only on load and on change (not on every touch), so they never jump while the player drags a slider.
58→local function publishSettings(player, st)
59→ for _, k in SETTING_VOLUMES do player:SetAttribute("Set_" .. k, st[k]) end
60→ player:SetAttribute("Set_MusicOn", st.MusicOn)
61→ player:SetAttribute("Set_Lang", st.Lang)
62→end
63→local function cleanSettings(raw)
64→ local def = { Master = 1, Music = 1, Effects = 1, UI = 1, MusicOn = true, Lang = "auto" }
65→ if type(raw) ~= "table" then return def end
66→ for _, k in SETTING_VOLUMES do
67→ local v = tonumber(raw[k])
68→ if v and v == v then def[k] = math.clamp(math.floor(v * 100 + 0.5) / 100, 0, 1) end
69→ end
70→ if type(raw.MusicOn) == "boolean" then def.MusicOn = raw.MusicOn end
71→ if type(raw.Lang) == "string" and SETTING_LANGS[raw.Lang] then def.Lang = raw.Lang end
72→ return def
73→end
74→
75→-- fills missing fields of older saves (version 1 had only Shards / Boosters / Ornaments)
76→local function migrate(d)
77→ if (tonumber(d.Version) or 1) < 3 then
78→ d.Ornaments, d.Listings, d.Discovered, d.Pity = {}, {}, {}, {}
79→ end
80→ -- saves from before the tutorial existed: players who already generated something do not get it
81→ if d.TutorialDone == nil then
82→ d.TutorialDone = type(d.Stats) == "table" and (tonumber(d.Stats.Generated) or 0) > 0
83→ end
84→ local def = defaults()
85→ for k, v in def do
86→ if d[k] == nil then d[k] = v end
87→ end
88→ for old, new in Config.BOOSTER_MIGRATE do
89→ if d.Boosters[old] then
90→ d.Boosters[new] = (d.Boosters[new] or 0) + d.Boosters[old]
91→ d.Boosters[old] = nil
92→ end
93→ end
94→ d.Shards = math.max(0, math.floor(tonumber(d.Shards) or 0))
95→ if type(d.Crafts) ~= "table" then d.Crafts = {} end
96→ -- TEST top-up: ONCE per profile (it used to run on every load, so any balance below the minimum came back
97→ -- as the minimum after rejoining and looked like "shards are not saved")
98→ if Config.TEST_MIN_SHARDS and not d.TestTopUp then
99→ d.Shards = math.max(d.Shards, Config.TEST_MIN_SHARDS)
100→ d.TestTopUp = true
101→ end
102→ d.Coins, d.Sparks = nil, nil -- removed: shards are the only resource
103→ d.Level = math.clamp(math.floor(tonumber(d.Level) or 1), 1, Config.MAX_LEVEL)
104→ d.XP = math.max(0, math.floor(tonumber(d.XP) or 0))
105→ d.NextId = math.max(1, math.floor(tonumber(d.NextId) or 1))
106→ d.Settings = cleanSettings(d.Settings)
107→ d.Version = VERSION
108→ return d
109→end
110→
111→local function retry(fn)
112→ for attempt = 1, 4 do
113→ local ok, result = pcall(fn)
114→ if ok then return true, result end
115→ warn("[OrnamentData] attempt " .. attempt .. " failed: " .. tostring(result))
116→ task.wait(attempt)
117→ end
118→ return false
119→end
120→
121→local function inventoryFolder(player)
122→ local f = player:FindFirstChild("OrnamentInventory")
123→ if not f then
124→ f = Instance.new("Folder")
125→ f.Name = "OrnamentInventory"
126→ f.Parent = player
127→ end
128→ return f
129→end
130→
131→local function mirrorOrnament(player, uid, item)
132→ local c = Instance.new("Configuration")
133→ c.Name = uid
134→ c:SetAttribute("Toy", item.Toy)
135→ c:SetAttribute("Rarity", item.Rarity)
136→ c:SetAttribute("Variant", item.Variant)
137→ c:SetAttribute("Order", tonumber(uid) or 0)
138→ c:SetAttribute("Created", item.T or 0)
139→ c:SetAttribute("OnTree", item.OnTree)
140→ c:SetAttribute("Cost", item.Cost)
141→ c.Parent = inventoryFolder(player)
142→end
143→
144→-- tier attributes: MaxTier (highest tier the generator may use), TierFound_<n> (different toys of tier n found),
145→-- TierToys_<n> (one char per toy of tier n in Config.ToysByTier order: char(48 + mask), mask bit (k-1) = rarity
146→-- Config.RARITIES[k] found; "0" = never dropped). Recomputed only when the level or the collection changed.
147→local function publishTiers(player, p)
148→ local d = p.data
149→ if not p.tierStale and p.tierLevel == d.Level then return end
150→ p.tierStale, p.tierLevel = false, d.Level
151→ for i in Config.TIERS do player:SetAttribute("TierFound_" .. i, Config.TierFound(d.Discovered, i)) end
152→ for i in Config.TIERS do
153→ local chars = {}
154→ for k, toy in Config.ToysByTier[i] or {} do
155→ local mask = 0
156→ for ri, r in Config.RARITIES do
157→ if d.Discovered[toy.Id .. "|" .. r.Id] then mask += 2 ^ (ri - 1) end
158→ end
159→ chars[k] = string.char(48 + mask)
160→ end
161→ player:SetAttribute("TierToys_" .. i, table.concat(chars))
162→ end
163→ player:SetAttribute("MaxTier", Config.MaxTier(d.Level, d.Discovered))
164→end
165→
166→local function publish(player, p)
167→ local d = p.data
168→ player:SetAttribute("Shards", d.Shards)
169→ player:SetAttribute("Level", d.Level)
170→ player:SetAttribute("XP", d.XP)
171→ player:SetAttribute("XPNeed", d.Level >= Config.MAX_LEVEL and 0 or Config.XpToNext(d.Level))
172→ for id in Config.BOOSTERS do player:SetAttribute("Booster_" .. id, d.Boosters[id] or 0) end
173→ for _, pity in Config.PITY do player:SetAttribute("Pity_" .. pity.Rarity, d.Pity[pity.Rarity] or 0) end
174→ for _, u in Config.UPGRADES do player:SetAttribute("Upg_" .. u.Id, d.Upgrades[u.Id] or 0) end
175→ for _, s in Config.SHOP do
176→ local v = d.Decor[s.Id]
177→ player:SetAttribute("Decor_" .. s.Id, v ~= nil and v ~= false) -- owned
178→ player:SetAttribute("Placed_" .. s.Id, type(v) == "table") -- standing on the plot
179→ end
180→ -- Craft_<id> = crafted items NOT on the plot (can be placed or sold)
181→ for _, c in Config.CRAFTS do
182→ player:SetAttribute("Craft_" .. c.Id, (d.Crafts[c.Id] or 0) + (d.Decor[c.Id] == true and 1 or 0))
183→ end
184→ local cap, every = Config.RegenCap(d.Upgrades.Regen), Config.RegenSeconds(d.Upgrades.Regen)
185→ player:SetAttribute("TutorialDone", d.TutorialDone == true)
186→ player:SetAttribute("ShardCap", cap)
187→ player:SetAttribute("ShardRegenAt", d.Shards >= cap and 0 or math.ceil(d.RegenAt + every))
188→ publishTiers(player, p)
189→end
190→
191→local function touch(player, p)
192→ p.dirty = true
193→ publish(player, p)
194→end
195→
196→---------------------------------------------------------------- lifecycle
197→function PlayerData.Load(player)
198→ local p = { canSave = false, dirty = false, tierStale = true }
199→ local ok, saved, locked = false, nil, false
200→ if store then
201→ for attempt = 1, 6 do
202→ local callOk, result = pcall(function()
203→ local outcome
204→ store:UpdateAsync(keyOf(player), function(old)
205→ old = type(old) == "table" and old or nil
206→ if old and type(old.Lock) == "table" and old.Lock.Job ~= JOB and os.time() - (tonumber(old.Lock.Time) or 0) < LOCK_STALE then
207→ outcome = "locked"
208→ return nil -- cancel: another server still owns this profile
209→ end
210→ local d = old or defaults()
211→ d.Lock = { Job = JOB, Time = os.time() }
212→ outcome = d
213→ return d
214→ end)
215→ return outcome
216→ end)
217→ if callOk and result ~= "locked" then
218→ ok, saved, locked = true, result, false
219→ break
220→ end
221→ locked = callOk and result == "locked"
222→ if not callOk then warn("[OrnamentData] load attempt " .. attempt .. " failed: " .. tostring(result)) end
223→ task.wait(locked and 5 or attempt)
224→ if not player.Parent then return end
225→ end
226→ end
227→ if locked then
228→ player:Kick("Your data is still being saved on another server. Please rejoin in a minute.")
229→ return
230→ end
231→ if ok then
232→ p.data = migrate(type(saved) == "table" and saved or defaults())
233→ p.canSave = true
234→ else
235→ p.data = defaults()
236→ warn("[OrnamentData] could not load data for " .. player.Name .. "; this session will NOT be saved")
237→ end
238→ if not player.Parent then return end
239→ profiles[player] = p
240→ inventoryFolder(player)
241→ for uid, item in p.data.Ornaments do
242→ if type(item) == "table" and Config.ToyById[item.Toy] and Config.RarityById[item.Rarity] then
243→ mirrorOrnament(player, uid, item)
244→ else
245→ p.data.Ornaments[uid] = nil
246→ end
247→ end
248→ PlayerData.TickRegen(player) -- shards regenerated while offline
249→ publish(player, p)
250→ publishSettings(player, p.data.Settings)
251→ player:SetAttribute("DataLoaded", true)
252→end
253→
254→function PlayerData.Get(player)
255→ local p = profiles[player]
256→ return p and p.data
257→end
258→
259→---------------------------------------------------------------- currencies
260→local function addField(player, field, amount)
261→ local p = profiles[player]
262→ if not p then return false end
263→ p.data[field] = math.max(0, p.data[field] + amount)
264→ touch(player, p)
265→ return true
266→end
267→function PlayerData.AddShards(player, amount)
268→ local p = profiles[player]
269→ local cap = p and Config.RegenCap(p.data.Upgrades.Regen)
270→ if p and amount < 0 and p.data.Shards >= cap and p.data.Shards + amount < cap then
271→ p.data.RegenAt = os.time() -- regeneration restarts when the stock drops below the cap
272→ end
273→ return addField(player, "Shards", amount)
274→end
275→
276→function PlayerData.AddBooster(player, id, amount)
277→ local p = profiles[player]
278→ if not p or not Config.BOOSTERS[id] then return false end
279→ p.data.Boosters[id] = math.max(0, (p.data.Boosters[id] or 0) + amount)
280→ touch(player, p)
281→ return true
282→end
283→
284→-- free shard regeneration (call periodically): +1 per REGEN_SECONDS while below REGEN_CAP
285→function PlayerData.TickRegen(player)
286→ local p = profiles[player]
287→ if not p then return end
288→ local d = p.data
289→ local now = os.time()
290→ local cap, every = Config.RegenCap(d.Upgrades.Regen), Config.RegenSeconds(d.Upgrades.Regen)
291→ if d.Shards >= cap then
292→ d.RegenAt = now
293→ return
294→ end
295→ local ticks = math.floor((now - d.RegenAt) / every)
296→ if ticks > 0 then
297→ local add = math.min(ticks, cap - d.Shards)
298→ d.Shards += add
299→ d.RegenAt += ticks * every
300→ touch(player, p)
301→ end
302→end
303→
304→---------------------------------------------------------------- upgrades
305→function PlayerData.UpgradeLevel(player, id)
306→ local p = profiles[player]
307→ return p and (p.data.Upgrades[id] or 0) or 0
308→end
309→
310→-- pays the next level of an upgrade; returns new level or nil, message
311→function PlayerData.BuyUpgrade(player, id)
312→ local p = profiles[player]
313→ if not p or not Config.UpgradeById[id] then return nil, "Unknown upgrade" end
314→ local d = p.data
315→ local level = d.Upgrades[id] or 0
316→ local cost = Config.UpgradeCost(id, level)
317→ if not cost then return nil, "Already at max level" end
318→ if d.Shards < cost then return nil, "Not enough shards: you need " .. cost end
319→ PlayerData.AddShards(player, -cost)
320→ d.Upgrades[id] = level + 1
321→ touch(player, p)
322→ return level + 1
323→end
324→
325→---------------------------------------------------------------- level / xp
326→-- adds XP; returns the list of levels reached (the caller hands out the rewards)
327→function PlayerData.AddXP(player, amount)
328→ local p = profiles[player]
329→ if not p then return {} end
330→ local d = p.data
331→ local reached = {}
332→ if d.Level >= Config.MAX_LEVEL then return reached end
333→ if amount > 0 and player:GetAttribute("VIP") == true then amount = math.floor(amount * Config.VIP.XP + 0.5) end -- VIP pass
334→ d.XP += amount
335→ while d.Level < Config.MAX_LEVEL and d.XP >= Config.XpToNext(d.Level) do
336→ d.XP -= Config.XpToNext(d.Level)
337→ d.Level += 1
338→ table.insert(reached, d.Level)
339→ end
340→ if d.Level >= Config.MAX_LEVEL then d.XP = 0 end
341→ touch(player, p)
342→ return reached
343→end
344→
345→---------------------------------------------------------------- pity / collection
346→function PlayerData.SetPity(player, rarityId, value)
347→ local p = profiles[player]
348→ if not p then return end
349→ p.data.Pity[rarityId] = value
350→ touch(player, p)
351→end
352→
353→-- marks "Toy|Rarity" as collected; true the first time
354→function PlayerData.Discover(player, toyId, rarityId)
355→ local p = profiles[player]
356→ if not p then return false end
357→ local key = toyId .. "|" .. rarityId
358→ if p.data.Discovered[key] then return false end
359→ p.data.Discovered[key] = true
360→ p.tierStale = true
361→ touch(player, p)
362→ return true
363→end
364→
365→function PlayerData.CountStat(player, stat, amount)
366→ local p = profiles[player]
367→ if not p then return end
368→ p.data.Stats[stat] = (p.data.Stats[stat] or 0) + amount
369→ p.dirty = true
370→end
371→
372→---------------------------------------------------------------- ornaments
373→function PlayerData.OrnamentCount(player)
374→ local p = profiles[player]
375→ if not p then return 0 end
376→ local n = 0
377→ for _ in p.data.Ornaments do n += 1 end
378→ return n
379→end
380→
381→-- cost = shards spent on the toy (generation price; for Fused toys: inputs + fee) -> market quick-sell
382→function PlayerData.AddOrnament(player, toyId, rarityId, variantId, cost)
383→ local p = profiles[player]
384→ if not p then return nil end
385→ local uid = tostring(p.data.NextId)
386→ p.data.NextId += 1
387→ local item = { Toy = toyId, Rarity = rarityId, Variant = variantId, T = os.time(), Cost = tonumber(cost) and math.max(0, math.floor(cost)) or 0 }
388→ p.data.Ornaments[uid] = item
389→ p.dirty = true
390→ mirrorOrnament(player, uid, item)
391→ return uid
392→end
393→
394→-- uids of `count` plain (no variant) toys of one kind + rarity, oldest first; nil if there are fewer
395→function PlayerData.FindFusable(player, toyId, rarityId, count)
396→ local p = profiles[player]
397→ if not p then return nil end
398→ local list = {}
399→ for uid, item in p.data.Ornaments do
400→ if item.Toy == toyId and item.Rarity == rarityId and not item.Variant and not item.OnTree then table.insert(list, uid) end
401→ end
402→ if #list < count then return nil end
403→ table.sort(list, function(a, b) return (tonumber(a) or 0) < (tonumber(b) or 0) end)
404→ return table.move(list, 1, count, 1, {})
405→end
406→
407→-- removes the given uids (only ones the player owns); returns the removed items
408→function PlayerData.TakeOrnaments(player, uids)
409→ local p = profiles[player]
410→ if not p then return {} end
411→ local removed = {}
412→ local folder = inventoryFolder(player)
413→ for _, uid in uids do
414→ local item = p.data.Ornaments[uid]
415→ if item and not item.OnTree then
416→ p.data.Ornaments[uid] = nil
417→ table.insert(removed, item)
418→ local c = folder:FindFirstChild(uid)
419→ if c then c:Destroy() end
420→ end
421→ end
422→ if #removed > 0 then p.dirty = true end
423→ return removed
424→end
425→
426→---------------------------------------------------------------- trading (phase 3)
427→local function count(t) local n = 0 for _ in t do n += 1 end return n end
428→
429→-- true if the player owns the toy and it is old enough to be traded
430→function PlayerData.CanTradeItem(player, uid, minAge)
431→ local p = profiles[player]
432→ local it = p and p.data.Ornaments[uid]
433→ return it ~= nil and not it.OnTree and os.time() - (it.T or 0) >= minAge
434→end
435→
436→function PlayerData.ItemInfo(player, uid)
437→ local p = profiles[player]
438→ local it = p and p.data.Ornaments[uid]
439→ return it and { Toy = it.Toy, Rarity = it.Rarity, Variant = it.Variant, T = it.T, OnTree = it.OnTree, Cost = it.Cost } or nil
440→end
441→
442→-- Swaps two offers in one step after re-validating everything. offer = { uids = { ... }, shards = n }.
443→-- The receiver of shards gets them minus tax. Returns true, { gotA = items for A, gotB = items for B } or false, msg.
444→function PlayerData.ExecuteTrade(pa, pb, offerA, offerB, taxRate, minAge)
445→ local A, B = profiles[pa], profiles[pb]
446→ if not A or not B then return false, "Player data not loaded" end
447→ offerA.shards, offerB.shards = 0, 0 -- only ornaments can be traded
448→ local now = os.time()
449→ local function valid(P, offer)
450→ if P.data.Shards < offer.shards then return false end
451→ local seen = {}
452→ for _, uid in offer.uids do
453→ local it = P.data.Ornaments[uid]
454→ if seen[uid] or not it or it.OnTree or now - (it.T or 0) < minAge then return false end
455→ seen[uid] = true
456→ end
457→ return true
458→ end
459→ if not valid(A, offerA) or not valid(B, offerB) then return false, "The offer is no longer valid" end
460→ local capA = Config.StorageCap(A.data.Upgrades.Storage)
461→ local capB = Config.StorageCap(B.data.Upgrades.Storage)
462→ if count(A.data.Ornaments) - #offerA.uids + #offerB.uids > capA then return false, pa.DisplayName .. ": storage would overflow" end
463→ if count(B.data.Ornaments) - #offerB.uids + #offerA.uids > capB then return false, pb.DisplayName .. ": storage would overflow" end
464→
465→ local itemsA = PlayerData.TakeOrnaments(pa, offerA.uids)
466→ local itemsB = PlayerData.TakeOrnaments(pb, offerB.uids)
467→ local function give(player, P, items)
468→ for _, it in items do
469→ local uid = tostring(P.data.NextId)
470→ P.data.NextId += 1
471→ local copy = { Toy = it.Toy, Rarity = it.Rarity, Variant = it.Variant, T = it.T, Cost = it.Cost }
472→ P.data.Ornaments[uid] = copy
473→ mirrorOrnament(player, uid, copy)
474→ P.data.Discovered[it.Toy .. "|" .. it.Rarity] = true
475→ P.tierStale = true
476→ end
477→ end
478→ give(pb, B, itemsA)
479→ give(pa, A, itemsB)
480→ A.data.Shards = A.data.Shards - offerA.shards + math.floor(offerB.shards * (1 - taxRate))
481→ B.data.Shards = B.data.Shards - offerB.shards + math.floor(offerA.shards * (1 - taxRate))
482→ A.data.Stats.Trades = (A.data.Stats.Trades or 0) + 1
483→ B.data.Stats.Trades = (B.data.Stats.Trades or 0) + 1
484→ touch(pa, A)
485→ touch(pb, B)
486→ return true, { gotA = itemsB, gotB = itemsA }
487→end
488→
489→---------------------------------------------------------------- market (phase 5)
490→function PlayerData.Listings(player)
491→ local p = profiles[player]
492→ return p and p.data.Listings or {}
493→end
494→
495→-- moves a toy from the inventory into the market escrow record (the toy stays saved with the seller until
496→-- the listing is sold, cancelled or expired)
497→function PlayerData.EscrowForListing(player, uid, listingId, price, expires)
498→ local p = profiles[player]
499→ if not p or not p.data.Ornaments[uid] then return nil end
500→ local item = PlayerData.TakeOrnaments(player, { uid })[1]
501→ if not item then return nil end
502→ p.data.Listings[listingId] = { Item = item, Price = price, Expires = expires }
503→ touch(player, p)
504→ return item
505→end
506→
507→-- same for a crafted item (one that is not on the plot)
508→function PlayerData.EscrowCraft(player, id, listingId, price, expires)
509→ local p = profiles[player]
510→ if not p or not PlayerData.TakeCraft(player, id) then return nil end
511→ local item = { Craft = id }
512→ p.data.Listings[listingId] = { Item = item, Price = price, Expires = expires }
513→ touch(player, p)
514→ return item
515→end
516→
517→function PlayerData.DropListing(player, listingId)
518→ local p = profiles[player]
519→ if not p then return nil end
520→ local rec = p.data.Listings[listingId]
521→ p.data.Listings[listingId] = nil
522→ if rec then touch(player, p) end
523→ return rec
524→end
525→
526→---------------------------------------------------------------- Craft House (crafted plot items)
527→-- one crafted item lives in Decor[id] (true = in the inventory, table = on the plot), the rest are counted in
528→-- Crafts[id]. Adding fills Decor first, taking uses the extras first, so a placed item always stays put.
529→local function addCraft(p, id)
530→ if p.data.Decor[id] == nil or p.data.Decor[id] == false then
531→ p.data.Decor[id] = true
532→ else
533→ p.data.Crafts[id] = (p.data.Crafts[id] or 0) + 1
534→ end
535→end
536→function PlayerData.AddCraft(player, id)
537→ local p = profiles[player]
538→ if not p or not Config.CraftById[id] then return false end
539→ addCraft(p, id)
540→ touch(player, p)
541→ return true
542→end
543→-- crafted items of `id` that are not on the plot
544→function PlayerData.CraftSpare(player, id)
545→ local p = profiles[player]
546→ if not p then return 0 end
547→ return (p.data.Crafts[id] or 0) + (p.data.Decor[id] == true and 1 or 0)
548→end
549→-- takes one crafted item that is NOT on the plot (market listing); false if there is none
550→function PlayerData.TakeCraft(player, id)
551→ local p = profiles[player]
552→ if not p or not Config.CraftById[id] then return false end
553→ local d = p.data
554→ if (d.Crafts[id] or 0) > 0 then
555→ d.Crafts[id] -= 1
556→ if d.Crafts[id] <= 0 then d.Crafts[id] = nil end
557→ elseif d.Decor[id] == true then
558→ d.Decor[id] = nil
559→ else
560→ return false
561→ end
562→ touch(player, p)
563→ return true
564→end
565→-- crafts one item: takes the recipe toys (Config.CraftPick) and adds the item. Returns true, takenItems or false, msg
566→function PlayerData.CraftItem(player, id)
567→ local p = profiles[player]
568→ local c = Config.CraftById[id]
569→ if not p or not c then return false, "Unknown item" end
570→ local items = {}
571→ for uid, it in p.data.Ornaments do
572→ table.insert(items, { uid = uid, Toy = it.Toy, Rarity = it.Rarity, Variant = it.Variant, OnTree = it.OnTree })
573→ end
574→ local picks, complete = Config.CraftPick(id, items)
575→ if not complete then return false, "Not enough ornaments for this recipe" end
576→ local uids = {}
577→ for _, line in picks do for _, it in line do table.insert(uids, it.uid) end end
578→ local taken = PlayerData.TakeOrnaments(player, uids)
579→ if #taken ~= #uids then
580→ -- can not happen (all checked above); give back whatever was taken
581→ for _, it in taken do PlayerData.GiveItem(player, it, false) end
582→ return false, "Not enough ornaments for this recipe"
583→ end
584→ addCraft(p, id)
585→ p.data.Stats.Crafted = (p.data.Stats.Crafted or 0) + 1
586→ touch(player, p)
587→ return true, taken
588→end
589→
590→-- gives a toy (bought or returned) back into the inventory, keeping its variant. A crafted item ({ Craft = id })
591→-- goes to the crafted items instead.
592→function PlayerData.GiveItem(player, item, fresh)
593→ local p = profiles[player]
594→ if not p then return nil end
595→ if item.Craft then
596→ if not Config.CraftById[item.Craft] then return nil end
597→ addCraft(p, item.Craft)
598→ touch(player, p)
599→ return "craft"
600→ end
601→ local uid = tostring(p.data.NextId)
602→ p.data.NextId += 1
603→ local copy = { Toy = item.Toy, Rarity = item.Rarity, Variant = item.Variant, T = fresh and os.time() or item.T, Cost = item.Cost }
604→ p.data.Ornaments[uid] = copy
605→ p.data.Discovered[item.Toy .. "|" .. item.Rarity] = true
606→ p.tierStale = true
607→ mirrorOrnament(player, uid, copy)
608→ touch(player, p)
609→ return uid
610→end
611→
612→---------------------------------------------------------------- shop (plot decorations)
613→function PlayerData.OwnsDecor(player, id)
614→ local p = profiles[player]
615→ local v = p and p.data.Decor[id]
616→ return v ~= nil and v ~= false
617→end
618→
619→-- all placements of the player: { [id] = { X, Z, R } }
620→function PlayerData.DecorPlacements(player)
621→ local p = profiles[player]
622→ local out = {}
623→ if not p then return out end
624→ for id, v in p.data.Decor do
625→ if type(v) == "table" then out[id] = v end
626→ end
627→ return out
628→end
629→
630→-- placement = { X, Z, R } to put it on the plot, or nil to put it back into the inventory
631→function PlayerData.SetDecorPlacement(player, id, placement)
632→ local p = profiles[player]
633→ if not p or not PlayerData.OwnsDecor(player, id) then return false end
634→ p.data.Decor[id] = placement and { X = placement.X, Z = placement.Z, R = placement.R, Points = placement.Points } or true
635→ touch(player, p)
636→ return true
637→end
638→
639→-- pays for a decoration; returns true or false, message
640→function PlayerData.BuyDecor(player, id)
641→ local p = profiles[player]
642→ local item = Config.ShopById[id]
643→ if not p or not item then return false, "No such item" end
644→ if item.Craft then return false, "This item is made in the Craft House" end
645→ if PlayerData.OwnsDecor(player, id) then return false, "Already bought" end
646→ if p.data.Shards < item.Price then return false, "Not enough shards: you need " .. item.Price end
647→ PlayerData.AddShards(player, -item.Price)
648→ p.data.Decor[id] = true
649→ touch(player, p)
650→ return true
651→end
652→
653→---------------------------------------------------------------- Robux purchases
654→-- Grants a purchase exactly once: grant(player) runs only if purchaseId is new, then the profile is saved
655→-- right away. Returns true when the purchase is safely recorded (-> PurchaseGranted), false to retry later.
656→function PlayerData.GrantPurchase(player, purchaseId, grant)
657→ local p = profiles[player]
658→ if not p then return false end
659→ local d = p.data
660→ if d.Receipts[purchaseId] then return true end
661→ grant(player)
662→ d.Receipts[purchaseId] = os.time()
663→ -- keep the receipt list small: drop the oldest beyond 100
664→ local list = {}
665→ for id, t in d.Receipts do table.insert(list, { id = id, t = t }) end
666→ if #list > 100 then
667→ table.sort(list, function(a, b) return a.t < b.t end)
668→ for k = 1, #list - 100 do d.Receipts[list[k].id] = nil end
669→ end
670→ touch(player, p)
671→ if not p.canSave or not store then return true end -- Studio without API access: nothing to save
672→ return PlayerData.Save(player) == true
673→end
674→
675→---------------------------------------------------------------- Christmas tree toys
676→-- { [slot] = uid } of the toys hanging on the player's tree
677→function PlayerData.TreeToys(player)
678→ local p = profiles[player]
679→ local out = {}
680→ if not p then return out end
681→ for uid, it in p.data.Ornaments do
682→ if it.OnTree then out[it.OnTree] = uid end
683→ end
684→ return out
685→end
686→
687→-- slot = number to hang it, nil to take it off; returns true or false, message
688→function PlayerData.SetToySlot(player, uid, slot)
689→ local p = profiles[player]
690→ local it = p and p.data.Ornaments[uid]
691→ if not it then return false, "Ornament not found" end
692→ if slot ~= nil then
693→ for otherUid, other in p.data.Ornaments do
694→ if otherUid ~= uid and other.OnTree == slot then return false, "This spot is already taken" end
695→ end
696→ end
697→ it.OnTree = slot
698→ local c = player:FindFirstChild("OrnamentInventory") and player.OrnamentInventory:FindFirstChild(uid)
699→ if c then c:SetAttribute("OnTree", slot) end
700→ p.dirty = true
701→ return true
702→end
703→
704→---------------------------------------------------------------- tutorial
705→function PlayerData.SetTutorialDone(player)
706→ local p = profiles[player]
707→ if not p or p.data.TutorialDone then return end
708→ p.data.TutorialDone = true
709→ touch(player, p)
710→end
711→
712→---------------------------------------------------------------- admin (OrnamentAdminServer)
713→-- sets the level directly (XP of the new level starts at 0); no level-up rewards
714→function PlayerData.SetLevel(player, level)
715→ local p = profiles[player]
716→ if not p then return false end
717→ p.tierStale = true
718→ p.data.Level = math.clamp(math.floor(level), 1, Config.MAX_LEVEL)
719→ p.data.XP = 0
720→ touch(player, p)
721→ return true
722→end
723→
724→function PlayerData.ResetTutorial(player)
725→ local p = profiles[player]
726→ if not p then return false end
727→ p.data.TutorialDone = false
728→ touch(player, p)
729→ return true
730→end
731→
732→-- "tutorial reset for everyone": a global counter; a profile with an older one gets TutorialDone = false once
733→function PlayerData.ApplyTutorialEpoch(player, epoch)
734→ local p = profiles[player]
735→ if not p or type(epoch) ~= "number" or epoch <= 0 then return end
736→ local d = p.data
737→ if (d.TutorialEpoch or 0) >= epoch then return end
738→ d.TutorialEpoch = epoch
739→ d.TutorialDone = false
740→ touch(player, p)
741→end
742→
743→-- the profile becomes a new player's; Robux receipts stay (a purchase is never granted twice).
744→-- Returns the ids of the old market listings (the caller takes them off the market), nil if not loaded.
745→function PlayerData.ResetProfile(player)
746→ local p = profiles[player]
747→ if not p then return nil end
748→ local old = p.data
749→ local d = defaults()
750→ d.Receipts = old.Receipts or {}
751→ d.TestTopUp = old.TestTopUp
752→ d.TutorialEpoch = old.TutorialEpoch
753→ d.Promos = old.Promos or {} -- redeemed codes stay redeemed (no second reward after a reset)
754→ d.VipGift = old.VipGift == true
755→ d.Settings = old.Settings or d.Settings -- the player's sound / language settings are not progress
756→ p.data = d
757→ p.tierStale = true
758→ local inv = player:FindFirstChild("OrnamentInventory")
759→ if inv then inv:ClearAllChildren() end
760→ touch(player, p)
761→ local lots = {}
762→ for id in old.Listings or {} do table.insert(lots, id) end
763→ return lots
764→end
765→
766→---------------------------------------------------------------- promo codes (OrnamentPromo)
767→function PlayerData.HasPromo(player, code)
768→ local p = profiles[player]
769→ return p ~= nil and type(p.data.Promos) == "table" and p.data.Promos[code] ~= nil
770→end
771→function PlayerData.MarkPromo(player, code)
772→ local p = profiles[player]
773→ if not p then return false end
774→ p.data.Promos = type(p.data.Promos) == "table" and p.data.Promos or {}
775→ p.data.Promos[code] = os.time()
776→ touch(player, p)
777→ return true
778→end
779→function PlayerData.SetVipGift(player)
780→ local p = profiles[player]
781→ if not p then return false end
782→ p.data.VipGift = true
783→ touch(player, p)
784→ return true
785→end
786→function PlayerData.HasVipGift(player)
787→ local p = profiles[player]
788→ return p ~= nil and p.data.VipGift == true
789→end
790→
791→---------------------------------------------------------------- settings
792→-- partial update from the Settings window; unknown keys / bad values are ignored. Returns true if anything changed.
793→function PlayerData.SetSettings(player, patch)
794→ local p = profiles[player]
795→ if not p or type(patch) ~= "table" then return false end
796→ local merged = table.clone(p.data.Settings or {})
797→ for k, v in patch do if type(k) == "string" then merged[k] = v end end
798→ local clean = cleanSettings(merged)
799→ local changed = false
800→ for k, v in clean do if p.data.Settings[k] ~= v then changed = true end end
801→ if not changed then return false end
802→ p.data.Settings = clean
803→ p.dirty = true
804→ publishSettings(player, clean)
805→ return true
806→end
807→
808→---------------------------------------------------------------- saving
809→local function deepCopy(t)
810→ local c = {}
811→ for k, v in t do c[k] = type(v) == "table" and deepCopy(v) or v end
812→ return c
813→end
814→
815→-- writes the profile (also refreshes the session lock); release = drop the lock (player left)
816→function PlayerData.Save(player, release)
817→ local p = profiles[player]
818→ if not p or not p.canSave or not store then return end
819→ if p.released and not release then return end -- leaving: only the final (lock-releasing) save may write
820→ local snapshot = deepCopy(p.data)
821→ snapshot.Lock = (not release) and { Job = JOB, Time = os.time() } or nil
822→ local lost = false
823→ inflight += 1
824→ local ok = retry(function()
825→ store:UpdateAsync(keyOf(player), function(old)
826→ if type(old) == "table" and type(old.Lock) == "table" and old.Lock.Job ~= JOB then
827→ lost = true
828→ return nil -- someone else owns the profile now: never overwrite
829→ end
830→ -- an autosave that finishes after the final save must not put the lock back
831→ if not release and p.released then return nil end
832→ return snapshot
833→ end)
834→ end)
835→ inflight -= 1
836→ if lost then
837→ warn("[OrnamentData] lost the session lock for " .. player.Name .. "; changes are not saved")
838→ p.canSave = false
839→ elseif ok then
840→ p.dirty = false
841→ end
842→ return ok and not lost
843→end
844→
845→function PlayerData.Release(player)
846→ local p = profiles[player]
847→ if not p or p.released then return end
848→ p.released = true
849→ PlayerData.Save(player, true)
850→ profiles[player] = nil
851→end
852→
853→function PlayerData.ForEach(fn)
854→ for player in profiles do fn(player) end
855→end
856→
857→function PlayerData.SaveAll()
858→ local pending = 0
859→ for player in profiles do
860→ pending += 1
861→ task.spawn(function()
862→ PlayerData.Release(player)
863→ pending -= 1
864→ end)
865→ end
866→ -- also wait for the saves PlayerRemoving already started (on shutdown the players leave first, so their
867→ -- profiles may be gone from `profiles` while the save is still on its way)
868→ task.wait(0.5)
869→ local deadline = os.clock() + 25
870→ while (pending > 0 or inflight > 0) and os.clock() < deadline do task.wait(0.2) end
871→end
872→
873→return PlayerData
874→
+732
View File
@@ -0,0 +1,732 @@
1→-- ShopKit: shared pieces of the New Year shop-style windows (Мастерская, Рынок).
2→-- Art from GUI/магазин: snowy green panel, red ribbon, pill buttons, ray cards, crystal, holly, gift.
3→-- Design canvas 1400 x 1000 px; OrnamentCraftUI's openWindow() scales it to the screen.
4→--
5→-- K.pill : action button with states
6→-- ready (gold) / alt (blue) / confirm, danger (red) — clickable
7→-- done (green) / info (blue) — inert, off (grey, says what is missing) / busy (•••, waiting for the server)
8→-- hover = grow + light ring, press = shrink + darken, a click on "off" wiggles it.
9→-- K.chip : filter chip (green, gold when selected), same hover / press feel.
10→-- K.chrome : the whole window frame — gradient body, stars, garlands, ribbon title, balance plate, close button,
11→-- content panel, tip line and up to 4 tabs (normal / hover / pressed / selected + red badge).
12→local TweenService = game:GetService("TweenService")
13→
14→local K = {}
15→
16→K.FONT = Font.new("rbxasset://fonts/families/FredokaOne.json", Enum.FontWeight.Bold)
17→K.BODY = Font.new("rbxasset://fonts/families/GothamSSm.json", Enum.FontWeight.Bold)
18→K.INK = Color3.fromRGB(12, 8, 10)
19→K.WHITE = Color3.new(1, 1, 1)
20→K.GOLD = Color3.fromRGB(255, 211, 116)
21→K.SOFT = Color3.fromRGB(222, 238, 230)
22→K.OK = Color3.fromRGB(150, 255, 160)
23→K.WARN = Color3.fromRGB(255, 196, 120)
24→K.NAVY = Color3.fromRGB(14, 26, 58)
25→local FONT, BODY, INK, WHITE, GOLD, SOFT, OK, NAVY = K.FONT, K.BODY, K.INK, K.WHITE, K.GOLD, K.SOFT, K.OK, K.NAVY
26→
27→-- art (id, opaque rect in the source png)
28→K.ART = {
29→ panel = { "rbxassetid://138527541920438", { 18, 42, 278, 234 } },
30→ ribbon = { "rbxassetid://103499479509351", { 10, 74, 294, 166 } },
31→ green = { "rbxassetid://93987797017793", { 16, 110, 280, 102 } },
32→ red = { "rbxassetid://138508596098174", { 18, 108, 280, 102 } },
33→ blue = { "rbxassetid://111888989174975", { 18, 114, 278, 94 } },
34→ gold = { "rbxassetid://131564766133063", { 16, 108, 280, 102 } },
35→ grey = { "rbxassetid://89653402754634", { 16, 108, 280, 102 } },
36→ crystal = { "rbxassetid://105804941618750", { 54, 56, 206, 210 } },
37→ cardGreen = { "rbxassetid://105142745227171", { 16, 22, 280, 272 } },
38→ cardCyan = { "rbxassetid://116968687145512", { 18, 22, 280, 272 } },
39→ cardViolet = { "rbxassetid://103872013133887", { 16, 22, 282, 272 } },
40→ cardOrange = { "rbxassetid://125846279529125", { 18, 22, 280, 272 } },
41→ gift = { "rbxassetid://85573436333424" },
42→ holly = { "rbxassetid://96646166091621" },
43→ garland = { "rbxassetid://133428323657868" },
44→}
45→K.CARD_SLICE = Rect.new(34, 60, 246, 206)
46→local ART = K.ART
47→
48→function K.tween(o, t, props, style, dir)
49→ local tw = TweenService:Create(o, TweenInfo.new(t, style or Enum.EasingStyle.Quad, dir or Enum.EasingDirection.Out), props)
50→ tw:Play()
51→ return tw
52→end
53→local tween = K.tween
54→function K.new(class, props, children)
55→ local o = Instance.new(class)
56→ for k, v in props do if k ~= "Parent" then o[k] = v end end
57→ for _, c in children or {} do c.Parent = o end
58→ if class == "TextButton" or class == "ImageButton" then o:SetAttribute("UXDone", true) end -- OrnamentUX: hands off
59→ if props.Parent then o.Parent = props.Parent end
60→ return o
61→end
62→local new = K.new
63→function K.corner(r) return new("UICorner", { CornerRadius = r }) end
64→local corner = K.corner
65→-- Own 9-slice for atlas art. Roblox's ScaleType.Slice combined with ImageRectOffset/Size draws the borders from the
66→-- wrong spot on many devices (seams and a "shifted" frame, worst on phones with reduced texture quality), while a
67→-- plain Stretch of an ImageRect is always exact. So a sliced art becomes 9 stretched pieces under the (invisible)
68→-- image: corners keep their size, edges stretch one way, the centre both ways. SliceCenter is relative to the
69→-- art rect (like before); border sizes are in design units (SliceScale x art px) and scale with the window's UIScale.
70→-- The pieces follow the image's ImageColor3 / ImageTransparency / ZIndex / Image / rect (the host's own
71→-- ImageTransparency is remembered in the "ArtTransparency" attribute; the host itself stays fully transparent).
72→local function slice9(img, center, scale)
73→ local holder = Instance.new("Frame")
74→ holder.Name = "Slice9"
75→ holder.BackgroundTransparency = 1
76→ holder.Size = UDim2.fromScale(1, 1)
77→ holder.ZIndex = img.ZIndex
78→ local pieces = {}
79→ local function build()
80→ for _, p in pieces do p:Destroy() end
81→ table.clear(pieces)
82→ local off, size = img.ImageRectOffset, img.ImageRectSize
83→ local L, T = center.Min.X, center.Min.Y
84→ local R, B = size.X - center.Max.X, size.Y - center.Max.Y
85→ local cw, chh = size.X - L - R, size.Y - T - B
86→ local l, t, r, b = L * scale, T * scale, R * scale, B * scale
87→ local E = 1 -- edges / centre reach 1 unit under their neighbours: no hairline gaps between pieces
88→ -- { source x, source w, position, size }; drawn centre -> edges -> corners
89→ local cols = {
90→ { 0, L, UDim.new(0, 0), UDim.new(0, l) },
91→ { L, cw, UDim.new(0, l - E), UDim.new(1, -l - r + 2 * E) },
92→ { L + cw, R, UDim.new(1, -r), UDim.new(0, r) },
93→ }
94→ local rows = {
95→ { 0, T, UDim.new(0, 0), UDim.new(0, t) },
96→ { T, chh, UDim.new(0, t - E), UDim.new(1, -t - b + 2 * E) },
97→ { T + chh, B, UDim.new(1, -b), UDim.new(0, b) },
98→ }
99→ local order = { { 2, 2 }, { 2, 1 }, { 2, 3 }, { 1, 2 }, { 3, 2 }, { 1, 1 }, { 3, 1 }, { 1, 3 }, { 3, 3 } }
100→ for k, cr in order do
101→ local c = cols[cr[1] ]
102→ local rw = rows[cr[2] ]
103→ if c[2] > 0 and rw[2] > 0 then
104→ local p = Instance.new("ImageLabel")
105→ p.Name = "Piece" .. k
106→ p.BackgroundTransparency = 1
107→ p.Image = img.Image
108→ p.ImageRectOffset = off + Vector2.new(c[1], rw[1])
109→ p.ImageRectSize = Vector2.new(c[2], rw[2])
110→ p.ScaleType = Enum.ScaleType.Stretch
111→ p.ImageColor3 = img.ImageColor3
112→ p.ImageTransparency = img:GetAttribute("ArtTransparency") or 0
113→ p.Position = UDim2.new(c[3], rw[3])
114→ p.Size = UDim2.new(c[4], rw[4])
115→ p.ZIndex = img.ZIndex
116→ p.Parent = holder
117→ table.insert(pieces, p)
118→ end
119→ end
120→ end
121→ build()
122→ img:GetPropertyChangedSignal("ImageColor3"):Connect(function() for _, p in pieces do p.ImageColor3 = img.ImageColor3 end end)
123→ img:GetPropertyChangedSignal("ImageTransparency"):Connect(function()
124→ if img.ImageTransparency == 1 then return end
125→ img:SetAttribute("ArtTransparency", img.ImageTransparency)
126→ for _, p in pieces do p.ImageTransparency = img.ImageTransparency end
127→ img.ImageTransparency = 1
128→ end)
129→ img:GetPropertyChangedSignal("ZIndex"):Connect(function() holder.ZIndex = img.ZIndex; for _, p in pieces do p.ZIndex = img.ZIndex end end)
130→ for _, prop in { "Image", "ImageRectOffset", "ImageRectSize" } do img:GetPropertyChangedSignal(prop):Connect(build) end
131→ img.ImageTransparency = 1
132→ holder.Parent = img
133→end
134→function K.art(name, props, isButton)
135→ local d = ART[name]
136→ props.BackgroundTransparency = 1
137→ props.Image = d[1]
138→ if d[2] then
139→ props.ImageRectOffset = Vector2.new(d[2][1], d[2][2])
140→ props.ImageRectSize = Vector2.new(d[2][3], d[2][4])
141→ end
142→ local sliced = d[2] ~= nil and props.ScaleType == Enum.ScaleType.Slice
143→ local center, scale, transp = props.SliceCenter, props.SliceScale or 1, props.ImageTransparency
144→ if sliced then props.ScaleType, props.SliceCenter, props.SliceScale = Enum.ScaleType.Stretch, nil, nil end
145→ local o = new(isButton and "ImageButton" or "ImageLabel", props)
146→ if sliced then
147→ if transp then o:SetAttribute("ArtTransparency", transp) end
148→ slice9(o, center, scale)
149→ end
150→ return o
151→end
152→local art = K.art
153→function K.setArt(img, name)
154→ local d = ART[name]
155→ img.Image = d[1]
156→ img.ImageRectOffset = Vector2.new(d[2][1], d[2][2])
157→ img.ImageRectSize = Vector2.new(d[2][3], d[2][4])
158→end
159→local setArt = K.setArt
160→-- rounded title text with a thin black outline
161→function K.label(props, stroke)
162→ props.BackgroundTransparency = 1
163→ props.FontFace = props.FontFace or FONT
164→ props.TextColor3 = props.TextColor3 or WHITE
165→ if props.TextXAlignment == nil then props.TextXAlignment = Enum.TextXAlignment.Left end
166→ local t = new("TextLabel", props)
167→ new("UIStroke", { Color = INK, Thickness = stroke or 2, Parent = t })
168→ return t
169→end
170→local label = K.label
171→function K.maxText(t, size) new("UITextSizeConstraint", { MaxTextSize = size, Parent = t }) return t end
172→local maxText = K.maxText
173→function K.isPress(input)
174→ return input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch
175→end
176→local isPress = K.isPress
177→-- floating "+1" over a card
178→function K.floatText(parent, text, color)
179→ local t = label({ AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.45), Size = UDim2.fromOffset(300, 60),
180→ Text = text, TextSize = 48, TextColor3 = color or OK, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 40, Parent = parent }, 3)
181→ local sc = new("UIScale", { Scale = 0.6, Parent = t })
182→ tween(sc, 0.25, { Scale = 1 }, Enum.EasingStyle.Back)
183→ tween(t, 1.1, { Position = UDim2.fromScale(0.5, 0.05), TextTransparency = 1 })
184→ tween(t.UIStroke, 1.1, { Transparency = 1 })
185→ task.delay(1.15, function() t:Destroy() end)
186→end
187→function K.flash(card, radius)
188→ local f = new("Frame", { Size = UDim2.fromScale(1, 1), BackgroundColor3 = WHITE, BackgroundTransparency = 0.45, ZIndex = 39, Parent = card }, { corner(UDim.new(0, radius or 30)) })
189→ tween(f, 0.5, { BackgroundTransparency = 1 })
190→ task.delay(0.55, function() f:Destroy() end)
191→end
192→-- vertical scrolling list / grid
193→function K.scroll(parent, pos, size, layout)
194→ local s = new("ScrollingFrame", { Position = pos, Size = size, BackgroundTransparency = 1, BorderSizePixel = 0, ScrollBarThickness = 10, ZIndex = 4,
195→ ScrollBarImageColor3 = GOLD, AutomaticCanvasSize = Enum.AutomaticSize.Y, CanvasSize = UDim2.new(), ScrollingDirection = Enum.ScrollingDirection.Y, Parent = parent })
196→ if layout then layout.Parent = s end
197→ return s
198→end
199→-- gift + title + hint (+ optional button) for an empty list
200→function K.emptyState(props, title, hint)
201→ local f = new("Frame", props)
202→ f.BackgroundTransparency = 1
203→ f.Parent = props.Parent
204→ art("gift", { AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 10), Size = UDim2.fromOffset(170, 170), ScaleType = Enum.ScaleType.Fit, ZIndex = 5, Parent = f })
205→ maxText(label({ Position = UDim2.new(0, 40, 0, 190), Size = UDim2.new(1, -80, 0, 50), Text = title, TextScaled = true,
206→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 5, Parent = f }, 3), 42)
207→ maxText(label({ Position = UDim2.new(0, 40, 0, 246), Size = UDim2.new(1, -80, 0, 60), Text = hint, TextScaled = true, TextWrapped = true, FontFace = BODY,
208→ TextColor3 = SOFT, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 5, Parent = f }, 1.5), 26)
209→ return f
210→end
211→
212→-- links between windows: OrnamentCraftUI registers K.nav.<Window> = function(tabId) ... end
213→K.nav = {}
214→function K.go(window, tab)
215→ local f = K.nav[window]
216→ if f then f(tab) end
217→end
218→
219→-- the toy's 3D model in a square ViewportFrame (transparent background); same interface as the old pattern icon:
220→-- returns the GuiObject, the caller sets AnchorPoint / Position / ZIndex
221→local ToyModels
222→function K.toyIcon(item, size, parent)
223→ ToyModels = ToyModels or require(game:GetService("ReplicatedStorage"):WaitForChild("OrnamentMachine"):WaitForChild("ToyModels"))
224→ local vp = Instance.new("ViewportFrame")
225→ vp.Name = "ToyIcon"
226→ vp.BackgroundTransparency = 1
227→ vp.Size = UDim2.fromOffset(size, size)
228→ vp.Ambient = Color3.fromRGB(170, 170, 185)
229→ vp.LightColor = Color3.fromRGB(255, 245, 230)
230→ vp.LightDirection = Vector3.new(-1, -1.3, -1)
231→ local ok, model = pcall(ToyModels.Build, item, 1)
232→ if ok and model then
233→ model:PivotTo(CFrame.Angles(0, math.rad(20), 0))
234→ model.Parent = vp
235→ end
236→ local cam = Instance.new("Camera")
237→ cam.FieldOfView = 30
238→ cam.CFrame = CFrame.lookAt(Vector3.new(0, 0.2, 3.3), Vector3.new(0, 0, 0))
239→ cam.Parent = vp
240→ vp.CurrentCamera = cam
241→ vp.Parent = parent
242→ return vp
243→end
244→
245→-- a crafted item (Config.CRAFTS id) as its 3D model in a square ViewportFrame (Decor template); same interface
246→-- as K.toyIcon. The model is cloned after its meshes loaded.
247→K.CRAFT_COLOR = Color3.fromRGB(255, 170, 60)
248→-- turns a crafted model so its front/side faces the camera (yaw 90: the train centred at the front, engine three-quarter view)
249→-- and fills the view with it (the ring of the train's Track, seen from ~30 degrees up, slightly cropped)
250→K.CRAFT_YAW = 90
251→function K.frameCraft(model, cam, angle, aspect)
252→ local track = model:FindFirstChild("Track")
253→ if not track then
254→ -- other crafted items (front = +Z): three-quarter front view, whole item in the frame
255→ model:PivotTo(CFrame.Angles(0, math.rad(-22), 0))
256→ local cf, sz = model:GetBoundingBox()
257→ cam.FieldOfView = 30
258→ local fitV = (sz.Y / 2 + 0.15 * sz.Y) / math.tan(math.rad(15))
259→ local fitW = (math.max(sz.X, sz.Z) / 2 * 1.15) / (math.tan(math.rad(15)) * math.min(aspect or 1, 1.4))
260→ local up = math.rad(14)
261→ local dir = Vector3.new(0, math.sin(up), math.cos(up))
262→ cam.CFrame = CFrame.lookAt(cf.Position + dir * (math.max(fitV, fitW) + math.max(sz.X, sz.Z) / 2), cf.Position)
263→ return
264→ end
265→ model:PivotTo(CFrame.Angles(0, math.rad(angle or K.CRAFT_YAW), 0))
266→ local cf, sz = (track or model):GetBoundingBox()
267→ local centre = cf.Position
268→ local D = math.max(sz.X, sz.Z)
269→ cam.FieldOfView = 30
270→ local up = math.rad(30)
271→ local dir = Vector3.new(0, math.sin(up), math.cos(up))
272→ -- fit the ring's width (horizontal FOV grows with the view's width / height) and its height (~half the ring + engine)
273→ local tanV = math.tan(math.rad(15))
274→ local distW = (D / 2) / (tanV * (aspect or 1)) * 0.7
275→ local distH = (D * math.sin(up) / 2 * 0.7 + 1.6) / tanV
276→ local dist = math.max(distW, distH)
277→ local target = centre + Vector3.new(0, 0.9, D * 0.22) -- towards the camera: the train in front fills the view, the far rails crop
278→ cam.CFrame = CFrame.lookAt(target + dir * dist, target)
279→end
280→function K.craftIcon(id, size, parent, angle)
281→ local RS = game:GetService("ReplicatedStorage")
282→ local folder = RS:WaitForChild("OrnamentMachine")
283→ local Config = require(folder:WaitForChild("Config"))
284→ local vp = Instance.new("ViewportFrame")
285→ vp.Name = "CraftIcon"
286→ vp.BackgroundTransparency = 1
287→ vp.Size = UDim2.fromOffset(size, size)
288→ vp.Ambient = Color3.fromRGB(175, 175, 190)
289→ vp.LightColor = Color3.fromRGB(255, 245, 230)
290→ vp.LightDirection = Vector3.new(-1, -1.3, -1)
291→ local cam = Instance.new("Camera")
292→ cam.FieldOfView = 32
293→ cam.Parent = vp
294→ vp.CurrentCamera = cam
295→ vp.Parent = parent
296→ local shop = Config.ShopById[id]
297→ local template = shop and folder:WaitForChild("Decor"):FindFirstChild(shop.Model)
298→ if template then
299→ task.spawn(function()
300→ pcall(function() game:GetService("ContentProvider"):PreloadAsync({ template }) end)
301→ if not vp.Parent then return end
302→ local m = template:Clone()
303→ m:RemoveTag("TrainRide") -- a still picture (TrainRide drives tagged models)
304→ for _, d in m:GetDescendants() do
305→ if d:IsA("ParticleEmitter") or d:IsA("Light") or d:IsA("Sound") then d:Destroy() end
306→ end
307→ m.Parent = vp
308→ local a = vp.AbsoluteSize
309→ K.frameCraft(m, cam, angle, (a.X > 0 and a.Y > 0) and a.X / a.Y or 1)
310→ end)
311→ end
312→ return vp
313→end
314→
315→---------------------------------------------------------------- hover tooltip
316→-- K.tooltip(guiObject, getText): while the mouse is over the object a small dark card with getText() (rich text)
317→-- follows the cursor. Lives in its own ScreenGui on top of everything; hides when the object goes away.
318→local tipGui, tipLabel, tipOwner, tipConn
319→local function tipHide(owner)
320→ if owner and tipOwner ~= owner then return end
321→ tipOwner = nil
322→ if tipGui then tipGui.Enabled = false end
323→ if tipConn then tipConn:Disconnect(); tipConn = nil end
324→end
325→local function tipPlace()
326→ local UIS = game:GetService("UserInputService")
327→ local m = UIS:GetMouseLocation()
328→ local vp = workspace.CurrentCamera.ViewportSize
329→ local s = tipLabel.AbsoluteSize
330→ local x, y = m.X + 18, m.Y + 18
331→ if x + s.X > vp.X - 6 then x = m.X - s.X - 12 end
332→ if y + s.Y > vp.Y - 6 then y = m.Y - s.Y - 12 end
333→ tipLabel.Position = UDim2.fromOffset(x, y)
334→end
335→function K.tooltip(obj, getText)
336→ local function show()
337→ local pg = game:GetService("Players").LocalPlayer:FindFirstChildOfClass("PlayerGui")
338→ if not pg then return end
339→ if not tipGui or not tipGui.Parent then
340→ tipGui = new("ScreenGui", { Name = "KTooltip", DisplayOrder = 200, IgnoreGuiInset = true, ResetOnSpawn = false, Enabled = false, Parent = pg })
341→ tipLabel = new("TextLabel", { AutomaticSize = Enum.AutomaticSize.XY, Size = UDim2.fromOffset(0, 0), BackgroundColor3 = Color3.fromRGB(12, 20, 40),
342→ BackgroundTransparency = 0.05, RichText = true, TextWrapped = false, FontFace = BODY, TextSize = 21, TextColor3 = WHITE,
343→ TextXAlignment = Enum.TextXAlignment.Left, Text = "", ZIndex = 10, Parent = tipGui }, {
344→ corner(UDim.new(0, 10)), new("UIStroke", { Color = GOLD, Thickness = 2, ApplyStrokeMode = Enum.ApplyStrokeMode.Border }),
345→ new("UIPadding", { PaddingLeft = UDim.new(0, 12), PaddingRight = UDim.new(0, 12), PaddingTop = UDim.new(0, 8), PaddingBottom = UDim.new(0, 8) }),
346→ })
347→ end
348→ local ok, t = pcall(getText)
349→ if not ok or not t or t == "" then return end
350→ tipLabel.Text = t
351→ tipOwner = obj
352→ tipGui.Enabled = true
353→ tipPlace()
354→ if tipConn then tipConn:Disconnect() end
355→ tipConn = game:GetService("RunService").RenderStepped:Connect(function()
356→ if not obj.Parent or not obj.Visible or not obj:IsDescendantOf(game) then tipHide(obj) return end
357→ local sg = obj:FindFirstAncestorOfClass("ScreenGui")
358→ if sg and not sg.Enabled then tipHide(obj) return end
359→ tipPlace()
360→ end)
361→ end
362→ obj.MouseEnter:Connect(show)
363→ obj.MouseLeave:Connect(function() tipHide(obj) end)
364→ obj.Destroying:Connect(function() tipHide(obj) end)
365→end
366→-- tooltip text of a toy: name, tier · rarity (· variant)
367→function K.toyTip(Config, it, extra)
368→ local toy, r = Config.ToyById[it.Toy], Config.RarityById[it.Rarity]
369→ if not toy or not r then return "" end
370→ local v = it.Variant and Config.VariantById[it.Variant]
371→ local function hex(c) return string.format("#%02X%02X%02X", c.R * 255, c.G * 255, c.B * 255) end
372→ local t = "<b>" .. toy.Name .. "</b>\n<font color=\"" .. hex(r.Color) .. "\">" .. r.Name .. "</font> · " .. Config.TIERS[toy.Tier].Name
373→ if v then t ..= " · <font color=\"" .. hex(v.Color) .. "\">" .. v.Name .. "</font>" end
374→ if extra then t ..= "\n" .. extra end
375→ return t
376→end
377→
378→-- toy tile (button): dark rounded square, the toy's model on a disc, name, rarity line, optional value line.
379→-- o = { Config, miniPattern, parent, item, w, h, order, z, value } -> { button, stroke, scale, setSelected, lock }
380→function K.toyTile(o)
381→ local Config = o.Config
382→ local it = o.item
383→ local r = Config.RarityById[it.Rarity]
384→ local v = it.Variant and Config.VariantById[it.Variant]
385→ local z = o.z or 5
386→ local edge = v and v.Color or r.Color
387→ local b = new("TextButton", { Text = "", AutoButtonColor = false, BackgroundColor3 = Color3.fromRGB(10, 26, 34), Size = UDim2.fromOffset(o.w, o.h),
388→ LayoutOrder = o.order or 0, ZIndex = z, Parent = o.parent }, { corner(UDim.new(0, 18)) })
389→ local st = new("UIStroke", { Color = edge, Thickness = 2.5, ApplyStrokeMode = Enum.ApplyStrokeMode.Border, Parent = b })
390→ local sc = new("UIScale", { Parent = b })
391→ local d = math.floor(math.min(o.w * 0.66, o.h * 0.52))
392→ local disc = new("Frame", { AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 6), Size = UDim2.fromOffset(d, d), BackgroundColor3 = Color3.new(0, 0, 0),
393→ BackgroundTransparency = 0.4, ZIndex = z + 1, Parent = b }, { corner(UDim.new(0.5, 0)) })
394→ local mini = K.toyIcon(it, math.floor(d * 0.92), disc)
395→ mini.AnchorPoint = Vector2.new(0.5, 0.5)
396→ mini.Position = UDim2.fromScale(0.5, 0.5)
397→ mini.ZIndex = z + 2
398→ for _, x in mini:GetDescendants() do if x:IsA("GuiObject") then x.ZIndex = z + 2 end end
399→ local y = d + 8
400→ local lineH = math.floor((o.h - y - 4) / (o.value and 3 or 2))
401→ maxText(label({ Position = UDim2.fromOffset(4, y), Size = UDim2.new(1, -8, 0, lineH), Text = Config.ToyById[it.Toy].Name, TextScaled = true,
402→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = z + 1, Parent = b }, 1.5), 22)
403→ maxText(label({ Position = UDim2.fromOffset(4, y + lineH), Size = UDim2.new(1, -8, 0, lineH), Text = r.Name .. (v and (" · " .. v.Name) or ""), TextScaled = true,
404→ TextColor3 = edge, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = z + 1, Parent = b }, 1.5), 18)
405→ if o.value then
406→ maxText(label({ Position = UDim2.fromOffset(4, y + lineH * 2), Size = UDim2.new(1, -8, 0, lineH), Text = o.valueText or (Config.Value(it) .. " shards"), TextScaled = true, FontFace = BODY,
407→ TextColor3 = Color3.fromRGB(190, 225, 255), TextXAlignment = Enum.TextXAlignment.Center, ZIndex = z + 1, Parent = b }, 1.5), 16)
408→ end
409→ K.tooltip(b, function() return K.toyTip(Config, it) end)
410→ local t = { button = b, stroke = st, scale = sc, selected = false, locked = false, inert = o.inert }
411→ local function paint(hover, down)
412→ st.Color = t.selected and GOLD or edge
413→ st.Thickness = t.selected and 5 or 2.5
414→ local live = not t.locked and not t.inert
415→ tween(sc, 0.12, { Scale = (down and live) and 0.94 or (hover and live) and 1.06 or t.selected and 1.04 or 1 }, Enum.EasingStyle.Back)
416→ end
417→ function t.setSelected(v2) t.selected = v2; paint() end
418→ function t.lock(text)
419→ t.locked = true
420→ local f = new("Frame", { Size = UDim2.fromScale(1, 1), BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = 0.12, ZIndex = z + 5, Parent = b }, { corner(UDim.new(0, 18)) })
421→ maxText(label({ Position = UDim2.fromScale(0.06, 0.2), Size = UDim2.fromScale(0.88, 0.6), Text = text, TextScaled = true, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = z + 6, Parent = f }, 2), 24)
422→ end
423→ function t.wiggle()
424→ tween(b, 0.05, { Rotation = -4 }).Completed:Wait()
425→ tween(b, 0.07, { Rotation = 4 }).Completed:Wait()
426→ tween(b, 0.06, { Rotation = 0 })
427→ end
428→ local hover = false
429→ b.MouseEnter:Connect(function() hover = true; paint(true) end)
430→ b.MouseLeave:Connect(function() hover = false; paint(false) end)
431→ b.InputBegan:Connect(function(i) if isPress(i) then paint(hover, true) end end)
432→ b.InputEnded:Connect(function(i) if isPress(i) then paint(hover) end end)
433→ return t
434→end
435→
436→---------------------------------------------------------------- pill button with states
437→local ART_FOR = { ready = "gold", alt = "blue", info = "blue", confirm = "red", danger = "red", done = "green", off = "grey", busy = "grey" }
438→local LIVE = { ready = true, alt = true, confirm = true, danger = true }
439→function K.pill(parent, props, onClick)
440→ local textMax = props.TextMax or 32
441→ props.TextMax = nil
442→ props.AutoButtonColor = false
443→ local b = art("gold", props, true)
444→ b.Parent = parent
445→ local p, z = b.Position, b.Size
446→ b.AnchorPoint = Vector2.new(0.5, 0.5)
447→ b.Position = p + UDim2.new(z.X.Scale / 2, z.X.Offset / 2, z.Y.Scale / 2, z.Y.Offset / 2)
448→ local sc = new("UIScale", { Parent = b })
449→ local ring = new("Frame", { AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), Size = UDim2.new(1, 4, 1, 4),
450→ BackgroundTransparency = 1, ZIndex = 1, Parent = b }, { corner(UDim.new(0.5, 0)) })
451→ local ringStroke = new("UIStroke", { Color = Color3.fromRGB(255, 240, 180), Thickness = 4, Transparency = 1, Parent = ring })
452→ local cap = maxText(label({ Position = UDim2.fromScale(0.08, 0.16), Size = UDim2.fromScale(0.84, 0.62), Text = "", TextScaled = true,
453→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = (props.ZIndex or 1) + 1, Parent = b }, 2.5), textMax)
454→ local o = { button = b, state = "ready", hover = false }
455→ local dots
456→ local function paint()
457→ local s = o.state
458→ setArt(b, ART_FOR[s] or "gold")
459→ local live = LIVE[s] == true
460→ b.ImageColor3 = (o.down and live) and Color3.fromRGB(205, 205, 205) or WHITE
461→ cap.TextColor3 = s == "off" and Color3.fromRGB(214, 220, 226) or WHITE
462→ cap.Position = UDim2.fromScale(0.08, (o.down and live) and 0.2 or 0.16)
463→ ringStroke.Transparency = (o.hover and live) and 0.15 or 1
464→ local target = not live and 1 or o.down and 0.94 or o.hover and 1.05 or 1
465→ tween(sc, o.down and 0.07 or 0.14, { Scale = target }, o.down and Enum.EasingStyle.Quad or Enum.EasingStyle.Back)
466→ end
467→ function o.set(state, caption)
468→ if caption then cap.Text = caption end
469→ if state == o.state and state ~= "busy" then paint() return end
470→ if state == "busy" and o.state == "busy" then return end
471→ o.state = state
472→ b.Active = LIVE[state] == true
473→ b.Selectable = b.Active
474→ if state == "busy" then
475→ local my = {}
476→ dots = my
477→ task.spawn(function()
478→ local n = 0
479→ while dots == my and o.state == "busy" do
480→ n = n % 3 + 1
481→ cap.Text = string.rep("•", n)
482→ task.wait(0.25)
483→ end
484→ end)
485→ else
486→ dots = nil
487→ end
488→ paint()
489→ end
490→ function o.wiggle()
491→ tween(b, 0.05, { Rotation = -3 }).Completed:Wait()
492→ tween(b, 0.07, { Rotation = 3 }).Completed:Wait()
493→ tween(b, 0.06, { Rotation = 0 })
494→ end
495→ b.MouseEnter:Connect(function() o.hover = true; paint() end)
496→ b.MouseLeave:Connect(function() o.hover, o.down = false, false; paint() end)
497→ b.SelectionGained:Connect(function() o.hover = true; paint() end)
498→ b.SelectionLost:Connect(function() o.hover = false; paint() end)
499→ b.InputBegan:Connect(function(input) if isPress(input) then o.down = true; paint() end end)
500→ b.InputEnded:Connect(function(input) if isPress(input) then o.down = false; paint() end end)
501→ b.Activated:Connect(function()
502→ if LIVE[o.state] then
503→ onClick(o.state)
504→ elseif o.state == "off" then
505→ o.wiggle() -- "can't"
506→ end
507→ end)
508→ paint()
509→ return o
510→end
511→
512→---------------------------------------------------------------- filter chip (green; gold when selected)
513→function K.chip(parent, props, text, onClick, dot)
514→ props.AutoButtonColor = false
515→ local b = art("green", props, true)
516→ b.Parent = parent
517→ local sc = new("UIScale", { Parent = b })
518→ local z = (props.ZIndex or 4) + 1
519→ local x0 = 0.1
520→ if dot then
521→ new("Frame", { AnchorPoint = Vector2.new(0, 0.5), Position = UDim2.new(0.08, 0, 0.47, 0), Size = UDim2.fromOffset(18, 18), BackgroundColor3 = dot, ZIndex = z, Parent = b },
522→ { corner(UDim.new(0.5, 0)), new("UIStroke", { Color = INK, Thickness = 2 }) })
523→ x0 = 0.2
524→ end
525→ local cap = maxText(label({ Position = UDim2.fromScale(x0, 0.18), Size = UDim2.fromScale(0.92 - x0, 0.58), Text = text, TextScaled = true,
526→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = z, Parent = b }, 2), 24)
527→ local o = { button = b, selected = false, hover = false, down = false }
528→ local function paint()
529→ setArt(b, o.selected and "gold" or "green")
530→ b.ImageColor3 = o.down and Color3.fromRGB(205, 205, 205) or WHITE
531→ cap.TextColor3 = o.selected and WHITE or Color3.fromRGB(236, 248, 238)
532→ tween(sc, 0.12, { Scale = o.down and 0.95 or (o.hover or o.selected) and 1.04 or 1 }, Enum.EasingStyle.Back)
533→ end
534→ function o.setSelected(v) o.selected = v; paint() end
535→ b.MouseEnter:Connect(function() o.hover = true; paint() end)
536→ b.MouseLeave:Connect(function() o.hover, o.down = false, false; paint() end)
537→ b.InputBegan:Connect(function(input) if isPress(input) then o.down = true; paint() end end)
538→ b.InputEnded:Connect(function(input) if isPress(input) then o.down = false; paint() end end)
539→ b.Activated:Connect(function() onClick() end)
540→ paint()
541→ return o
542→end
543→
544→-- price plate: crystal + number (orange when you can not afford it)
545→function K.pricePlate(parent, pos, size, z)
546→ z = z or 3
547→ local f = new("Frame", { Position = pos, Size = size, BackgroundColor3 = NAVY, BackgroundTransparency = 0.1, ZIndex = z, Parent = parent }, {
548→ corner(UDim.new(0.5, 0)), new("UIStroke", { Color = Color3.fromRGB(190, 225, 255), Thickness = 2 }),
549→ })
550→ art("crystal", { Position = UDim2.new(0, -10, 0.5, -30), Size = UDim2.fromOffset(60, 60), ZIndex = z + 1, Parent = f })
551→ local t = maxText(label({ Position = UDim2.new(0, 52, 0, 4), Size = UDim2.new(1, -62, 1, -8), Text = "", TextScaled = true,
552→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = z + 1, Parent = f }, 2), 32)
553→ return f, t
554→end
555→
556→---------------------------------------------------------------- window frame + tabs
557→-- opts: win, title, subtitle, tabs = { { id, text, icon, tip } }, closeWindow, fmtNum, onTab(id)
558→K.AREA_POS, K.AREA_SIZE = UDim2.fromOffset(70, 346), UDim2.fromOffset(1260, 566)
559→function K.chrome(opts)
560→ local win = opts.win
561→ local panel = win.panel
562→ local WIDTH, HEIGHT = 1400, 1000
563→ win.w, win.h = WIDTH, HEIGHT
564→ panel.Size = UDim2.fromOffset(WIDTH, HEIGHT)
565→ panel.BackgroundTransparency = 1
566→ for _, c in panel:GetChildren() do
567→ if c:IsA("UIStroke") then c.Enabled = false end
568→ if c:IsA("Frame") then c.Visible = false end -- makeWindow's title bar
569→ end
570→ local fmt = opts.fmtNum
571→
572→ local bg = new("Frame", { Name = "Bg", Size = UDim2.fromScale(1, 1), BackgroundColor3 = WHITE, ZIndex = 0, Parent = panel }, {
573→ corner(UDim.new(0, 44)),
574→ new("UIGradient", { Rotation = 90, Color = ColorSequence.new(Color3.fromRGB(22, 84, 70), Color3.fromRGB(8, 36, 44)) }),
575→ new("UIStroke", { Name = "GoldEdge", Color = Color3.fromRGB(242, 196, 82), Thickness = 5 }),
576→ })
577→ new("Frame", { Position = UDim2.fromOffset(12, 12), Size = UDim2.new(1, -24, 1, -24), BackgroundTransparency = 1, ZIndex = 0, Parent = bg }, {
578→ corner(UDim.new(0, 36)), new("UIStroke", { Color = GOLD, Thickness = 2, Transparency = 0.55 }),
579→ })
580→ -- twinkling stars in the header sky
581→ local rng = Random.new(7)
582→ for _ = 1, 26 do
583→ local s = rng:NextInteger(3, 7)
584→ local star = new("Frame", { Position = UDim2.fromOffset(rng:NextInteger(40, 1360), rng:NextInteger(24, 190)), Size = UDim2.fromOffset(s, s),
585→ BackgroundColor3 = WHITE, BackgroundTransparency = rng:NextNumber(0.2, 0.6), ZIndex = 1, Parent = panel }, { corner(UDim.new(0.5, 0)) })
586→ local delay0 = rng:NextNumber(0, 3)
587→ task.spawn(function()
588→ task.wait(delay0)
589→ while star.Parent do
590→ tween(star, 1.4, { BackgroundTransparency = 0.85 }, Enum.EasingStyle.Sine).Completed:Wait()
591→ tween(star, 1.4, { BackgroundTransparency = 0.2 }, Enum.EasingStyle.Sine).Completed:Wait()
592→ end
593→ end)
594→ end
595→ art("garland", { Position = UDim2.fromOffset(20, -70), Size = UDim2.fromOffset(330, 330), ScaleType = Enum.ScaleType.Fit, ZIndex = 2, Parent = panel })
596→ art("garland", { Position = UDim2.fromOffset(1050, -70), Size = UDim2.fromOffset(330, 330), ScaleType = Enum.ScaleType.Fit, ZIndex = 2, Parent = panel })
597→
598→ -- ribbon title + subtitle
599→ local ribbon = art("ribbon", { AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.fromOffset(WIDTH / 2, -22), Size = UDim2.fromOffset(480, 271), ZIndex = 3, Parent = panel })
600→ maxText(label({ Position = UDim2.fromScale(0.14, 0.5), Size = UDim2.fromScale(0.72, 0.25), Text = opts.title, TextScaled = true,
601→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 4, Parent = ribbon }, 3.5), 64)
602→ maxText(label({ Position = UDim2.fromOffset(60, 132), Size = UDim2.fromOffset(330, 56), Text = opts.subtitle or "", TextScaled = true,
603→ TextColor3 = SOFT, FontFace = BODY, ZIndex = 3, Parent = panel }, 1.5), 24)
604→
605→ -- balance plate (animated count)
606→ local balance = art("blue", { Position = UDim2.fromOffset(1000, 120), Size = UDim2.fromOffset(250, 84), ZIndex = 3, Parent = panel })
607→ art("crystal", { Position = UDim2.fromOffset(-26, -10), Size = UDim2.fromOffset(100, 100), ZIndex = 4, Parent = balance })
608→ local balanceText = maxText(label({ Position = UDim2.fromOffset(72, 12), Size = UDim2.new(1, -90, 1, -24), Text = "0", TextScaled = true,
609→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 4, Parent = balance }, 3), 40)
610→ local lastShown = 0
611→ local function setBalance(v, instant)
612→ local from = lastShown
613→ lastShown = v
614→ if instant or from == v or not win.overlay.Visible then balanceText.Text = fmt(v) return end
615→ local nv = Instance.new("NumberValue")
616→ nv.Value = from
617→ nv.Changed:Connect(function(x) balanceText.Text = fmt(x) end)
618→ tween(nv, 0.45, { Value = v }).Completed:Connect(function() balanceText.Text = fmt(v); nv:Destroy() end)
619→ end
620→
621→ -- close: drawn in code (red glossy square, gold rim, snow cap, "X"; Fredoka has no ✕ glyph)
622→ local close = new("TextButton", { Name = "Close", AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromOffset(1320, 92), Size = UDim2.fromOffset(96, 96), Text = "",
623→ BackgroundColor3 = Color3.fromRGB(214, 36, 46), AutoButtonColor = false, ZIndex = 5, Parent = panel }, {
624→ corner(UDim.new(0, 24)),
625→ new("UIStroke", { Color = GOLD, Thickness = 5, ApplyStrokeMode = Enum.ApplyStrokeMode.Border }),
626→ })
627→ new("Frame", { AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 6), Size = UDim2.new(1, -16, 0.4, 0), BackgroundColor3 = WHITE,
628→ BackgroundTransparency = 0.8, ZIndex = 6, Parent = close }, { corner(UDim.new(0, 18)), new("UIGradient", { Rotation = 90, Transparency = NumberSequence.new(0.1, 1) }) })
629→ new("Frame", { Position = UDim2.new(0, -6, 0, -12), Size = UDim2.new(1, 12, 0, 24), BackgroundColor3 = Color3.fromRGB(245, 250, 255), ZIndex = 8, Parent = close }, {
630→ corner(UDim.new(0.5, 0)), new("UIGradient", { Rotation = 90, Color = ColorSequence.new(WHITE, Color3.fromRGB(205, 222, 240)) }),
631→ })
632→ label({ Position = UDim2.fromScale(0.14, 0.16), Size = UDim2.fromScale(0.72, 0.72), Text = "X", TextScaled = true, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 7, Parent = close }, 3)
633→ local closeScale = new("UIScale", { Parent = close })
634→ close.MouseEnter:Connect(function() tween(closeScale, 0.14, { Scale = 1.08 }, Enum.EasingStyle.Back); tween(close, 0.14, { Rotation = 6 }) end)
635→ close.MouseLeave:Connect(function() tween(closeScale, 0.14, { Scale = 1 }); tween(close, 0.14, { Rotation = 0 }) end)
636→ close.InputBegan:Connect(function(i) if isPress(i) then tween(closeScale, 0.06, { Scale = 0.92 }) end end)
637→ close.Activated:Connect(function() opts.closeWindow() end)
638→
639→ -- content panel + footer tip
640→ art("panel", { Position = UDim2.fromOffset(40, 300), Size = UDim2.fromOffset(1320, 632), ScaleType = Enum.ScaleType.Slice,
641→ SliceCenter = Rect.new(60, 70, 218, 180), ZIndex = 2, Parent = panel })
642→ art("holly", { Position = UDim2.fromOffset(1262, 262), Size = UDim2.fromOffset(130, 130), ScaleType = Enum.ScaleType.Fit, ZIndex = 6, Parent = panel })
643→ art("gift", { Position = UDim2.fromOffset(-34, 850), Size = UDim2.fromOffset(150, 150), ScaleType = Enum.ScaleType.Fit, ZIndex = 6, Parent = panel })
644→ local tip = maxText(label({ Position = UDim2.fromOffset(130, 940), Size = UDim2.fromOffset(1140, 44), Text = "", TextScaled = true, FontFace = BODY,
645→ TextColor3 = SOFT, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 3, Parent = panel }, 1.5), 26)
646→
647→ -- pages: a CanvasGroup each (fade + slide on switch)
648→ local AREA_POS, AREA_SIZE = K.AREA_POS, K.AREA_SIZE
649→ local pages = {}
650→ local function makePage(id, withScroll)
651→ local g = new("CanvasGroup", { Name = "Page" .. id, Position = AREA_POS, Size = AREA_SIZE, BackgroundTransparency = 1, Visible = false, ZIndex = 4, Parent = panel })
652→ pages[id] = { group = g }
653→ if withScroll then
654→ return g, K.scroll(g, UDim2.new(), UDim2.fromScale(1, 1))
655→ end
656→ return g
657→ end
658→
659→ -- tabs
660→ local tabs, current = {}, nil
661→ local self = { panel = panel, tabs = tabs, makePage = makePage, setBalance = setBalance, tip = tip }
662→ local startX = math.floor((WIDTH - (#opts.tabs * 300 + (#opts.tabs - 1) * 22)) / 2)
663→ for i, t in opts.tabs do
664→ local x = startX + (i - 1) * 322
665→ local b = art("green", { Name = "Tab" .. t.id, AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromOffset(x + 150, 258), Size = UDim2.fromOffset(300, 96),
666→ AutoButtonColor = false, ZIndex = 3, Parent = panel }, true)
667→ local sc = new("UIScale", { Parent = b })
668→ local ring = new("Frame", { AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), Size = UDim2.new(1, 4, 1, 4), BackgroundTransparency = 1, Parent = b }, { corner(UDim.new(0.5, 0)) })
669→ local ringStroke = new("UIStroke", { Color = Color3.fromRGB(255, 240, 180), Thickness = 4, Transparency = 1, Parent = ring })
670→ label({ Position = UDim2.fromScale(0.07, 0.17), Size = UDim2.fromScale(0.2, 0.62), Text = t.icon, TextScaled = true, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 4, Parent = b }, 0)
671→ local cap = maxText(label({ Position = UDim2.fromScale(0.27, 0.17), Size = UDim2.fromScale(0.66, 0.6), Text = t.text, TextScaled = true,
672→ TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 4, Parent = b }, 2.5), 34)
673→ local badge = new("Frame", { AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.new(1, -18, 0, 10), Size = UDim2.fromOffset(46, 46),
674→ BackgroundColor3 = Color3.fromRGB(226, 40, 52), Visible = false, ZIndex = 6, Parent = b }, { corner(UDim.new(0.5, 0)), new("UIStroke", { Color = WHITE, Thickness = 3 }) })
675→ local badgeText = label({ Size = UDim2.fromScale(1, 1), Text = "", TextScaled = true, TextXAlignment = Enum.TextXAlignment.Center, ZIndex = 7, Parent = badge }, 1.5)
676→ new("UIPadding", { PaddingTop = UDim.new(0.2, 0), PaddingBottom = UDim.new(0.2, 0), PaddingLeft = UDim.new(0.15, 0), PaddingRight = UDim.new(0.15, 0), Parent = badge })
677→ local badgeScale = new("UIScale", { Parent = badge })
678→ local o = { button = b, hover = false, down = false, count = 0 }
679→ function o.paint()
680→ local sel = current == t.id
681→ setArt(b, sel and "red" or "green")
682→ b.ImageColor3 = (o.down and not sel) and Color3.fromRGB(205, 205, 205) or WHITE
683→ cap.TextColor3 = sel and WHITE or Color3.fromRGB(236, 248, 238)
684→ ringStroke.Transparency = (o.hover and not sel) and 0.2 or 1
685→ b.Position = UDim2.fromOffset(x + 150, sel and 252 or 258)
686→ tween(sc, 0.14, { Scale = o.down and 0.95 or sel and 1.07 or o.hover and 1.04 or 1 }, Enum.EasingStyle.Back)
687→ end
688→ function o.setBadge(n)
689→ badge.Visible = n > 0
690→ badgeText.Text = n > 9 and "9+" or tostring(n)
691→ if n > o.count then
692→ badgeScale.Scale = 1.5
693→ tween(badgeScale, 0.3, { Scale = 1 }, Enum.EasingStyle.Back)
694→ end
695→ o.count = n
696→ end
697→ b.MouseEnter:Connect(function() o.hover = true; o.paint() end)
698→ b.MouseLeave:Connect(function() o.hover, o.down = false, false; o.paint() end)
699→ b.SelectionGained:Connect(function() o.hover = true; o.paint() end)
700→ b.SelectionLost:Connect(function() o.hover = false; o.paint() end)
701→ b.InputBegan:Connect(function(input) if isPress(input) then o.down = true; o.paint() end end)
702→ b.InputEnded:Connect(function(input) if isPress(input) then o.down = false; o.paint() end end)
703→ b.Activated:Connect(function() self.showTab(t.id) end)
704→ tabs[t.id] = o
705→ end
706→
707→ function self.current() return current end
708→ function self.showTab(id, force)
709→ if current == id and not force then return end
710→ local prev = current
711→ current = id
712→ for _, t in tabs do t.paint() end
713→ for pid, p in pages do
714→ if pid == id then
715→ p.group.Visible = true
716→ if prev ~= id then
717→ p.group.GroupTransparency = 1
718→ p.group.Position = AREA_POS + UDim2.fromOffset(0, 24)
719→ tween(p.group, 0.22, { GroupTransparency = 0, Position = AREA_POS })
720→ end
721→ elseif pid == prev then
722→ p.group.Visible = false
723→ end
724→ end
725→ for _, t in opts.tabs do if t.id == id then tip.Text = t.tip; tip.TextColor3 = SOFT end end
726→ if opts.onTab then opts.onTab(id) end
727→ end
728→ return self
729→end
730→
731→return K
732→