I am trying to make some simple kitPvP with bukkit API (mainly for learning purposes), but I'm struggling with backing up a player's inventory before they choose a kit.
My code right now: (File: Commands.java, it's getting called from main with onCommand)
public boolean testkit(CommandSender sender, String[] args) {
if(sender instanceof Player) {
String kit = args[0]; // I know, may throw exception
Player player = (Player) sender;
PlayerInventory inventory = player.getInventory();
// Backup inventory into HashMap(?)
if(kit.equalsIgnoreCase("basic")) {
// Clear inventory then give items to player (or replace)
} else if(kit.equalsIgnoreCase("out")) {
// Clear inventory then give backup to player (or replace)
} else {
sender.sendMessage("No such kit.");
return false;
}
return true; // Returns if a good kit selected
} else {
sender.sendMessage("Only players can select kits!");
return false;
}
}
Now, I have a problem with the following parts:
I have no idea how to do these things, because you cannot create a new PlayerInventory instance (it's an interface), and I have no idea what could hold the player's items. (Also I know that a HashMap will be wiped if the server closes, but that's not the point)
Also, I imagine there is some way to replace the player's inventory with another one, but I have absolutely no idea how.
EDIT: Found a rather unelegant solution. Over here,found how to make a new inventory, and made a function to just iterate over the player's inventory and copy the items into the backup.
private void overwrite(Inventory source, Inventory dest) {
for(int i = 0; i < source.getSize(); i++) {
dest.setItem(i, source.getItem(i));
}
}
private Inventory copy(Inventory inventory) {
Inventory copy = Bukkit.createInventory(inventory.getHolder(), inventory.getSize(), inventory.getName());
overwrite(inventory, copy);
return copy;
}
One question though: Will the ItemStack update to the new inventory if changed at old inventory? (Not very crucial here, but important to know IMO) If it will, any way to prevent that?
What you should be doing is calling getContents()
on the Player's inventory, then saving the array that that returns into a HashMap. You then clear()
the player's inventory, and individually set the contents of each slot (or, for a more elegant solution, have a ItemStack[]
ready for the items of each kit, that you can push into the inventory using setContents()
).
Once the player is done with the kit and you want to restore their original Inventory, you just setContents()
with the copy of their items that you have stored in the HashMap.
Do note that getContents()
and setContents()
don't deal with armor slots, so to do that, you'll want to also getArmorContents()
and setArmorContents()
.