Adding block to/Removing blocks from an ArrayList

Discussion in 'Plugin Development' started by Kevinzuman22, Jan 1, 2016.

Thread Status:
Not open for further replies.
  1. I have been trying to make a plugin that gets redstone lamps from an ArrayList, and turn those on at day, and turn them off at night.

    I am struggling to making commands for adding/removing the blocks to the ArrayList. What I want my command to do, is when I type in the command, which is '/lt add', it will get the block the player is looking at, checking if it is either material type REDSTONE_LAMP_OFF or REDSTONE_LAMP_ON, and then add the block to the ArrayList. And it will also check if the block hasn't been added to the list yet.

    And for my command '/lt remove', it will pretty much do the same, but instead of checking if it is a redstone lamp, it will check if the block is in the list. And if it is, it will remove the block from the ArrayList.

    And that ArrayList, I'd like to have saved in a file called either lamps.csv or lamps.yml.

    This is my current Main class:
    Code:
    package com.greenadine.lamptimer;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.util.ArrayList;
    import java.util.logging.Logger;
    
    import org.bukkit.ChatColor;
    import org.bukkit.block.Block;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import com.greenadine.lamptimer.commands.LampCommandExecutor;
    import com.greenadine.lamptimer.listeners.LampListener;
    
    public class Main extends JavaPlugin {
       
        public String saveFile = "plugins/LampTimer/lamps.csv";
        public ArrayList<Lamp> Lamps = new ArrayList<Lamp>(); // A list of all placed clocks
       
        public static Logger log = Logger.getLogger("Minecraft");
        public static String prefix = ChatColor.BLUE + "[LampListener] ";
        public static String noperm = prefix + ChatColor.RED + "No permission to use this command. Contact administrators if this shouldn't be the case.";
       
        ArrayList<Lamp> lamps;
       
        @SuppressWarnings("unchecked")
        public void onEnable() {
            loadConfiguration();
            LampListener listener = new LampListener(this);
            getServer().getPluginManager().registerEvents(listener, this);
            getCommand("lt").setExecutor(new LampCommandExecutor(this));
            log.info("[LampTimer] Successfully enabled!");
           
            File dir = getDataFolder();
           
            if(!dir.exists()) {
                if(!dir.mkdirs()) {
                    System.out.println("[LampTimer] Could not create directory for plugin LampTimer.");
                }
            }
           
            lamps = (ArrayList<Lamp>) load(new File(getDataFolder(), "lamps.yml"));
           
           
            if(lamps == null) {
                lamps = new ArrayList<Lamp>();
            }
        }
       
        public void onDisable() {
            try {
                save(lamps, new File(getDataFolder(), "lamps.dat"));
            } catch(Exception e) {
                e.printStackTrace();
                log.warning("[LampTimer] Could not save lamps to file!");
            }
           
            log.info("[LampTimer] Successfully disabled!");
        }
    
        private void loadConfiguration() {
            FileConfiguration config = getConfig();
            config.options().header("Enable or disable logging adding lamps, removing lamps and turning on and off of the lamps.");
            config.addDefault("logging", Boolean.valueOf(true));
            config.addDefault("daytime", "800");
            config.addDefault("nighttime", "14000");
            config.options().copyDefaults(true);
            config.options().copyHeader(true);
            saveConfig();
        }
       
        public void save(Object o, File f) {
            try {
                if(!f.exists()) {
                    f.createNewFile();
                }
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
                oos.writeObject(o);
                oos.flush();
                oos.close();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
       
        public Object load(File f) {
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
                Object result = ois.readObject();
                ois.close();
                return result;
            } catch(Exception e) {
                return null;
            }
        }
    }
    And this is my current LampCommandExecutor:
    Code:
    package com.greenadine.lamptimer.commands;
    
    import java.util.ArrayList;
    import java.util.Locale;
    import java.util.Set;
    
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.block.Block;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    
    import com.greenadine.lamptimer.Lamp;
    import com.greenadine.lamptimer.Main;
    
    public class LampCommandExecutor implements CommandExecutor {
       
        private Main plugin;
       
        public LampCommandExecutor(Main plugin) {
            this.plugin = plugin;
        }
       
       
    
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if(!sender.hasPermission(new Permissions().command)) {
                sender.sendMessage(Main.noperm);
                return false;
            }
            if(!(sender instanceof Player)) {
                sender.sendMessage("[LampTimer] This command can only be used by players! Go in-game as an adminsitrator or operator to add/remove lamps to the list.");
                return false;
            } else {
                Player p = (Player) sender;
                if(args.length == 0) {
                    p.sendMessage(ChatColor.BLUE + "---= " + ChatColor.WHITE + "LampTimer" + ChatColor.BLUE + " =---");
                    p.sendMessage(ChatColor.GRAY + "LampTimer plugin version 0.5 made by Kevinzuman22.");
                    p.sendMessage(ChatColor.GRAY + "Available commands:");
                    if(!p.hasPermission(new Permissions().add)) {
                        p.sendMessage(ChatColor.RED + "/lt add - Add the lamp you are looking at to the list.");
                    } else if(p.hasPermission(new Permissions().add)){
                        p.sendMessage(ChatColor.WHITE + "/lt add - Add the lamp you are looking at to the list.");
                    }
                    if(!p.hasPermission(new Permissions().remove)) {
                        p.sendMessage(ChatColor.RED + "/lt remove - Remove the lamp you are looking at to the list.");
                    } else if(p.hasPermission(new Permissions().remove)){
                        p.sendMessage(ChatColor.WHITE + "/lt remove - Remove the lamp you are looking at to the list.");
                    }
                    if(!p.hasPermission(new Permissions().removeall)) {
                        p.sendMessage(ChatColor.RED + "/lt removeall - Remove ALL lamps in the list.");
                    } else if(p.hasPermission(new Permissions().removeall)){
                        p.sendMessage(ChatColor.WHITE + "/lt removeall - Remove ALL lamps in the list.");
                    }
                    p.sendMessage("");
                    p.sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + "Note:");
                    p.sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + "White means you have permission to use that command.");
                    p.sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + "Red means you have no permission to use that command.");
                    return true;
                }
                else if(args.length == 1) {   
                    if(args[0].equalsIgnoreCase("add")) {
                        if(!p.hasPermission(new Permissions().add)) {
                            p.sendMessage(Main.noperm);
                            return false;
                        }
                        Block lamp = (Block) p.getTargetBlock((Set<Material>) null, 200);
                        ArrayList<Lamp> lamps = new ArrayList<Lamp>();
                        if(lamp.getType().equals(Material.REDSTONE_LAMP_OFF) || lamp.getType().equals(Material.REDSTONE_LAMP_ON)) {
                            if(!lamps.contains(lamp.getX() + ";" + lamp.getZ() + ";" + lamp.getY())) {
                               
                                // Add lamp to ArrayList 'lamps'.
                               
                                p.sendMessage(Main.prefix + ChatColor.GREEN + "Successfully added lamp at location X:'" + ChatColor.GOLD + lamp.getX() + ChatColor.GREEN + "', Y:'" + ChatColor.GOLD + lamp.getY() + ChatColor.GREEN + "', Z'" + ChatColor.GOLD + lamp.getZ() + ChatColor.GREEN + "'.");
                               
                            } else {
                                p.sendMessage(Main.prefix + ChatColor.RED + "Lamp could not be added, since it is already in the list.");
                            }
                        } else {
                            p.sendMessage(Main.prefix + ChatColor.RED + "Block type '" + lamp.getType().toString().toLowerCase(Locale.ENGLISH) + "' isn't valid. Valid block types: 'redstone_lamp_on', 'redstone_lamp_off'.");
                        }
                        return true;
                    } else if(args[0].equalsIgnoreCase("remove")) {
                        if(!p.hasPermission(new Permissions().remove)) {
                            p.sendMessage(Main.noperm);
                            return false;
                        }
                        Block lamp = (Block) p.getTargetBlock((Set<Material>) null, 200);
                        if(lamp.getType().equals(Material.REDSTONE_LAMP_OFF) || lamp.getType().equals(Material.REDSTONE_LAMP_ON)) {
                            ArrayList<Block> lamps = new ArrayList<Block>();
                            if(lamps.contains(lamp.getX() + ";" + lamp.getZ() + ";" + lamp.getY())) { // NOTE: How do I check if it is in the ArrayList correctly?
                               
                                // TODO Remove lamp from ArrayList 'lamps'.
                                p.sendMessage(Main.prefix + ChatColor.GREEN + "Successfully removed lamp from list.");
                            } else {
                                p.sendMessage(Main.prefix + ChatColor.RED + "This lamp cannot be removed, since it isn't in the list.");
                            }
                           
                        } else {
                            p.sendMessage(Main.prefix + ChatColor.RED + "Block type '" + lamp.getType().toString().toLowerCase(Locale.ENGLISH) + "' isn't valid. Valid block types: 'redstone_lamp_on', 'redstone_lamp_off'.");
                        }
                       
                        return true;
                    } else if(args[0].equalsIgnoreCase("removeall")) {
                        if(!p.hasPermission(new Permissions().removeall)) {
                            p.sendMessage(Main.noperm);
                            return false;
                        }
                        ArrayList<Lamp> lamps = new ArrayList<Lamp>();
    
                        // Clear ArrayList 'lamps'.
                       
                        p.sendMessage(Main.prefix + ChatColor.WHITE + "Successfully removed" + ChatColor.RED + " ALL " + ChatColor.WHITE + "lamps from list!");
                        if(plugin.getConfig().getBoolean("logging") == Boolean.valueOf(true)) {
                            Main.log.info("[LampTimer] Removed ALL lamps from list!");
                        } else {
                            //Do nothing.
                        }
                    } else if(args[0].equalsIgnoreCase("reload")) {
                        if(!p.hasPermission(new Permissions().reload)) {
                            p.sendMessage(Main.noperm);
                        }
                        try {
                            plugin.reloadConfig();
                        } catch(Exception e) {
                            p.sendMessage(Main.prefix + ChatColor.RED + "Could not reload config! See console for information.");
                            Main.log.warning("[LampTimer] Could not reload config!");
                            plugin.saveConfig();
                            e.printStackTrace();
                            return false;
                        }
                        p.sendMessage(Main.prefix + ChatColor.WHITE + "Successfully reloaded config!");
                       
                    } else {
                        p.sendMessage(Main.prefix + ChatColor.RED + "'" + args[0]+ "' is not a recognized command! Type '/lt' for a list of available commands.");
                        return false;
                    }
                } else {
                    p.sendMessage(Main.prefix + ChatColor.RED + "Arguments are not required. Look at the Redstone Lamp you want to add or remove, and then use a command.");
                    return false;
                }
            }
           
            return false;
        }
    }

    Every function in the CommandExecutor works, except for adding and removing the actual blocks to or from the ArrayList.

    And also, I do not know how to make a listener that will turn the lamps on and off at day and night. Is there are listener for that, or do I need to make a scheduler for that? And if I do need to use a scheduler, how do I make one that will work inside the listener?

    My current LampListener (I will change '(event)' with the event type: which event type should I use?):
    Code:
    public void onDayNightEvent((event) e) {
            Block block = e.getBlock();
            ArrayList<Lamp> lamps = new ArrayList<Lamp>();
            if(block.getType().equals(Material.REDSTONE_LAMP_OFF) && lamps.contains(block.getWorld().toString() + ";" + block.getX() + ";" + block.getY() + ";" + block.getZ()) && block.getWorld().getTime() == plugin.getConfig().getInt("daytime")) {
                block.setType(Material.REDSTONE_LAMP_ON);
                if(plugin.getConfig().getBoolean("logging") == Boolean.valueOf(true)) {
                    plugin.getLogger().info("[LampTimer] All registered lamps are now turned on.");
                } else {
                    //Do nothing.
                }
            }
            else if(block.getType().equals(Material.REDSTONE_LAMP_ON) && lamps.contains(block.getWorld().toString() + ";" + block.getX() + ";" + block.getY() + ";" + block.getZ()) && block.getWorld().getTime() == plugin.getConfig().getInt("nighttime")) {
                block.setType(Material.REDSTONE_LAMP_OFF);
                if(plugin.getConfig().getBoolean("logging") == Boolean.valueOf(true)) {
                    plugin.getLogger().info("[LampTimer] All registered lamps are now off.");
                } else {
                    //Do nothing.
                }
            } else {
                //Do nothing.
            }
        }
    Any suggestions or solutions for my problems? Thanks in advance!
     
  2. Offline

    mcdorli

    Code:
    if(!p.hasPermission(new Permissions().add)) {
                        p.sendMessage(ChatColor.RED + "/lt add - Add the lamp you are looking at to the list.");
                    } else if(p.hasPermission(new Permissions().add)){
                        p.sendMessage(ChatColor.WHITE + "/lt add - Add the lamp you are looking at to the list.");
                    }
                    if(!p.hasPermission(new Permissions().remove)) {
                        p.sendMessage(ChatColor.RED + "/lt remove - Remove the lamp you are looking at to the list.");
                    } else if(p.hasPermission(new Permissions().remove)){
                        p.sendMessage(ChatColor.WHITE + "/lt remove - Remove the lamp you are looking at to the list.");
                    }
                    if(!p.hasPermission(new Permissions().removeall)) {
                        p.sendMessage(ChatColor.RED + "/lt removeall - Remove ALL lamps in the list.");
                    } else if(p.hasPermission(new Permissions().removeall)){
                        p.sendMessage(ChatColor.WHITE + "/lt removeall - Remove ALL lamps in the list.");
                    }
    
    what? Use a specific permission, like lamptimer.add.
    Errors?
     
  3. Offline

    Tecno_Wizard

  4. @mcdorli I am using the permission lamptimer.add, but it is defined in my Permissions class together with all my other permission nodes, which looks like this:
    Code:
    package com.greenadine.lamptimer.commands;
    
    import org.bukkit.permissions.Permission;
    
    public class Permissions {
    
        public Permission command = new Permission("lamptimer.command");
        public Permission add = new Permission("lamptimer.add");
        public Permission remove = new Permission("lamptimer.remove");
        public Permission removeall = new Permission("lamptimer.remove.all");
        public Permission reload = new Permission("lamptimer.reload");
    
    }
    This way I can access it more easily, or at least in my opinion it is easier.

    And for the errors, I was first using this method to add a lamp:
    Code:
    Block lamp = (Block) p.getTargetBlock((Set<Material>) null, 200);
    ArrayList<Lamp> lamps = new ArrayList<Lamp>();
    if(lamp.getType().equals(Material.REDSTONE_LAMP_OFF) || lamp.getType().equals(Material.REDSTONE_LAMP_ON)) {
        if(!lamps.contains(lamp.getX() + ";" + lamp.getZ() + ";" + lamp.getY())) {
            lamps.add((Lamp) lamp);
            p.sendMessage(Main.prefix + ChatColor.GREEN + "Successfully added lamp at location X:'" + ChatColor.GOLD + lamp.getX() + ChatColor.GREEN + "', Y:'" + ChatColor.GOLD + lamp.getY() + ChatColor.GREEN + "', Z'" + ChatColor.GOLD + lamp.getZ() + ChatColor.GREEN + "'.");
        } else {
            p.sendMessage(Main.prefix + ChatColor.RED + "Lamp could not be added, since it is already in the list.");
        }
    } else {
        p.sendMessage(Main.prefix + ChatColor.RED + "Block type '" + lamp.getType().toString().toLowerCase(Locale.ENGLISH) + "' isn't valid. Valid block types: 'redstone_lamp_on', 'redstone_lamp_off'.");
    }
    It tracked the block the player was looking at correctly, and all other functions worked as they should, but only on "lamp.add((Lamp) lamp)" I got errors

    These are the errors I got by using '/lamptimer add' with using the method I named above:
    At the end, it will say 'at com.greenadine.lamptimer.commands.LampCommandExecutor.onCommand(LampCommandExecutor.java:73) ~[?:?]'

    Line 73 contains the method "lamps.add((Lamp) lamp);".

    Any ideas on what might be the solution for this? And could you maybe also tell me what I should put in the Lamp class? Thanks in advance!

    EDIT: I read the error log a few times, and I saw it said "unhandled exception". I added a try/catch to the 'lamp.add((Lamp) lamp)', but now I get this error:
    This error says the same: an error on line 74, which contains "lamp.add((Lamp) lamp)". And it says class 'Lamp' cannot be casted block 'lamp'. I am guessing I haven't done the Lamp class correctly?
     
    Last edited: Jan 1, 2016
  5. Offline

    Tecno_Wizard

    @Kevinzuman22, did you learn C, because structures like your Permissions class just aren't proper in Java. You want an enum. Look it up.

    Your Lamp class isnt a block, yet you try to cast it like it is. .equals is unnecessary with final constants. You can't check for a lamp using a string with its data.

    You need to understand java and OOP more before you work with bukkit. We're not just going to spoonfeed you.
     
Thread Status:
Not open for further replies.

Share This Page