What would be the best way to create a money printer?

Discussion in 'Plugin Development' started by callum2904, Jul 22, 2014.

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

    callum2904

    I am recreating printers from the DarkRP Gmod gamemode and I was wondering what the best way would be to create these.
    The printers will be a chest that i place and then using the holographic displays api i will create two displays above the printer, the printer owners name and the amount of money in the printer.

    How should i store the data? In hashmaps?
    Hashmap 1 = string and int - name and money increment
    Hashmap 2 = string and int - name and printer limit

    If anyone has existing code that i could look at or know any plugins which do something like this itd be helpful.
    I already took a look at the LightRP plugins source but it has code for different things everywhere and is unhelpful. Its classes are not seperated very well so it is hard to learn from it.

    Thanks.
     
  2. callum2904 Why not simply create a Printer object?
     
  3. Offline

    callum2904

    Iv created this
    Code:
    import java.util.ArrayList;
    
    import me.callum2904.Roleplay.Main;
    import me.callum2904.Roleplay.Threads.PrinterSchedule;
    import me.callum2904.Roleplay.Utils.Variables;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Location;
    import org.bukkit.Material;
    import org.bukkit.entity.Player;
    
    import com.gmail.filoghost.holograms.api.Hologram;
    import com.gmail.filoghost.holograms.api.HolographicDisplaysAPI;
    
    public class Printer {
    
    	private Location location;
    	private Player owner;
    	private String printerType;
    	private int money = 0;
    	private PrinterSchedule schedule = new PrinterSchedule(this);
    	public Hologram name;
    	public Hologram balance;
    
    	public static ArrayList<Printer> printers = new ArrayList<Printer>();
    
    	public Printer(Player owner, Location location, String printerType) {
    		if (Variables.PrinterType.contains(printerType.toUpperCase())) {
    			this.printerType = printerType;
    			this.owner = owner;
    			this.location = location;
    			
    			
    			
    			printers.add(this);
    
    			Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), schedule, 10L, 10L);
    			name = HolographicDisplaysAPI.createHologram(Main.getInstance(),
    					location.add(0, 0.7, 0), owner.getName());
    			balance = HolographicDisplaysAPI.createHologram(Main.getInstance(),
    					location.add(0, 0.3, 0), money + "");
    		}else{
    			Main.getInstance().sendErrorMessage(owner, "Could not create that printer! Invalid printer type!");
    		}
    	}
    	
    	public String getPrinterType(){
    		return this.printerType;
    	}
    
    	public Location getLocation() {
    		return this.location;
    	}
    
    	public Player getOwner() {
    		return this.owner;
    	}
    
    	public int getMoney() {
    		return this.money;
    	}
    
    	public void setMoney(int amount) {
    		this.money = amount;
    	}
    
    	public void addMoney(int amount) {
    		this.money += amount;
    	}
    
    	public void removeMoney(int amount) {
    		this.money -= amount;
    	}
    
    	public void destroy() {
    		Main.getInstance().sendMessage(owner, "Your printer has been destoyed!");
    		location.getBlock().setType(Material.AIR);
    		schedule.cancel();
    		balance.delete();
    		name.delete();
    		printers.remove(this);
    	}
    
    }
    
    And i also created a sheduler like this
    Code:
    import me.callum2904.Roleplay.Main;
    import me.callum2904.Roleplay.Objectives.Printer;
    import me.callum2904.Roleplay.Utils.Variables;
    
    import org.bukkit.Bukkit;
    import org.bukkit.scheduler.BukkitRunnable;
    
    public class PrinterSchedule extends BukkitRunnable {
    
    	private Printer printer;
    	private int increment;
    
    	private int getIncrement() {
    		for(String string : Variables.PrinterIncrements.keySet()){
    			if(string != null){
    				if(string.equalsIgnoreCase(printer.getPrinterType())){
    					return Variables.PrinterIncrements.get(string);
    				}
    			}
    		}
    		return 0;
    	}
    
    	public PrinterSchedule(Printer printer) {
    		this.printer = printer;
    		this.increment = getIncrement();
    	}
    
    	public void run() {
    
    		Main.getInstance().sendWarningMessage(Bukkit.getPlayer("callum2904"), "Adding " + increment);
    		printer.addMoney(increment);
    		printer.balance.clearLines();
    		printer.balance.addLine(printer.getMoney() + "");
    		printer.balance.update();
    	}
    
    }
    
    but the increment doesnt work for some reason
     
  4. callum2904 I think you should learn a bit more of Java - some of this doesn't really seem to follow the basic principles of it, and your code seems needlessly convoluted. There's also a problem such as what happens if a player disconnects from the server while they have a printer? Potential source of memory leak there.
     
  5. Offline

    callum2904

    I created this within 5 - 6 minutes of the first post it was meant as a basis not as the final product. I just wanted to see how others would do something like this.
     
  6. Offline

    TehVoyager

    callum2904

    In your class you should probably use UUID, not player objects.

    Maybe make an update method that reloads the displays to have the right amounts.
     
  7. Offline

    callum2904

    Would someone be able to fix this for me
    Code:
    package me.callum2904.Roleplay.Objectives;
    
    import java.util.ArrayList;
    import java.util.UUID;
    
    import me.callum2904.Roleplay.Main;
    import me.callum2904.Roleplay.Threads.PrinterSchedule;
    import me.callum2904.Roleplay.Utils.Methods;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.block.Block;
    
    import com.gmail.filoghost.holograms.api.Hologram;
    import com.gmail.filoghost.holograms.api.HolographicDisplaysAPI;
    
    public class Printer {
    	protected PrinterSchedule ps = new PrinterSchedule(this);
    	private int money = 0;
    	private Block block;
    	private UUID owner;
    	private String pName;
    	public Hologram playerName;
    	public Hologram moneyValue;
    
    	public static ArrayList<Printer> Printers = new ArrayList<Printer>();
    
    	public Printer(Block block, UUID owner) {
    		if (!Printers.contains(this)) {
    			Printers.add(this);
    			this.owner = owner;
    			this.block = block;
    			this.pName = Bukkit.getPlayer(owner).getName();
    			this.playerName = HolographicDisplaysAPI.createHologram(Main.getInstance(), block
    					.getLocation().add(0.5, 0.7, 0.5), this.pName);
    			this.moneyValue = HolographicDisplaysAPI.createHologram(Main.getInstance(), block
    					.getLocation().add(0.5, 0.3, 0.5), money + "");
    			this.ps.scheduleTask(Main
    					.getInstance()
    					.getServer()
    					.getScheduler()
    					.runTaskTimer(Main.getInstance(), this.ps,
    							Methods.getMethods().getInterval(block.getType()) * 20,
    							Methods.getMethods().getInterval(block.getType()) * 20));
    		}else{
    			Main.getInstance().sendErrorMessage(Bukkit.getPlayer(owner), "Cannot create another printer!");
    		}
    	}
    
    	public void addMoney(int m) {
    		this.money += m;
    	}
    
    	public void removeMoney(int m) {
    		this.money -= m;
    	}
    
    	public int getMoney() {
    		return this.money;
    	}
    
    	public Block getBlock() {
    		return this.block;
    	}
    
    	public void delete() {
    		this.block.setType(Material.AIR);
    		this.moneyValue.delete();
    		this.playerName.delete();
    		this.ps.cancelTask();
    	}
    
    	public UUID getOwner() {
    		return this.owner;
    	}
    }
    
    
    Code:
    import me.callum2904.Roleplay.Objectives.Printer;
    import me.callum2904.Roleplay.Utils.Methods;
    
    import org.bukkit.scheduler.BukkitTask;
    
    public class PrinterSchedule implements Runnable {
    	protected BukkitTask id;
    	private final Printer printer;
    
    	public PrinterSchedule(Printer printer) {
    		this.printer = printer;
    	}
    
    	public void scheduleTask(BukkitTask bukkitTask) {
    		this.id = bukkitTask;
    	}
    
    	public void cancelTask() {
    		this.id.cancel();
    	}
    
    	public Printer getPrinter() {
    		return this.printer;
    	}
    
    	public void run() {
    		this.printer.addMoney(Methods.getMethods().getIncremenet(printer.getBlock().getType()));
    		printer.moneyValue.clearLines();
    		printer.moneyValue.addLine(printer.getMoney() + "");
    		printer.moneyValue.update();
    	}
    }
    
    Code:
    import me.callum2904.Roleplay.Objectives.Printer;
    
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.BlockBreakEvent;
    
    public class BlockBreakListener implements Listener{
    	
    	@EventHandler
    	public void onBlockBreak(BlockBreakEvent event){
    		for(Printer printer : Printer.Printers){
    			if(printer.getBlock().equals(event.getBlock())){
    				printer.delete();
    			}
    		}
    	}
    
    }
    
    Code:
    import me.callum2904.Roleplay.Main;
    import me.callum2904.Roleplay.Objectives.Printer;
    import me.callum2904.Roleplay.Utils.Methods;
    
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.player.PlayerInteractEvent;
    
    public class BlockPlaceListener implements Listener{
    
    	@EventHandler
    	public void onInteract(PlayerInteractEvent event){
    		Player player = event.getPlayer();
    		if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
    			if(Methods.getMethods().isPrinterBlock(event.getClickedBlock().getType()) && player.isOp()){
    				if(ChatColor.translateAlternateColorCodes('&', Methods.getMethods().getPrinterName(event.getClickedBlock().getType())).equalsIgnoreCase(player.getItemInHand().getItemMeta().getDisplayName())){
    					if(event.getClickedBlock().getLocation().add(0, 1, 0).getBlock().getType() == Material.AIR){
    						if(Main.getInstance().canUseHolographicDisplays() != true)
    							return;
    						@SuppressWarnings("unused")
    						Printer printer = new Printer(event.getClickedBlock(), player.getUniqueId());
    						player.getItemInHand().setType(Material.AIR);
    					}
    				}
    			}
    		}
    	}
    }
    
    Code:
    public class PrinterCommands implements CommandExecutor {
    
    	@Override
    	public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
    
    		if (sender instanceof Player) {
    			Player player = (Player) sender;
    			Config config = new Config("Config", Main.getInstance());
    			if (commandLabel.equalsIgnoreCase("Printer")) {
    				if (args.length == 0) {
    					player.sendMessage(ChatColor.RED + "| Printer | " + ChatColor.WHITE
    							+ "/Printer list");
    					player.sendMessage(ChatColor.RED + "| Printer | " + ChatColor.WHITE
    							+ "/Printer get <name>");
    					return true;
    				} else if (args.length == 1) {
    					if (args[0].equalsIgnoreCase("List")) {
    						for (String string : config.getConfig().getConfigurationSection("Printer")
    								.getKeys(false)) {
    							if (string != null) {
    								if (config.getConfig().contains("Printer." + string + ".Name")) {
    									player.sendMessage(ChatColor.RED
    											+ "| Printer List | "
    											+ ChatColor.WHITE
    											+ ChatColor.translateAlternateColorCodes(
    													'&',
    													config.getConfig().getString(
    															"Printer." + string + ".Name")));
    									return true;
    								}
    							}
    						}
    					}
    				}else if(args.length == 2){
    					if(args[0].equalsIgnoreCase("Get")){
    						String printerName = args[1];
    						for (String string : config.getConfig().getConfigurationSection("Printer")
    								.getKeys(false)) {
    							if (string != null) {
    								if (config.getConfig().contains("Printer." + string + ".Name")) {
    									String configPrinterName = ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', config.getConfig().getString("Printer." + string + ".Name")));
    									if(printerName.equalsIgnoreCase(configPrinterName)){
    										@SuppressWarnings("deprecation")
    										Material material = Material.getMaterial(config.getConfig().getInt("Printer." + string + ".Material"));
    										ItemStack item = new ItemStack(material, 1);
    										ItemMeta meta = item.getItemMeta();
    										meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getConfig().getString("Printer." + string + ".Name")));
    										item.setItemMeta(meta);
    										player.getInventory().addItem(item);
    										return true;
    									}
    								}
    							}
    						}
    					}
    				}
    			}
    		}
    
    		return false;
    	}
    
    }
    
    Code:
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    
    import me.callum2904.Roleplay.Main;
    import me.callum2904.Roleplay.Objectives.Printer;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Location;
    import org.bukkit.Material;
    import org.bukkit.Server;
    import org.bukkit.command.ConsoleCommandSender;
    
    public class Methods {
    	
    	public static ArrayList<Material> PrinterMaterials = new ArrayList<Material>();
    	
    	private static Methods methods = new Methods();
    
    	public static Methods getMethods() {
    		return methods;
    	}
    
    	public String serilizeLoc(Location loc) {
    		return "" + loc.getWorld().getName() + "," + loc.getBlockX() + "," + loc.getBlockY() + ","
    				+ loc.getBlockZ();
    	}
    
    	public Location deserilizeLoc(String string) {
    		if (string.contains(",")) {
    			String[] args = string.split(",");
    			if (args.length == 4) {
    				return new Location(Bukkit.getWorld(args[0]), Integer.parseInt(args[1]),
    						Integer.parseInt(args[2]), Integer.parseInt(args[3]));
    			}
    		}
    		return null;
    	}
    	
    	public List<Config> getFiles(String directory) {
    		List<Config> configs = new ArrayList<Config>();
    		File file = new File(directory);
    		if (file.exists()) {
    			File files[] = null;
    			if (file.isDirectory()) {
    
    				files = file.listFiles();
    				if (files.length != 0) {
    					for (File dirFile : files) {
    
    						if (!dirFile.isDirectory()) {
    							if (dirFile.getName().endsWith(".yml")) {
    
    								Config config = new Config(new File(directory), dirFile.getName()
    										.replace(".yml", ""), Main.getInstance());
    
    								configs.add(config);
    							}
    						}
    					}
    				}
    			}
    		}
    		return configs;
    	}
    	
    	public String displayXYZ(Location loc){
    		return "(" + loc.getBlockX() + " " + loc.getBlockY() + " " + loc.getBlockZ() + ")";
    	}
    	
    	public void printlnfx(String message) {
            Server server = Bukkit.getServer();
            ConsoleCommandSender console = server.getConsoleSender();
            console.sendMessage(message);
        }
    	
    	public void createFolder(String name){
    		File file = new File(name);
    		if (!file.exists()) {
    			if (file.mkdir()) {
    				System.out.println("Directory is created!");
    			} else {
    				System.out.println("Failed to create directory!");
    			}
    		}
    	}
    	
    	public void loadPrinterBlocks(){
    		Config config = new Config("Config", Main.getInstance());
    		for(String string : config.getConfig().getConfigurationSection("Printer").getKeys(false)){
    			if(string != null){
    				@SuppressWarnings("deprecation")
    				Material matId = Material.getMaterial(config.getConfig().getInt("Printer." + string + ".Material"));
    				PrinterMaterials.add(matId);
    			}
    		}
    	}
    	
    	public boolean isPrinterBlock(Material mat){
    		if(PrinterMaterials.contains(mat))
    			return true;
    		return false;
    	}
    	
    	@SuppressWarnings("deprecation")
    	public String getPrinterName(Material mat){
    		if(PrinterMaterials.contains(mat)){
    			Config config = new Config("Config", Main.getInstance());
    			for(String string : config.getConfig().getConfigurationSection("Printer").getKeys(false)){
    				if(string != null){
    					int matId = config.getConfig().getInt("Printer." + string + ".Material");
    					if(mat.getId() == matId){
    						if(config.getConfig().contains("Printer." + string + ".Name")){
    							return config.getConfig().getString("Printer." + string + ".Name");
    							
    						}
    					}
    				}
    			}
    		}
    		return null;
    	}
    	
    	@SuppressWarnings("deprecation")
    	public int getInterval(Material material){
    		Config config = new Config("Config", Main.getInstance());
    		for(String string : config.getConfig().getConfigurationSection("Printer").getKeys(false)){
    			if(string != null){
    				int matId = config.getConfig().getInt("Printer." + string + ".Material");
    				if(material.getId() == matId){
    					if(config.getConfig().contains("Printer." + string + ".Interval")){
    						return config.getConfig().getInt("Printer." + string + ".Interval");
    					}
    				}
    			}
    		}
    		return 0;
    	}
    	
    	@SuppressWarnings("deprecation")
    	public int getIncremenet(Material material){
    		Config config = new Config("Config", Main.getInstance());
    		for(String string : config.getConfig().getConfigurationSection("Printer").getKeys(false)){
    			if(string != null){
    				int matId = config.getConfig().getInt("Printer." + string + ".Material");
    				if(material.getId() == matId){
    					if(config.getConfig().contains("Printer." + string + ".Increment")){
    						return config.getConfig().getInt("Printer." + string + ".Increment");
    					}
    				}
    			}
    		}
    		return 0;
    	}
    
    }
    
    Code:
    import java.io.File;
    import java.io.IOException;
    import java.util.logging.Level;
    
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.plugin.Plugin;
    
    public class Config {
    	private final Plugin PLUGIN;
    	private final String FILENAME;
    	private final File FOLDER;
    	private FileConfiguration config;
    	private File configFile;
    
    	public Config(String filename, Plugin instance) {
    		if (!filename.endsWith(".yml")) {
    			filename += ".yml";
    		}
    		this.FILENAME = filename;
    		this.PLUGIN = instance;
    		this.FOLDER = this.PLUGIN.getDataFolder();
    		this.config = null;
    		this.configFile = null;
    		reload();
    	}
    
    	public Config(File folder, String filename, Plugin instance) {
    		if (!filename.endsWith(".yml")) {
    			filename += ".yml";
    		}
    		this.FILENAME = filename;
    		this.PLUGIN = instance;
    		this.FOLDER = folder;
    		this.config = null;
    		this.configFile = null;
    		reload();
    	}
    
    	public FileConfiguration getConfig() {
    		if (config == null) {
    			reload();
    		}
    		return config;
    	}
    
    	public void reload() {
    		if (!this.FOLDER.exists()) {
    			try {
    				if (this.FOLDER.mkdir()) {
    					this.PLUGIN.getLogger().log(Level.INFO,
    							"Folder " + this.FOLDER.getName() + " created.");
    				} else {
    					this.PLUGIN.getLogger().log(Level.WARNING,
    							"Unable to create folder " + this.FOLDER.getName() + ".");
    				}
    			} catch (Exception e) {
    
    			}
    		}
    		configFile = new File(this.FOLDER, this.FILENAME);
    		if (!configFile.exists()) {
    			try {
    				configFile.createNewFile();
    			} catch (IOException e) {
    
    			}
    		}
    		config = YamlConfiguration.loadConfiguration(configFile);
    	}
    
    	public void saveDefaultConfig() {
    		if (configFile == null) {
    			configFile = new File(this.PLUGIN.getDataFolder(), this.FILENAME);
    		}
    
    		if (!configFile.exists()) {
    			this.PLUGIN.saveResource(this.FILENAME, false);
    		}
    	}
    
    	public void save() {
    		if (config == null || configFile == null) {
    			return;
    		}
    		try {
    			getConfig().save(configFile);
    		} catch (IOException ex) {
    			this.PLUGIN.getLogger().log(Level.WARNING,
    					"Could not save config to " + configFile.getName(), ex);
    		}
    	}
    
    	public void set(String path, Object o) {
    		getConfig().set(path, o);
    	}
    
    Can someone help me by fixing this! I can get the from commands fine, I can place them and it starts the timer, I can break them but it doesnt remove the hologram.

    PLEASE HELP THIS IS MAKING ME GO CRAZY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     
Thread Status:
Not open for further replies.

Share This Page