[TUT]How to create the /I <Item> Command | Using HashMaps

Discussion in 'Resources' started by emericask8ur, Nov 13, 2011.

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

    emericask8ur

    Create a new Class called HashMapz
    Code:
    public class HashMapz {
    public static HashMap<String, Material> items = new HashMap<String, Material>();
    public static void setItems() {
    items.put("apple", Material.APPLE);
    items.put("cake", Material.CAKE);
         }
    }
    
    The Command
    Code:
    if (cmdLabel.equalsIgnoreCase("i") && args.length==1 ){
    			Material type = HashMapz.items.get(args[0].toLowerCase());
    			if (type == null) {
    				sender.sendMessage(R + "Invalid item name");
    				return true;
    			}
    			ItemStack item = new ItemStack(type, type.getMaxStackSize());
    			p.getInventory().addItem(item);
    			sender.sendMessage(ChatColor.AQUA + "You have gave yourself " + args[0]);
    			return true;
    		}
    
    In the Main Class Under onEnabled enter this:
    Code:
    	HashMapz.setItems();
    
    in the plugin.yml Register the command
    Code:
    commands:
      I:
       description: Spawn a Item
       usage: /I [ItemName]
    
     
    MrMag518 likes this.
  2. Offline

    Kohle

    Short, sweet, simple. :)
     
    emericask8ur likes this.
  3. Offline

    rob4001

    Hmm But this doesnt support data values?
     
  4. Offline

    emericask8ur

    You can import data values for the string "1", Material.Stone get it?
     
  5. Offline

    iffa

    Code:java
    1. // Package Declaration
    2. package me.iffa.trashcan.commands.general;
    3.  
    4. // TrashCan Imports
    5. import me.iffa.trashcan.commands.TrashCommand;
    6. import me.iffa.trashcan.utils.MessageUtil;
    7.  
    8. // Bukkit Imports
    9. import org.bukkit.ChatColor;
    10. import org.bukkit.Material;
    11. import org.bukkit.command.CommandSender;
    12. import org.bukkit.entity.Player;
    13. import org.bukkit.inventory.ItemStack;
    14.  
    15. /**
    16.  * Represents /item.
    17.  *
    18.  * @author iffamies
    19.  */
    20. public class ItemCommand extends TrashCommand {
    21.  
    22. /**
    23.   * Constructor of ItemCommand.
    24.   *
    25.   * @param label Command label
    26.   */
    27. public ItemCommand(String label) {
    28. super(label);
    29. }
    30.  
    31. /**
    32.   * {@inheritDoc}
    33.   */
    34. @Override
    35. public boolean executeCommand(CommandSender cs, String[] args) {
    36. if (!(cs instanceof Player)) {
    37. MessageUtil.sendMessage(cs, "Sorry, only players can use this command.");
    38. return true;
    39. }
    40. Player player = (Player) cs;
    41. if (!player.hasPermission("trashcan.general.item")) {
    42. MessageUtil.sendMessage(player, ChatColor.RED + "You don't have permission!");
    43. return true;
    44. }
    45. if (args.length < 1) {
    46. return false;
    47. } else {
    48. String[] itemAndData = args[0].split(":");
    49. int item = 0;
    50. try {
    51. item = Integer.parseInt(itemAndData[0]);
    52. } catch (NumberFormatException ex) {
    53. // Item was not an int, do nothing
    54. }
    55. Material itemMat = item == 0 ? Material.matchMaterial(itemAndData[0]) : Material.getMaterial(item);
    56. int damage = 0;
    57. if (itemMat == null) {
    58. MessageUtil.sendMessage(player, ChatColor.RED + "Invalid item '" + itemAndData[0] + "'!");
    59. return true;
    60. }
    61. if (itemAndData.length == 2) {
    62. try {
    63. damage = Integer.parseInt(itemAndData[1]);
    64. } catch (NumberFormatException ex) {
    65. // Data was not an int, complain here
    66. MessageUtil.sendMessage(player, ChatColor.RED + "Data must be a valid number!");
    67. return true;
    68. }
    69. }
    70. ItemStack itemStack = new ItemStack(itemMat, 1, (short) damage);
    71. if (args.length == 1) {
    72. player.getInventory().addItem(itemStack);
    73. } else {
    74. int amount = 1;
    75. try {
    76. amount = Integer.parseInt(args[1]);
    77. } catch (NumberFormatException ex) {
    78. MessageUtil.sendMessage(player, ChatColor.RED + "Invalid item amount!");
    79. return true;
    80. }
    81. itemStack.setAmount(amount);
    82. player.getInventory().addItem(itemStack);
    83. }
    84. MessageUtil.sendMessage(player, ChatColor.GREEN + "You've been given " + itemStack.getAmount() + " of " + itemMat.toString() + " (" + itemMat.getId() + ")!");
    85. return true;
    86. }
    87. }
    88.  
    89. /**
    90.   * {@inheritDoc}
    91.   */
    92. @Override
    93. public void sendUsage(CommandSender cs) {
    94. MessageUtil.sendMessage(cs, ChatColor.GRAY + "Usage: /item <item[:damage]> [amount]");
    95. }
    96. }


    It's a shame I'm not allowed to release this plugin. grr
     
  6. Offline

    emericask8ur

    Why do that much?
     
  7. Offline

    thescreem

    It's great that you show people what code they need, but you don't explain anything. How are people supposed to learn what this does if there are no explanations? :confused:
     
  8. Offline

    emericask8ur

    Thats a great Question. Its like hard for me to Explain but easy for me to show rather ;)
     
  9. Offline

    Tauryuu

    Can you show us how to do Item Data Values too? :p
    (For reference purposes)
     
  10. Offline

    emericask8ur

    Pretty much the same thing but the String is a Number rather than a Word example:
    Code:
    items.put("1", Material.CAKE);
    
    Because that string will be what ever the user Types
     
  11. Offline

    r3Fuze

    I think he is talking about data values for different types of wool, slabs, logs, etc.
     
  12. Offline

    Tauryuu

    Yes. That.
     
  13. Offline

    emericask8ur

    Actually I have a new code for items :] Its 100% to find any item and its less code.
     
  14. Offline

    oxguy3

    If you're going to take this HashMap approach, wouldn't it be easier to store names with item IDs, then create ItemStacks with this constructor.

    Doing it this way also means you could just use regex to recognize if the user specifies a number, so that instead of hashmapping ("1",1), you could just do new ItemStack(args[1], args[2], 0) and plop that in the PlayerInventory. You'd have to make sure that the number actually corresponds to a real item, but thats the basic approach.

    You could also use regex to recognize "number:number" to deal with item damage.

    Sorry this isn't very detailed; I'm on my iPod ATM.
     
  15. Offline

    user_43347

    This has problems, it would require someone to enter every item in order to work.
    It's so much easier to do something like this, where it tries to make an itemstack, and if it can't, it continues.
    Code:
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
            if (cmd.getName().equals("i")) {
                if (sender instanceof Player) {
                    Player p = (Player) sender;
                    try {
                        p.getInventory().addItem(new ItemStack(Integer.parseInt(args[0]), Integer.parseInt(args[1])));
                    } catch (Exception e) {
                        p.sendMessage("Sorry, I couldn't find that item!");
                    }
                } else {
                    log.info("Sorry, this command is for players only!");
                }
            }
            return true;
    }
     
  16. Offline

    emericask8ur

    public static Material getMaterial(String name) {
    Material m = null;
    try {
    m = Material.getMaterial(Integer.parseInt(name));
    if (m != null) return m;
    } catch (Exception ex) {};
    name = name.toLowerCase();
    //custom names
    m = items.get(name);
    if (m != null) return m;
    //matching
    m = Material.matchMaterial(name);
    if (m != null) return m;
    //looping
    name = name.replace("_", "");
    for (Material mm : Material.values()) {
    if (mm.toString().replace("_", "").equalsIgnoreCase(name)) {
    return mm;
    }
    }
    return null;
    }
    }

     
  17. Offline

    user_43347

    There isn't a code option for nothing.
     
  18. Offline

    beatcomet

    it isn't better to use enums instead of Hashmap?
     
  19. Offline

    emericask8ur

    I would not, hashmaps are more reliable.
     
  20. Offline

    ferrybig

    I think its the oposite way, you can use enums whit multiply threads, whitout more code, but this cant be done whit HashMaps, also enums are inited automatic
     
  21. Offline

    emericask8ur

    I know now, this is a long time ago.
     
  22. Offline

    vYN

    Does anyone have a hash map with all the items in it? and working? I'm not lazy. Just asking xD
     
  23. Offline

    Archelaus

    Whilst I'm unsure why no one has suggested this, Material has a matchMaterial method, why not just use that?
     
    emericask8ur likes this.
  24. Offline

    Acrobot

    Archelaus
    Iffa actually did this in his code, but I found the method not working well for mossy cobblestone few months ago :p
     
  25. Offline

    davejavu

    Why not just use my code here?
    Code:java
    1.  
    2. //Author = davejavu
    3. if (cmdLabel.equalsIgnoreCase("i") && args.length == 1){
    4. Material mat;
    5. if (args[0].matches("-?\\d+(.\\d+)?"){
    6. mat = Material.geyById(Integer.parseInt(args[0]));
    7. }else{
    8. mat = Material.matchMaterial(args[0]);
    9. }
    10. player.getInventory().setItem(player.getInventory().firstEmpty(), mat).setAmount(64);
    11. player.sendMessage(ChatColor.GOLD + "Item given");
    12. }
     
  26. Offline

    emericask8ur

    So many ways to do this, I posted a nice one above as well. Yet, good job! Like yours too.
     
  27. Offline

    KeybordPiano459

    Wait why can't you?
     
Thread Status:
Not open for further replies.

Share This Page