BADABATS

Player Data Handler

May 20th, 2025
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.55 KB | None | 0 0
  1. local HTTP = game:GetService("HttpService")
  2. local ReplicatedStorage = game:GetService("ReplicatedStorage")
  3.  
  4. local ItemHandler = require(ReplicatedStorage:WaitForChild("Modules"):WaitForChild("ItemHandler"))
  5. local GrowPlaceHandler = require(ReplicatedStorage:WaitForChild("Modules"):WaitForChild("GrowPlaceHandler"))
  6. local UpdateMachine = ReplicatedStorage:WaitForChild("Events"):WaitForChild("RemoteEvents"):WaitForChild("Updatemachine")
  7.  
  8. local Data = {}
  9.  
  10. local playerData = {}
  11.  
  12. -- Initialize player data when they join
  13. function Data.Setup(player, data)
  14. -- store playerData in module
  15. print(data)
  16. playerData[player] = data[player]
  17. GrowPlaceHandler.SpawnInPlot(player, data) --change later to assigned plot
  18. Data.LoadPlayerMachines(player)
  19.  
  20. -- setup initial things such as spawn in player at right place or fill all invenotory slots etc..
  21. end
  22.  
  23. -- Function to calculate total weight of current inventory
  24. function Data.CalculateInventoryWeight(inventory)
  25. local totalWeight = 0
  26. for itemName, amount in pairs(inventory) do
  27. local itemWeight = ItemHandler[itemName].Weight
  28. totalWeight += itemWeight * amount
  29. end
  30. return totalWeight
  31. end
  32.  
  33. -- Handles adding or removing items from the player's inventory
  34. function Data.PlayerInventoryHandler(player, itemName, amount, remove)
  35. if not playerData[player] then
  36. warn("Player data not found.")
  37. return false, "Player data not found. Try rejoining"
  38. end
  39. if not ItemHandler[itemName]then
  40. return
  41. end
  42.  
  43. print(itemName)
  44. local itemWeight = ItemHandler[itemName].Weight
  45. if not itemWeight then
  46. warn("Item has no weight" .. itemName)
  47. return false, "Item has no weight! Contact a developer"
  48. end
  49.  
  50. local currentInventoryWeight = Data.CalculateInventoryWeight(playerData[player].Inventory)
  51. local additionalWeight = itemWeight * amount
  52.  
  53. if remove then
  54. if not playerData[player].Inventory[itemName] or playerData[player].Inventory[itemName] < amount then
  55. return false, "Dont have enough items to sell!"
  56. end
  57.  
  58. playerData[player].Inventory[itemName] = playerData[player].Inventory[itemName] - amount
  59.  
  60. -- If the item count drops to 0, remove the item from the inventory
  61. if playerData[player].Inventory[itemName] <= 0 then
  62. playerData[player].Inventory[itemName] = nil
  63. end
  64.  
  65. else
  66. -- Check if the total weight exceeds the limit when adding
  67. if currentInventoryWeight + additionalWeight > playerData[player].InventorySize then
  68. warn("Cannot add item, inventory weight exceeds limit!")
  69. -- You can trigger a UI event to notify the player
  70. return false, "Inventory weight exceeds limit!!!"
  71. end
  72.  
  73. -- Add the item to the inventory
  74. playerData[player].Inventory[itemName] = (playerData[player].Inventory[itemName] or 0) + amount
  75. print("Added to Inventory", playerData[player].Inventory)
  76. end
  77.  
  78. return true
  79. end
  80.  
  81. -- CashHandler function with buying and selling logic
  82. function Data.CashHandler(player, amount, itemName, buy, dealerName)
  83. if playerData[player] then
  84. -- Fetch the price of the item from the PricesModule
  85. print(player, amount, itemName, buy, dealerName)
  86. local itemPrice = ItemHandler[itemName].Price
  87. print(itemPrice)
  88. if not itemPrice then
  89. warn("Item price not found for: " .. itemName)
  90. return false, "Did not find item! Conctact a developer."
  91. end
  92.  
  93. -- Calculate the total cost based on the amount the player is buying/selling
  94. local totalCost = itemPrice * amount
  95.  
  96. -- Handle buying logic
  97. if buy then
  98.  
  99. itemPrice = ItemHandler[itemName].Price
  100. totalCost = itemPrice * amount
  101.  
  102. if totalCost <= playerData[player].Cash then
  103.  
  104. local succes1, message1 = Data.PlayerInventoryHandler(player, itemName, amount, false)
  105.  
  106. if not succes1 then
  107. return false, message1
  108. end
  109.  
  110. playerData[player].Cash -= totalCost
  111.  
  112. return true
  113. else
  114. -- Handle insufficient cash
  115. local remaining = math.abs(totalCost - playerData[player].Cash)
  116.  
  117. return false, "Not enough cash!"
  118. end
  119.  
  120. -- Handle selling logic
  121. elseif not buy then
  122.  
  123.  
  124. if not Data.PlayerInventoryHandler(player, itemName, amount, true) then
  125. warn("Not enough items to sell.") --update localplayer here
  126. return false, "Not enough items to sell!"
  127. end
  128.  
  129. playerData[player].Cash += totalCost
  130.  
  131. return true
  132. else
  133. warn("Invalid operation. Specify whether to buy or sell.")
  134. return false, "Invalid operation. Contact developer ASAP"
  135. end
  136. else
  137. warn("Player data not found.")
  138. return false, "Player data not found. Try rejoining"
  139. end
  140. end
  141.  
  142. function Data.GrowPlaceHandler(player, item, cf, add, remove)
  143. -- Check if player data exists
  144. if not playerData[player] then
  145. warn("Player data not found.")
  146. return false
  147. end
  148.  
  149. if add and item and cf then
  150. -- Extract position (X, Y, Z) from the CFrame
  151. local position = {cf.X, cf.Y, cf.Z}
  152.  
  153. -- Extract rotation matrix components from CFrame
  154. local _, _, _, r1c1, r1c2, r1c3, r2c1, r2c2, r2c3, r3c1, r3c2, r3c3 = cf:components()
  155.  
  156. -- Calculate yaw, pitch, and roll in degrees
  157. local yaw = math.deg(math.atan2(r1c3, r3c3))
  158. local pitch = math.deg(math.asin(-r2c3))
  159. local roll = math.deg(math.atan2(r2c1, r2c2))
  160.  
  161. -- Structure the GrowPlace data with orientation in degrees
  162. playerData[player].GrowPlace[item.Name] = {
  163. cframe = {
  164. position = position,
  165. orientation = {roll, yaw, pitch} -- Store orientation as {roll, pitch, yaw}
  166. },
  167. Inventory = {},
  168. Finished = {},
  169. Recipe = {},
  170. Timer = 0,
  171. Repeat = 0
  172. }
  173.  
  174. print("placed item", playerData[player].GrowPlace)
  175. end
  176.  
  177.  
  178. if remove then
  179. --Removes numbers from the item
  180. local test = item.Name:match("^(%a+)")
  181. local itemName = test:match("^(%a+)")
  182. --Calculate if everything fits in the inventory
  183. local currentInventoryWeight = Data.CalculateInventoryWeight(playerData[player].Inventory)
  184. local currentItemInventoryWeight = Data.CalculateInventoryWeight(playerData[player].GrowPlace[item.Name].Inventory)
  185. local currentItemFinishedWeight = Data.CalculateInventoryWeight(playerData[player].GrowPlace[item.Name].Finished)
  186. local MachineWeight = ItemHandler[itemName].Weight
  187. if currentInventoryWeight + currentItemInventoryWeight + MachineWeight + currentItemFinishedWeight > playerData[player].InventorySize then
  188. warn("Cannot remove ".. itemName .. " not enough space in inventory")
  189.  
  190. return false
  191. else
  192. --Put everything in back in the inventory
  193. for _, Table in ipairs({playerData[player].GrowPlace[item.Name].Inventory, playerData[player].GrowPlace[item.Name].Finished}) do
  194. for ProductName, Amount in pairs(Table) do
  195. Data.PlayerInventoryHandler(player, ProductName, Amount, false)
  196. end
  197. end
  198. Data.PlayerInventoryHandler(player, itemName, 1, false)
  199.  
  200. playerData[player].GrowPlace[item.Name] = nil
  201. print("Removed", playerData[player].GrowPlace)
  202. return true
  203. end
  204. end
  205. end
  206.  
  207. function Data.Lock(player, start)
  208. local state = playerData[player].GrowPlace.Lock
  209.  
  210. if start then return state end
  211.  
  212. if state == "Locked" then
  213. playerData[player].GrowPlace.Lock = "Friends"
  214.  
  215. elseif state == "Friends" then
  216. playerData[player].GrowPlace.Lock = "Unlocked"
  217.  
  218. elseif state == "Unlocked" then
  219. playerData[player].GrowPlace.Lock = "Locked"
  220.  
  221. else
  222. warn("No locked state found")
  223. playerData[player].GrowPlace.Lock = "Locked"
  224.  
  225. end
  226.  
  227. state = playerData[player].GrowPlace.Lock
  228. return state
  229. end
  230.  
  231. local function CompleteMachineProcess(player, machine)
  232. if not playerData[player] then return end -- Ensure player data exists
  233.  
  234. local machineData = playerData[player].GrowPlace[machine.Name]
  235. if not machineData or not machineData.Recipe then return end
  236.  
  237. local product = machineData.Recipe
  238.  
  239. -- Ensure "Finished" table exists
  240. machineData.Finished = machineData.Finished or {}
  241.  
  242. -- Store finished product in the "Finished" table
  243. machineData.Finished[product] = (machineData.Finished[product] or 0) + 1
  244.  
  245. -- Remove only the required ingredients for **one** product
  246. for i, ingredient in pairs(ItemHandler[product].Input) do
  247. Data.PlayerInventoryHandler(player, ingredient, 1, true) -- Remove 1 per product completion
  248. if machineData.Inventory[ingredient] then
  249. machineData.Inventory[ingredient] -= 1 -- Reduce from machine inventory
  250. if machineData.Inventory[ingredient] <= 0 then
  251. machineData.Inventory[ingredient] = nil -- Remove ingredient if it's empty
  252. end
  253. end
  254. end
  255.  
  256. UpdateMachine:FireClient(player, machineData, machine, nil, true)
  257. print("Product completed: " .. product .. " has been added to the Finished table!")
  258. end
  259.  
  260. local function StartMachineTimer(machine, player, remainingtime)
  261. local machineData = playerData[player] and playerData[player].GrowPlace[machine.Name]
  262. if not machineData or machineData.Repeat <= 0 then return end
  263.  
  264. task.spawn(function()
  265. while machineData.Repeat > 0 do
  266. if not machineData.Recipe then return end
  267.  
  268. local repeatTime
  269. if not remainingtime then
  270. repeatTime = ItemHandler[machineData.Recipe].Time
  271. else
  272. repeatTime = remainingtime
  273. end
  274. print("Starting cooking:", machineData.Recipe, "- Remaining:", machineData.Repeat)
  275.  
  276. machineData.Timer = repeatTime
  277.  
  278. while machineData.Timer > 0 do
  279. if not playerData[player] then
  280. print("Player left, pausing machine:", machine.Name)
  281. return
  282. end
  283.  
  284. machineData.Timer -= 1
  285. UpdateMachine:FireClient(player, machineData, machine, repeatTime, false)
  286. task.wait(1)
  287. end
  288.  
  289. if machineData.Timer <= 0 then
  290. print("Timer complete! Processing:", machine.Name)
  291. CompleteMachineProcess(player, machine)
  292. machineData.Repeat -= 1
  293. end
  294. end
  295.  
  296. machineData.Timer = 0
  297. print("All products finished, resetting machine:", machine.Name)
  298. end)
  299. end
  300.  
  301. function Data.LoadPlayerMachines(player)
  302. if not playerData[player] then return end
  303.  
  304. for machineName, machineData in pairs(playerData[player].GrowPlace) do
  305. if machineData.Repeat and machineData.Repeat > 0 then
  306. local house = playerData[player].GrowPlace.GPLevel
  307. local machineInstance = workspace:WaitForChild("Houses")[house][house .. player.Name]:WaitForChild("Plot"):WaitForChild("GrowItemHolder"):FindFirstChild(machineName)
  308.  
  309. if machineInstance then
  310. print("Resuming machine:", machineName, "with", machineData.Timer, "seconds left and", machineData.Repeat, "items left.")
  311. StartMachineTimer(machineInstance, player, machineData.Timer)
  312. else
  313. warn("Machine instance not found for:", machineName)
  314. end
  315. end
  316. end
  317. end
  318.  
  319. function Data.Machines(player, amount, product, cook, machine)
  320. print(player, amount, product, cook, machine.Parent)
  321.  
  322. if not playerData[player] or not playerData[player].Inventory then
  323. return false, "Player data not found!"
  324. end
  325.  
  326. local machineData = playerData[player].GrowPlace[machine.Name]
  327. if not machineData then
  328. return false, "Invalid machine!"
  329. end
  330.  
  331. -- Check if the machine is already running
  332. if machineData.Timer > 0 then
  333. return false, "Machine is already running!"
  334. end
  335.  
  336. -- Calculate required ingredients
  337. local requiredIngredients = {}
  338. for _, input in pairs(ItemHandler[product].Input) do
  339. requiredIngredients[input] = (requiredIngredients[input] or 0) + amount
  340. end
  341.  
  342. -- Check if the player has all required ingredients
  343. for ingredient, requiredAmount in pairs(requiredIngredients) do
  344. local playerAmount = playerData[player].Inventory[ingredient] or 0
  345. if playerAmount < requiredAmount then
  346. return false, "Not enough " .. ingredient .. "! Required: " .. requiredAmount .. ", You have: " .. playerAmount
  347. end
  348. end
  349.  
  350. -- Move ingredients from player inventory to machine inventory using `PlayerInventoryHandler`
  351. machineData.Inventory = machineData.Inventory or {}
  352. for ingredient, requiredAmount in pairs(requiredIngredients) do
  353. Data.PlayerInventoryHandler(player, ingredient, requiredAmount, true) -- ✅ Remove from player
  354. machineData.Inventory[ingredient] = (machineData.Inventory[ingredient] or 0) + requiredAmount
  355. end
  356.  
  357. -- Set machine's recipe and timer
  358. machineData.Recipe = product
  359. machineData.Timer = ItemHandler[product].Time -- Time for **one** product
  360. machineData.Repeat = amount -- Number of products to make
  361.  
  362. -- Start the countdown on the server
  363. StartMachineTimer(machine, player)
  364.  
  365. return true, "Cooking started!"
  366. end
  367.  
  368.  
  369. --Get player data
  370. function Data.GetData(player, otherplayers)
  371. if not otherplayers then return playerData[player] end
  372. if otherplayers then return playerData[otherplayers] end
  373. end
  374.  
  375. -- Function to clean up player data when they leave
  376. function Data.Cleanup(player)
  377. GrowPlaceHandler.RemoveHouseOnLeave(player)
  378. playerData[player] = nil
  379. end
  380.  
  381. return Data
  382.  
Add Comment
Please, Sign In to add comment