[Tutorial] Save/Load Inventories, Locations, and XP Levels!

Discussion in 'Resources' started by PatoTheBest, Feb 8, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    PatoTheBest

    Hello, this is my first tutorial and please give me some feedback.

    First we will create the HashMaps that will store the information:
    Code:java
    1. private static HashMap<String, ItemStack[]> armourContents = new HashMap<String, ItemStack[]>();
    2. private static HashMap<String, ItemStack[]> inventoryContents = new HashMap<String, ItemStack[]>();
    3. private static HashMap<String, Location> locations = new HashMap<String, Location>();
    4. private static HashMap<String, Integer> xplevel = new HashMap<String, Integer>();


    After we have created the HashMaps, lets get on into saving the inventory.
    Code:java
    1.  
    2. armourContents.put(player.getName(), player.getInventory().getArmorContents()); //save armour
    3. inventoryContents.put(player.getName(), player.getInventory().getContents());//save Inventory
    4. locations.put(player.getName(), player.getLocation()); //save the Location
    5. xplevel.put(player.getName(), player.getLevel()); //save the xp level
    6. player.getInventory().clear(); //just clearing the inventory. Optional line.


    Now for the restore inventory method.
    Code:java
    1.  
    2. player.getInventory().clear(); //We will once again clear the inventory
    3. player.teleport(locations.get(player.getName())); //Teleport to the location
    4.  
    5. player.getInventory().setContents(inventoryContents.get(player.getName())); //restore inventory contents
    6. player.getInventory().setArmorContents(armourContents.get(player.getName())); //restore armour contents
    7. player.setLevel(xplevel.get(player.getName())); //restor XP Level
    8.  


    And now to remove the items from the HashMap
    Code:java
    1. xplevel.remove(player.getName());
    2. locations.remove(player.getName());
    3. armourContents.remove(player.getName());
    4. inventoryContents.remove(player.getName());


    Our final code will look something like:
    Code:java
    1. package me.tutorial.inventorymanager;
    2.  
    3. import java.util.HashMap;
    4.  
    5. import org.bukkit.Location;
    6. import org.bukkit.entity.Player;
    7. import org.bukkit.inventory.ItemStack;
    8.  
    9. public class InventoryManager {
    10.  
    11. private static HashMap<String, ItemStack[]> armourContents = new HashMap<String, ItemStack[]>();
    12. private static HashMap<String, ItemStack[]> inventoryContents = new HashMap<String, ItemStack[]>();
    13. private static HashMap<String, Location> locations = new HashMap<String, Location>();
    14. private static HashMap<String, Integer> xplevel = new HashMap<String, Integer>();
    15.  
    16. public static void saveInventory(Player player){
    17. armourContents.put(player.getName(), player.getInventory().getArmorContents());
    18. inventoryContents.put(player.getName(), player.getInventory().getContents());
    19. locations.put(player.getName(), player.getLocation());
    20. xplevel.put(player.getName(), player.getLevel());
    21. player.getInventory().clear();
    22. }
    23.  
    24. public static void restoreInventory(Player player){
    25. player.getInventory().clear();
    26. player.teleport(locations.get(player.getName()));
    27.  
    28. player.getInventory().setContents(inventoryContents.get(player.getName()));
    29. player.getInventory().setArmorContents(armourContents.get(player.getName()));
    30. player.setLevel(xplevel.get(player.getName()));
    31.  
    32. xplevel.remove(player.getName());
    33. locations.remove(player.getName());
    34. armourContents.remove(player.getName());
    35. inventoryContents.remove(player.getName());
    36. }
    37. }
    38.  

    Thanks for reading this ;)
     
    zThana likes this.
  2. Offline

    Bloxcraft

    Can you serialize it for use in data files?
     
  3. Offline

    HeavyMine13

    How can I save them to a config file and load em?
     
  4. Offline

    MrTwiggy

    Instead of having a Map for each individual attribute that you want to save about a player, why not create a PlayerData object that holds all of the attributes you want for a player, and just have one map of a player's name (string) to their PlayerData object.
     
    Plo124 and bobacadodl like this.
  5. Offline

    megasaad44

    Best tut for save/load invs EVER!
     
  6. Offline

    BungeeTheCookie

    And what happens when the server restarts?
     
    ArthurMaker likes this.
  7. Offline

    megasaad44

    BungeeTheCookie Er... I'll try to work on that ^_^"
    How do you save hashmaps anyways? Like after a restart.
     
  8. Offline

    Skyost

    A bit dirty :s
    Code:
    // First create a class like this :
     
    public class PlayerInfo {
     
        private final String uuid;
        private PlayerInventory inventory;
        private Location location;
        private int expLevel;
        private float exp;
     
        public PlayerInfo(final Player player) {
            this.uuid = player.getUniqueId().toString();
            this.inventory = player.getInventory();
            this.location = player.getLocation();
            this.expLevel = player.getLevel();
            this.exp = player.getExp();
        }
     
        public final String getUUID() {
            return uuid;
        }
     
        public final Player getPlayer() {
            final UUID uuid = UUID.fromString(this.uuid);
            //return Bukkit.getPlayer(uuid); <- Above 1.7.5.
            for(final Player player : Bukkit.getOnlinePlayers() {
                if(player.getUniqueId().equals(uuid)) {
                    return player;
                }
            }
        }
     
        public final void setInventory(final PlayerInventory inventory) {
            this.inventory = inventory;
        }
     
        public final PlayerInventory getInventory() {
            return inventory;
        }
     
        public final void setLocation(final Location location) {
            this.location = location;
        }
     
        public final Location getLocation() {
            return location;
        }
     
        public final void setExpLevel(final int expLevel) {
            this.expLevel = expLevel;
        }
     
        public final int getExpLevel() {
            return expLevel;
        }
     
        public final void setExp(final float exp) {
            this.exp = exp;
        }
     
        public final float getExp() {
            return exp;
        }
     
        @Override
        public final String toString() {
            final List<String> invContents = new ArrayList<String>();
            for(final ItemStack item : inventory.getContents()) {
                if(item != null) {
                    invContents.add(new JsonItemStack(item).toJson());
                }
            }
            final List<String> armorContents = new ArrayList<String>();
            for(final ItemStack item : inventory.getArmorContents() {
                if(item != null) {
                    armorContents.add(new JsonItemStack(item).toJson());
                }
            }
            final JSONObject object = new JSONObject();
            object.put("inventory", invContents);
            object.put("locWorld", location.getWorld.getName());
            object.put("locX", location.getX());
            object.put("locY", location.getY());
            object.put("locZ", location.getZ());
            object.put("expLevel", expLevel);
            object.put("exp", exp);
            return object.toJSONString();
        }
     
        public class JsonItemStack {
     
                private final String material;
                private final String name;
                private final List<String> lore;
                private final HashMap<String, Long> enchantments = new HashMap<String, Long>();
                private final long amount;
           
            public JsonItemStack(final ItemStack item) {
                material = item.getType().name();
                final ItemMeta meta = item.getItemMeta();
                name = meta.getDisplayName();
                lore = meta.getLore();
                for(final Entry<Enchantment, Integer> entry : meta.getEnchants().entrySet()) {
                    enchantments.put(entry.getKey().getName(), Long.valueOf(entry.getValue()));
                }
                this.amount = item.getAmount();
            }
       
            public JsonItemStack(final String material, final String name, final List<String> lore, final HashMap<String, Long> enchantments, final Long amount) {
                this.material = material;
                this.name = name;
                this.lore = lore;
                if(enchantments != null) {
                    this.enchantments.putAll(enchantments);
                }
                this.amount = amount == null ? 1L : amount;
            }
     
            public final String toJson() {
                final JSONObject object = new JSONObject();
                object.put("material", material);
                object.put("name", name);
                object.put("lore", lore);
                object.put("enchantments", enchantments);
                object.put("amount", amount);
                return object.toJSONString();
            }
     
            public static final JsonItemStack fromJson() {
                final JSONObject array = (JSONObject)JSONValue.parse(jsonItemStack);
                return new JsonItemStack((String)array.get("material"), (String)array.get("name"), (List<String>)array.get("lore"), (HashMap<String, Long>)array.get("enchantments"), (Long)array.get("amount"));
            }
     
            public final ItemStack toItemStack() {
                final ItemStack itemStack = new ItemStack(material == null ? Material.GRASS : Material.valueOf(material));
                final ItemMeta meta = itemStack.getItemMeta();
                boolean applyMeta = false;
                if(name != null) {
                    meta.setDisplayName(name);
                    applyMeta = true;
                }
                if(lore != null) {
                    meta.setLore(lore);
                    applyMeta = true;
                }
                if(enchantments.size() != 0) {
                    for(final Entry<String, Long> entry : enchantments.entrySet()) {
                        meta.addEnchant(Enchantment.getByName(entry.getKey()), Ints.checkedCast(entry.getValue()), true);
                    }
                    applyMeta = true;
                }
                itemStack.setItemMeta(meta);
                if(applyMeta) {
                    itemStack.setAmount(Ints.checkedCast(amount));
                }
                return itemStack;
            }
           
        }
     
    }
     
    // Now you can save each player informations in a map for example :
    // final HashMap<String, PlayerInfo> infos = new HashMap<String, PlayerInfos>();
    //
    // final Player player = Bukkit.getPlayer("Skyost");
    // infos.put(player, new PlayerInfos(player);
     
    DoctorDark likes this.
  9. Offline

    JUSTCAMH

    heavy
    You would need to on Disable run a method to add this to a file and on Enable run another method to load the data. Sorry I can't give you code at the moment but hopefully you can figure it out
     
  10. Offline

    Onlineids

  11. Offline

    RegalMachine

    PatoTheBest This should be updated to support UUID's... Should just be p.getUUID().toString() instead of p.getName() right?
     
  12. Offline

    Skyost

Thread Status:
Not open for further replies.

Share This Page