Guest User

Untitled

a guest
Dec 21st, 2023
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. package mondlw.laserserver.laserservermanager.data;
  2.  
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import java.util.Objects;
  9. import java.util.Optional;
  10.  
  11. import com.google.gson.Gson;
  12. import com.google.gson.GsonBuilder;
  13.  
  14. import org.bukkit.Bukkit;
  15. import org.bukkit.entity.Player;
  16. import org.bukkit.inventory.Inventory;
  17.  
  18. public class InventoryManager {
  19.  
  20. private static final HashMap<String, Inventory> inventories = new HashMap<>();
  21.  
  22. public static void saveData() {
  23. Gson gson = new GsonBuilder().setPrettyPrinting().create();
  24. String json = gson.toJson(inventories);
  25.  
  26. // Save the JSON string to a file
  27. try {
  28. File file = new File("inventories.json");
  29. FileWriter writer = new FileWriter(file);
  30. writer.write(json);
  31. writer.close();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36.  
  37. public static Inventory loadInventory(String playerName, String world, String mode) {
  38. Optional<Inventory> inventoryOptional = Optional.ofNullable(inventories.get(playerName + "_" + world + "_" + mode));
  39.  
  40. if (inventoryOptional.isPresent()) {
  41. return inventoryOptional.get();
  42. } else {
  43. return Bukkit.createInventory(null, 9, world + "-" + mode);
  44. }
  45. }
  46.  
  47. public static void replaceInventoryTo(Player player, String world, String mode) {
  48.  
  49. Inventory newInventory = inventories.get(player.getName() + "_" + world + "_" + mode);
  50. Inventory oldInventory = player.getInventory();
  51.  
  52. if(newInventory == null) {
  53. newInventory = Bukkit.createInventory(null, 36);
  54. }
  55.  
  56. if(mode.equals("build")) {
  57. // Save the current normal inventory
  58. if(inventories.containsKey(player.getName() + "_" + world + "_" + "normal")) {
  59. inventories.replace(player.getName() + "_" + world + "_" + "normal", oldInventory);
  60. } else {
  61. inventories.put(player.getName() + "_" + world + "_" + "normal", oldInventory);
  62. }
  63. } else {
  64. // Save the current build inventory
  65. if(inventories.containsKey(player.getName() + "_" + world + "_" + "build")) {
  66. inventories.replace(player.getName() + "_" + world + "_" + "build", oldInventory);
  67. } else {
  68. inventories.put(player.getName() + "_" + world + "_" + "build", oldInventory);
  69. }
  70. }
  71.  
  72. player.getInventory().setContents(newInventory.getContents());
  73. player.updateInventory();
  74.  
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment