Add a command for different classes.

Discussion in 'Plugin Development' started by BeastCraft3, Aug 15, 2014.

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

    BeastCraft3

    Hellau, Im wondering how I create this command: "/gun <username> <gun_name>"
    The command will basicly give the player a gun. My problem is that I got my guns in different classes. I think it has something to do with strings, but im not familer with commands for different classes.
    Heres one of my gun classes:
    Code:
    package CrankPhilsWarPlugin;
     
    import java.util.ArrayList;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.entity.Fireball;
    import org.bukkit.entity.Player;
    import org.bukkit.entity.Snowball;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.entity.EntityDamageByEntityEvent;
    import org.bukkit.event.player.PlayerInteractEvent;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
     
    public class RPG implements Listener {
     
    private Main main;
     
        public RPG(Main main) {
            this.main = main;
            main.getServer().getPluginManager().registerEvents(this, main);
        }
     
        ArrayList<Player> cooldown = new ArrayList<Player>();
     
     
        ItemStack RPG = new ItemStack(Material.GOLD_HOE);{
            ItemMeta Dragunovmeta = RPG.getItemMeta();
            ArrayList<String> cc = new ArrayList<String>();
            Dragunovmeta.setDisplayName(ChatColor.RED + "RPG");
            cc.add(ChatColor.GREEN + "RPG");
            Dragunovmeta.setLore(cc);
            RPG.setItemMeta(Dragunovmeta);
        }
       
       
            @EventHandler
            public void onPlayerInteract(PlayerInteractEvent e) {
                final Player player2 = e.getPlayer();
                if (!(e.getAction() == Action.RIGHT_CLICK_AIR)) return;
           
                if (!(e.getItem().getType() == Material.GOLD_HOE)) return;
           
                if(checkForItems(e.getPlayer(), 1, Material.TNT) == false) return;
           
                if (cooldown.contains(player2)) {
                    player2.sendMessage("§aYou have to wait 5 second!");
           
                } else {
                    Fireball f = e.getPlayer().launchProjectile(Fireball.class);
                    f.setYield(0);
                    f.setIsIncendiary(false);
               
                    subtractItems(e.getPlayer(), 1, Material.TNT);
                }
               
               
               
                    cooldown.add(player2);
                    Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(main, new Runnable() {
                    public void run() {
                    cooldown.remove(player2);
                    }
                    }, 50);
                    return;
           
                }
       
            @EventHandler
                public void onEntityDamage(EntityDamageByEntityEvent e) {
                        if (e.getDamager() instanceof Snowball) {
                            Fireball f = (Fireball) e.getDamager();
                                if (f.getShooter() instanceof Player) {
                                        Player shooter = (Player) f.getShooter();
                                        if (shooter.getItemInHand().getType() == Material.GOLD_HOE) {
                                                e.setDamage(6.0);
                                        }
                                }
                        }
                }
       
       
            public boolean checkForItems(Player p, int z, Material m){
                    Player player = p;
                    boolean check = false;
                    int count = 0;
                    ItemStack[] playInv = player.getInventory().getContents();
                    for(int i = 0; i < playInv.length; i++){
                        if(playInv[i] != null){
                            if(playInv[i].getType().equals(m)){
                                count += playInv[i].getAmount();
                            }
                        }
                    }
                    if(count >= z) check = true;
             
                        return check;
                }
            public void subtractItems(Player p, int z, Material m){
                    Player player = p;
                    ItemStack[] playInv = player.getInventory().getContents();
                    for(int i = 0; i < playInv.length; i++){
                        if(playInv[i] != null){
                            if(playInv[i].getType().equals(m)){
                                if(playInv[i].getAmount() == z){
                                    player.getInventory().setItem(i,  null);
                                    return;
                                }
                                else if(playInv[i].getAmount() > z){
                                    playInv[i].setAmount(playInv[i].getAmount() - z);
                                    return;
                                }
                                else{
                                    z -= playInv[i].getAmount();
                                    player.getInventory().setItem(i,  null);
                                }
                            }
                        }
                    }
             
                }
    }
    

    this is my Main class:
    Code:
    package CrankPhilsWarPlugin;
     
    import java.util.logging.Logger;
     
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class Main extends JavaPlugin{
       
        final Logger logger = Logger.getLogger("MineCraft");
       
        public void onEnable() {
            System.out.println("[PhilCWarZ] Enabled.");
            getServer().getPluginManager().registerEvents(new Dragunov(this), this);
            getServer().getPluginManager().registerEvents(new Awp(this), this);
            getServer().getPluginManager().registerEvents(new Msr(this), this);
            getServer().getPluginManager().registerEvents(new Barret50cal(this), this);
            getServer().getPluginManager().registerEvents(new Mp5(this), this);
            getServer().getPluginManager().registerEvents(new M16(this), this);
            getServer().getPluginManager().registerEvents(new M4A1(this), this);
            getServer().getPluginManager().registerEvents(new AK47(this), this);
            getServer().getPluginManager().registerEvents(new M1014(this), this);
            getServer().getPluginManager().registerEvents(new AA12(this), this);
            getServer().getPluginManager().registerEvents(new M1015(this), this);
            getServer().getPluginManager().registerEvents(new SPAS12(this), this);
            getServer().getPluginManager().registerEvents(new M9(this), this);
            getServer().getPluginManager().registerEvents(new A1911(this), this);
            getServer().getPluginManager().registerEvents(new Magnum(this), this);
            getServer().getPluginManager().registerEvents(new DesertEagle(this), this);
            getServer().getPluginManager().registerEvents(new RPG(this), this);
            getServer().getPluginManager().registerEvents(new UZI(this), this);
            getCommand("philcwarz").setExecutor(new PhilcWarz(this));
            new PhilcWarz(this);
            new Gun(this);
        }
     
    }
    

    This is my gun Command class:
    Code:
    package CrankPhilsWarPlugin;
     
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
     
    public class Gun implements CommandExecutor {
     
        public Main plugin;
     
        public Gun(Main instance) {
            plugin = instance;
        }
       
        public boolean onCommand(CommandSender sender, Command cmd, String label,
                String[] args) {
            if (!(sender instanceof Player)) {
                sender.sendMessage("§cError: §4Only players can use this command, not the consol");
                return true;
            }
            Player p = (Player) sender;
            if(label.equalsIgnoreCase("gun")) {
                if(p.hasPermission("gun.give")){
                    if(args.length == 0) {
                        p.sendMessage("Error: try /gun <username> <gun_name>");
                    }
                }
            }
            return false;
        }
     
    }
    
     
  2. Offline

    xAstraah

    BeaStcrAft, Create a new Object of your gun class that you would like to use?

    'Main main = new Main();' <-- Example don't use this word for word btw.
     
  3. Offline

    BeastCraft3

    xAstraah
    emm, Should I just add this to my gun classes: Main main = new Main();
     
  4. Offline

    xAstraah

    BeaStcrAft, You will use this code when you would like to access the guntype class. For example in my Command class i would do Gun gun = new Gun(); gun.givePlayerGun();

    All the best,
    xAstraah.
     
  5. Offline

    Zupsub

    Instead of having something like this:

    Code:
    Bukkit.getPluginManager().registerEvent(new GunType(this), this);
    100 times
    
    Make one class gun and call this in it's constructor:
    Code:
    public Gun(Main instance) {
    Bukkit.getPluginManager().registerEvents(this, instance);
    }
    
    Then for your command method, there are two solutions:
    1.) make an Map<Srring, Gun> and add all the guns with their name.
    Then you can retrieve them from the onCommand method.

    2.) make a method like getName() for the gun class, then make a Collection<Gun> with every gun. Loop threw every gun in there and check Gun#getName().equals(...) in the onCommand method, then you have yourr gun too.
     
  6. Offline

    BeastCraft3

    Zupsub
    Thank You for your reply, I tried this for a while but I can manage it. This is how far I am. Tell me if I've done anything wrong. The gun command part I would love some more help with.
    Code:
    package CrankPhilsWarPlugin;
     
    import org.bukkit.Bukkit;
    import org.bukkit.event.Listener;
     
    public class Guns implements Listener{
     
        public Guns(Main instance) {
            Bukkit.getPluginManager().registerEvents(this, instance);
            }
    }
    
     
  7. Offline

    BeastCraft3

    Help me please, anyone I really need help with this within tonight(7h)
     
  8. Offline

    Totom3

    BeastCraft3 I personally think you should have declared your guns in a more dynamic way, but anyways you probably won't have the time to change that in 1 day, so here's a very quick & simple solution :

    1. Make all your guns extend from a new abstract class "Gun" (not the one you use for your events, a new one).
    2. Put the declaration for your methods in it.
    3. In Gun.java, declare a new abstract method "asItemStack()" and a new method "getName()"
    4. In each one of your gun classes, implement the first method and return the ItemStack you have declared at the beginning of the class.
    5. Do the same for "getName()", but this time return a String (rpg, dragunov, deserteagle, uzi, etc...)
    7. In your main class, make a List<Gun>. When onEnable() is called, create an instance of each one of your guns and put it in the List.
    8. When onCommand() is called, iterate through all of the values in your List, and check if their getName() matches the second argument.
    Code:java
    1. for (Gun gun : listOfGuns) {
    2. if (gun.getName().equalsIgnoreCase(args[1]) {
    3. // Give the player the gun using gun.asItemStack()
    4. }
    5. }

    Again, this is the quickest solution I can think of right now, but is certainly not the best in the long term.
     
  9. Offline

    BeastCraft3

    Totom3
    Thank You Man, But the first steps I didnt really understand, Is there any chance that you could help me with the code?
     
  10. Offline

    Totom3

    BeastCraft3 Sure, but it's important you understand how abstract classes work if you use them. Here's a good tutorial, or : StackOverflow.

    1. Gun.java :
    Code:java
    1. public abstract class Gun {
    2.  
    3. // Declaring the fields for each gun
    4. protected String name;
    5.  
    6. // Here are other fields you might want to add
    7. protected double damage;
    8. protected double rpm;
    9. protected double reloadTime;
    10. protected double accuracy;
    11. protected Material baseMaterial;
    12.  
    13. // This method will not change depending on the gun; we can write it directly in here.
    14. public String getName() {
    15. return name;
    16. }
    17.  
    18. // We could do the same here, but you might want to generate the lore/display name in a different way for each gun,
    19. // so we'll let each gun override this method.
    20. public abstract ItemStack asItemStack();
    21.  
    22.  
    23.  
    24. // Just a few methods you might want to add
    25.  
    26. public abstract void shoot(Player player);
    27.  
    28. public abstract void reload();
    29.  
    30. }

    2. RPG.java (extends Gun) :
    Code:java
    1. public class RPG extends Gun {
    2.  
    3. // The constructors here
    4.  
    5. // If you don't write the code for this function in Gun.java, you'll have to override it for each gun.
    6. @Override
    7. public ItemStack asItemStack() {
    8. // This is the code you posted in your original post
    9.  
    10. ItemStack item = new ItemStack(this.baseMaterial, 1);
    11. ItemMeta meta = item.getItemMeta();
    12. ArrayList<String> cc = new ArrayList<>();
    13. cc.add(ChatColor.GREEN + "RPG");
    14.  
    15. meta.setDisplayName(ChatColor.RED + "RPG");
    16. meta.setLore(cc);
    17.  
    18. item.setItemMeta(meta);
    19.  
    20. return item;
    21. }
    22.  
    23. // You have to override this one as well
    24. @Override
    25. public void shoot(Player player) {
    26.  
    27. }
    28.  
    29. // Same for this one
    30. @Override
    31. public void reload() {
    32.  
    33. }
    34.  
    35. }

    This is just the code explaining my other post. You'll have to add all the other methods and the constructors.
     
  11. Offline

    BeastCraft3

    Totom3
    Thank you, I will make my guns like that the next time. But right now, Please give me the entire code for the "string in my rpg class, and how the command should be" I really need it done quickly. Please. I know your not suppost to give out the codes because I dont learn anything, but I really need help.
     
  12. Offline

    Totom3

    BeastCraft3 Alright then... :/

    In your onEnable(), create a list with all your guns in it :
    Code:java
    1. ArrayList<Gun> guns = new ArrayList<>();
    2. // I don't know which constructor you will use, so here I use a blank one
    3. guns.add(new Dragunov());
    4. guns.add(new Awp());
    5. guns.add(new Msr());
    6. guns.add(new Barret50cal());
    7. guns.add(new Mp5());
    8. guns.add(new M16());
    9. // You get the point, just do the same to complete the list


    In your onCommand(), "iterate through all of the values in your List, and check if their getName() matches the second argument" :
    Code:java
    1. for (Gun aGun : guns) {
    2. if (aGun.getName().equalsIgnoreCase(args[1]) {
    3. // This is the right one, now just give it to him
    4. // Using aGun.asItemStack()
    5. // I assume you are capable of doing this.
    6. }
    7. }

    I already said you shouldn't end up with this format, but yeah. I get that you have to get this done quickly, and then you can optimize it.
     
  13. Offline

    BeastCraft3

    Totom3
    Thank you, Hope I dont ask for to much, but can you just place this in my main class for me, and create the command for me? I see that you know what you are doing and I dont. I will learn though after reading the code and using it alot. Please paste this in my main class, show me how the rpg class should look like with the string or whatever you did and finish the command for me. It wold help me alot. I understand if you dont want to do it. Anyway, Thank you for your help. Your a good coder ;)
     
  14. Offline

    Totom3

    BeastCraft3 Uhm thanks but dude... I gave you everything you need. Next step is to add the brackets... Register the command executor and the events in onEnable(). Make sure the args aren't null in onCommand(). Look at your initial post. You already did that.

    And trust me, just reading code will not necessarily make you better instantly. The best is I think to first try yourself, then compare with the others. Good luck with your plugin
     
  15. Offline

    BeastCraft3

    Totom3
    Hello, I spoke with him. Im going to make the guns the best way now. Thank you for all your help. Is it okey if I ask for questions later in this thread about the guns? I might need some more help. Sorry if you feel that im bad at this. I just find the forums a good way to learn.
     
  16. Offline

    Totom3

  17. Offline

    BeastCraft3

    Totom3
    Cool ;)

    Totom3
    Hello, just a quick question: I got a redline under this method:
    Code:
    protected Material baseMaterial;
    SHould I change it to:
    Code:
    protected MaterialData baseMaterial;
    And how do I register the abstract class to my main class to make it work, if I need to.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 9, 2016
  18. Offline

    Totom3

    BeastCraft3 You don't need to register your abstract class. To use it, simply create a child class, and implement all abstract methods in it (actually, as soon as you type "extends Gun", the IDE should suggest you to do that for you).

    And I don't get why it does that... But anyways I just checked the MaterialData class and yeah sure why not ? It's more complete and lets you convert it to an ItemStack, as far as I understand.
     
  19. Offline

    BeastCraft3

    Totom3
    Hello? Is it okey if I add you on skype? That way it will be easier and faster to get help.
     
Thread Status:
Not open for further replies.

Share This Page