Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local HTTP = game:GetService("HttpService")
- local ReplicatedStorage = game:GetService("ReplicatedStorage")
- local ItemHandler = require(ReplicatedStorage:WaitForChild("Modules"):WaitForChild("ItemHandler"))
- local GrowPlaceHandler = require(ReplicatedStorage:WaitForChild("Modules"):WaitForChild("GrowPlaceHandler"))
- local UpdateMachine = ReplicatedStorage:WaitForChild("Events"):WaitForChild("RemoteEvents"):WaitForChild("Updatemachine")
- local Data = {}
- local playerData = {}
- -- Initialize player data when they join
- function Data.Setup(player, data)
- -- store playerData in module
- print(data)
- playerData[player] = data[player]
- GrowPlaceHandler.SpawnInPlot(player, data) --change later to assigned plot
- Data.LoadPlayerMachines(player)
- -- setup initial things such as spawn in player at right place or fill all invenotory slots etc..
- end
- -- Function to calculate total weight of current inventory
- function Data.CalculateInventoryWeight(inventory)
- local totalWeight = 0
- for itemName, amount in pairs(inventory) do
- local itemWeight = ItemHandler[itemName].Weight
- totalWeight += itemWeight * amount
- end
- return totalWeight
- end
- -- Handles adding or removing items from the player's inventory
- function Data.PlayerInventoryHandler(player, itemName, amount, remove)
- if not playerData[player] then
- warn("Player data not found.")
- return false, "Player data not found. Try rejoining"
- end
- if not ItemHandler[itemName]then
- return
- end
- print(itemName)
- local itemWeight = ItemHandler[itemName].Weight
- if not itemWeight then
- warn("Item has no weight" .. itemName)
- return false, "Item has no weight! Contact a developer"
- end
- local currentInventoryWeight = Data.CalculateInventoryWeight(playerData[player].Inventory)
- local additionalWeight = itemWeight * amount
- if remove then
- if not playerData[player].Inventory[itemName] or playerData[player].Inventory[itemName] < amount then
- return false, "Dont have enough items to sell!"
- end
- playerData[player].Inventory[itemName] = playerData[player].Inventory[itemName] - amount
- -- If the item count drops to 0, remove the item from the inventory
- if playerData[player].Inventory[itemName] <= 0 then
- playerData[player].Inventory[itemName] = nil
- end
- else
- -- Check if the total weight exceeds the limit when adding
- if currentInventoryWeight + additionalWeight > playerData[player].InventorySize then
- warn("Cannot add item, inventory weight exceeds limit!")
- -- You can trigger a UI event to notify the player
- return false, "Inventory weight exceeds limit!!!"
- end
- -- Add the item to the inventory
- playerData[player].Inventory[itemName] = (playerData[player].Inventory[itemName] or 0) + amount
- print("Added to Inventory", playerData[player].Inventory)
- end
- return true
- end
- -- CashHandler function with buying and selling logic
- function Data.CashHandler(player, amount, itemName, buy, dealerName)
- if playerData[player] then
- -- Fetch the price of the item from the PricesModule
- print(player, amount, itemName, buy, dealerName)
- local itemPrice = ItemHandler[itemName].Price
- print(itemPrice)
- if not itemPrice then
- warn("Item price not found for: " .. itemName)
- return false, "Did not find item! Conctact a developer."
- end
- -- Calculate the total cost based on the amount the player is buying/selling
- local totalCost = itemPrice * amount
- -- Handle buying logic
- if buy then
- itemPrice = ItemHandler[itemName].Price
- totalCost = itemPrice * amount
- if totalCost <= playerData[player].Cash then
- local succes1, message1 = Data.PlayerInventoryHandler(player, itemName, amount, false)
- if not succes1 then
- return false, message1
- end
- playerData[player].Cash -= totalCost
- return true
- else
- -- Handle insufficient cash
- local remaining = math.abs(totalCost - playerData[player].Cash)
- return false, "Not enough cash!"
- end
- -- Handle selling logic
- elseif not buy then
- if not Data.PlayerInventoryHandler(player, itemName, amount, true) then
- warn("Not enough items to sell.") --update localplayer here
- return false, "Not enough items to sell!"
- end
- playerData[player].Cash += totalCost
- return true
- else
- warn("Invalid operation. Specify whether to buy or sell.")
- return false, "Invalid operation. Contact developer ASAP"
- end
- else
- warn("Player data not found.")
- return false, "Player data not found. Try rejoining"
- end
- end
- function Data.GrowPlaceHandler(player, item, cf, add, remove)
- -- Check if player data exists
- if not playerData[player] then
- warn("Player data not found.")
- return false
- end
- if add and item and cf then
- -- Extract position (X, Y, Z) from the CFrame
- local position = {cf.X, cf.Y, cf.Z}
- -- Extract rotation matrix components from CFrame
- local _, _, _, r1c1, r1c2, r1c3, r2c1, r2c2, r2c3, r3c1, r3c2, r3c3 = cf:components()
- -- Calculate yaw, pitch, and roll in degrees
- local yaw = math.deg(math.atan2(r1c3, r3c3))
- local pitch = math.deg(math.asin(-r2c3))
- local roll = math.deg(math.atan2(r2c1, r2c2))
- -- Structure the GrowPlace data with orientation in degrees
- playerData[player].GrowPlace[item.Name] = {
- cframe = {
- position = position,
- orientation = {roll, yaw, pitch} -- Store orientation as {roll, pitch, yaw}
- },
- Inventory = {},
- Finished = {},
- Recipe = {},
- Timer = 0,
- Repeat = 0
- }
- print("placed item", playerData[player].GrowPlace)
- end
- if remove then
- --Removes numbers from the item
- local test = item.Name:match("^(%a+)")
- local itemName = test:match("^(%a+)")
- --Calculate if everything fits in the inventory
- local currentInventoryWeight = Data.CalculateInventoryWeight(playerData[player].Inventory)
- local currentItemInventoryWeight = Data.CalculateInventoryWeight(playerData[player].GrowPlace[item.Name].Inventory)
- local currentItemFinishedWeight = Data.CalculateInventoryWeight(playerData[player].GrowPlace[item.Name].Finished)
- local MachineWeight = ItemHandler[itemName].Weight
- if currentInventoryWeight + currentItemInventoryWeight + MachineWeight + currentItemFinishedWeight > playerData[player].InventorySize then
- warn("Cannot remove ".. itemName .. " not enough space in inventory")
- return false
- else
- --Put everything in back in the inventory
- for _, Table in ipairs({playerData[player].GrowPlace[item.Name].Inventory, playerData[player].GrowPlace[item.Name].Finished}) do
- for ProductName, Amount in pairs(Table) do
- Data.PlayerInventoryHandler(player, ProductName, Amount, false)
- end
- end
- Data.PlayerInventoryHandler(player, itemName, 1, false)
- playerData[player].GrowPlace[item.Name] = nil
- print("Removed", playerData[player].GrowPlace)
- return true
- end
- end
- end
- function Data.Lock(player, start)
- local state = playerData[player].GrowPlace.Lock
- if start then return state end
- if state == "Locked" then
- playerData[player].GrowPlace.Lock = "Friends"
- elseif state == "Friends" then
- playerData[player].GrowPlace.Lock = "Unlocked"
- elseif state == "Unlocked" then
- playerData[player].GrowPlace.Lock = "Locked"
- else
- warn("No locked state found")
- playerData[player].GrowPlace.Lock = "Locked"
- end
- state = playerData[player].GrowPlace.Lock
- return state
- end
- local function CompleteMachineProcess(player, machine)
- if not playerData[player] then return end -- Ensure player data exists
- local machineData = playerData[player].GrowPlace[machine.Name]
- if not machineData or not machineData.Recipe then return end
- local product = machineData.Recipe
- -- Ensure "Finished" table exists
- machineData.Finished = machineData.Finished or {}
- -- Store finished product in the "Finished" table
- machineData.Finished[product] = (machineData.Finished[product] or 0) + 1
- -- Remove only the required ingredients for **one** product
- for i, ingredient in pairs(ItemHandler[product].Input) do
- Data.PlayerInventoryHandler(player, ingredient, 1, true) -- Remove 1 per product completion
- if machineData.Inventory[ingredient] then
- machineData.Inventory[ingredient] -= 1 -- Reduce from machine inventory
- if machineData.Inventory[ingredient] <= 0 then
- machineData.Inventory[ingredient] = nil -- Remove ingredient if it's empty
- end
- end
- end
- UpdateMachine:FireClient(player, machineData, machine, nil, true)
- print("Product completed: " .. product .. " has been added to the Finished table!")
- end
- local function StartMachineTimer(machine, player, remainingtime)
- local machineData = playerData[player] and playerData[player].GrowPlace[machine.Name]
- if not machineData or machineData.Repeat <= 0 then return end
- task.spawn(function()
- while machineData.Repeat > 0 do
- if not machineData.Recipe then return end
- local repeatTime
- if not remainingtime then
- repeatTime = ItemHandler[machineData.Recipe].Time
- else
- repeatTime = remainingtime
- end
- print("Starting cooking:", machineData.Recipe, "- Remaining:", machineData.Repeat)
- machineData.Timer = repeatTime
- while machineData.Timer > 0 do
- if not playerData[player] then
- print("Player left, pausing machine:", machine.Name)
- return
- end
- machineData.Timer -= 1
- UpdateMachine:FireClient(player, machineData, machine, repeatTime, false)
- task.wait(1)
- end
- if machineData.Timer <= 0 then
- print("Timer complete! Processing:", machine.Name)
- CompleteMachineProcess(player, machine)
- machineData.Repeat -= 1
- end
- end
- machineData.Timer = 0
- print("All products finished, resetting machine:", machine.Name)
- end)
- end
- function Data.LoadPlayerMachines(player)
- if not playerData[player] then return end
- for machineName, machineData in pairs(playerData[player].GrowPlace) do
- if machineData.Repeat and machineData.Repeat > 0 then
- local house = playerData[player].GrowPlace.GPLevel
- local machineInstance = workspace:WaitForChild("Houses")[house][house .. player.Name]:WaitForChild("Plot"):WaitForChild("GrowItemHolder"):FindFirstChild(machineName)
- if machineInstance then
- print("Resuming machine:", machineName, "with", machineData.Timer, "seconds left and", machineData.Repeat, "items left.")
- StartMachineTimer(machineInstance, player, machineData.Timer)
- else
- warn("Machine instance not found for:", machineName)
- end
- end
- end
- end
- function Data.Machines(player, amount, product, cook, machine)
- print(player, amount, product, cook, machine.Parent)
- if not playerData[player] or not playerData[player].Inventory then
- return false, "Player data not found!"
- end
- local machineData = playerData[player].GrowPlace[machine.Name]
- if not machineData then
- return false, "Invalid machine!"
- end
- -- Check if the machine is already running
- if machineData.Timer > 0 then
- return false, "Machine is already running!"
- end
- -- Calculate required ingredients
- local requiredIngredients = {}
- for _, input in pairs(ItemHandler[product].Input) do
- requiredIngredients[input] = (requiredIngredients[input] or 0) + amount
- end
- -- Check if the player has all required ingredients
- for ingredient, requiredAmount in pairs(requiredIngredients) do
- local playerAmount = playerData[player].Inventory[ingredient] or 0
- if playerAmount < requiredAmount then
- return false, "Not enough " .. ingredient .. "! Required: " .. requiredAmount .. ", You have: " .. playerAmount
- end
- end
- -- Move ingredients from player inventory to machine inventory using `PlayerInventoryHandler`
- machineData.Inventory = machineData.Inventory or {}
- for ingredient, requiredAmount in pairs(requiredIngredients) do
- Data.PlayerInventoryHandler(player, ingredient, requiredAmount, true) -- ✅ Remove from player
- machineData.Inventory[ingredient] = (machineData.Inventory[ingredient] or 0) + requiredAmount
- end
- -- Set machine's recipe and timer
- machineData.Recipe = product
- machineData.Timer = ItemHandler[product].Time -- Time for **one** product
- machineData.Repeat = amount -- Number of products to make
- -- Start the countdown on the server
- StartMachineTimer(machine, player)
- return true, "Cooking started!"
- end
- --Get player data
- function Data.GetData(player, otherplayers)
- if not otherplayers then return playerData[player] end
- if otherplayers then return playerData[otherplayers] end
- end
- -- Function to clean up player data when they leave
- function Data.Cleanup(player)
- GrowPlaceHandler.RemoveHouseOnLeave(player)
- playerData[player] = nil
- end
- return Data
Add Comment
Please, Sign In to add comment