Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package net.minelounge.economy;
- import net.milkbowl.vault.economy.Economy;
- import org.bukkit.Bukkit;
- import org.bukkit.ChatColor;
- import org.bukkit.Location;
- import org.bukkit.Material;
- import org.bukkit.block.Block;
- import org.bukkit.block.Sign;
- import org.bukkit.command.Command;
- import org.bukkit.command.CommandExecutor;
- import org.bukkit.command.CommandSender;
- import org.bukkit.configuration.ConfigurationSection;
- import org.bukkit.configuration.file.FileConfiguration;
- import org.bukkit.configuration.file.YamlConfiguration;
- import org.bukkit.entity.EntityType;
- import org.bukkit.event.EventHandler;
- import org.bukkit.event.Listener;
- import org.bukkit.event.entity.EntityDeathEvent;
- import org.bukkit.event.entity.EntityDropItemEvent;
- import org.bukkit.inventory.ItemStack;
- import org.bukkit.plugin.RegisteredServiceProvider;
- import org.bukkit.plugin.java.JavaPlugin;
- import org.bukkit.scheduler.BukkitRunnable;
- import java.io.*;
- import java.util.*;
- public class GoldEconomyPlugin extends JavaPlugin {
- private HashMap<Material,Set<Location>> trackedSigns = new HashMap<Material,Set<Location>>();
- private HashMap<Material, Integer> startingPrices = new HashMap<Material,Integer>();
- private HashMap<Material, Integer> itemStock = new HashMap<Material, Integer>();
- //private Set<StockEvent> stockEvents;
- private FileConfiguration signConfig;
- private FileConfiguration stocksConfig;
- private File signsFile;
- private File stocksFile;
- private double goldPrice = 1000;
- private final int defaultGoldStock = 8000;
- private final long appreciationInterval = 24 * 60 * 60; //seconds
- private final long stockEventTimeLength = 1000L * 60L * 60L * 24L * 30L * 3L; // every 90 days
- private final int validationThreshold = 100; // If prices move more than this, something went wrong, so reset stock values
- private final double sellModifier = 0.4;
- private MarketFormula marketFormula;
- private final boolean updateStocksEverySign = true;
- private Economy economy;
- private Random random;
- private final double goldChance = 0.1;
- public void onEnable(){
- marketFormula = new SimpleMarketFormula();
- economy = setupEconomy();
- random = new Random();
- getCommand("resetstocks").setExecutor(new CommandExecutor() {
- @Override
- public boolean onCommand(CommandSender sender, Command command, String s, String[] strings) {
- if (!sender.hasPermission("goldeconomy.op")){
- return false;
- }
- itemStock.clear();
- if (stocksFile != null){
- try{
- stocksFile.delete();
- stocksFile.createNewFile();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- sender.sendMessage(ChatColor.GREEN + "Reset all stocks!");
- return true;
- }
- });
- getConfig().addDefault("gold-price", 1000);
- getConfig().addDefault("gold-item", Material.GOLD_INGOT.name());
- getConfig().addDefault("last-appreciation", 0L);
- saveConfig();
- goldPrice = getConfig().getInt("gold-price");
- if (getConfig().getLong("last-appreciation") < (System.currentTimeMillis() - (appreciationInterval * 1000))){
- goldPrice = marketFormula.appreciateGold(goldPrice);
- getConfig().set("gold-price", goldPrice);
- getConfig().set("last-appreciation", System.currentTimeMillis());
- saveConfig();
- }
- trackedSigns = new HashMap<Material, Set<Location>>();
- signsFile = new File(getDataFolder(), "signs.yml");
- signConfig = new YamlConfiguration();
- try{
- if (!signsFile.exists()){
- signsFile.createNewFile();
- }
- signConfig.load(signsFile);
- }catch(Exception e){
- e.printStackTrace();
- getServer().getPluginManager().disablePlugin(this);
- }
- for (String key : signConfig.getKeys(false)){
- String name = signConfig.getString(key+".name");
- String mat = signConfig.getString(key+".material");
- Material material = Material.valueOf(mat);
- int startingPrice = signConfig.getInt(key+".starting_price");
- double x = signConfig.getDouble(key+".x");
- double y = signConfig.getDouble(key+".y");
- double z = signConfig.getDouble(key+".z");
- String world = signConfig.getString(key+".world");
- Location l = new Location(Bukkit.getWorld(world), x, y, z);
- if (!trackedSigns.containsKey(material)) trackedSigns.put(material, new HashSet<Location>());
- trackedSigns.get(material).add(l);
- if (startingPrices.containsValue(material)){
- if (startingPrices.get(material) != startingPrice){
- Bukkit.getLogger().warning("Conflicting starting prices for "+mat + " found!");
- }
- }
- startingPrices.put(material, startingPrice);
- }
- //stockEvents = new HashSet<StockEvent>();
- /*stocksFile = new File(getDataFolder(), "stock-events.txt");
- try{
- if (!stocksFile.exists()){
- stocksFile.createNewFile();
- }
- BufferedReader read = new BufferedReader(new FileReader(stocksFile));
- String line = read.readLine();
- // LINE: Material_name stock
- while (line != null){
- //parse line
- String[] parts = line.split(" ");
- Material m = Material.valueOf(parts[0]);
- if (m == null) {
- Bukkit.getLogger().warning("Could not read material "+parts[0]);
- line = read.readLine();
- continue;
- }
- int amount = Integer.valueOf(parts[1]);
- long time = Long.valueOf(parts[2]);
- if (System.currentTimeMillis() - time > stockEventTimeLength){
- line = read.readLine();
- continue;
- }
- int curr = Integer.valueOf(parts[3]);
- StockEvent event = new StockEvent(m, amount, time, curr);
- if (amount > 0) addStock(m, amount);
- else if (amount < 0) removeStock(m, -amount);
- stockEvents.add(event);
- //don't really need to handle if amount = 0
- line = read.readLine();
- }
- read.close();
- }catch(Exception e){
- e.printStackTrace();
- }*/
- //TODO get stocks from file
- stocksFile = new File(getDataFolder(), "stocks.yml");
- try{
- if (!stocksFile.exists()){
- stocksFile.createNewFile();
- }
- stocksConfig = new YamlConfiguration();
- stocksConfig.load(stocksFile);
- for (String key : stocksConfig.getKeys(false)){
- itemStock.put(Material.getMaterial(key), stocksConfig.getInt(key));
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- if (!itemStock.containsKey(Material.GOLD_INGOT)){
- itemStock.put(Material.GOLD_INGOT, defaultGoldStock);
- }
- getServer().getPluginManager().registerEvents(new GoldSignListener(this, economy), this);
- getServer().getPluginManager().registerEvents(new Listener() {
- @EventHandler
- public void drop(EntityDeathEvent event){
- if (event.getEntityType() == EntityType.PIG_ZOMBIE){
- for (ItemStack is : event.getDrops().toArray(new ItemStack[0])){
- if (is.getType() == Material.GOLD_NUGGET || is.getType() == Material.GOLD_INGOT){
- if (random.nextDouble() > goldChance){
- event.getDrops().remove(is);
- }
- }
- }
- }
- }
- }, this);
- new BukkitRunnable(){
- public void run(){
- if (trackedSigns.size() == 0) return;
- List<Material> keys = new ArrayList<Material>(trackedSigns.keySet());
- Material m = keys.get(random.nextInt(keys.size()));
- updateSigns(m);
- }
- }.runTaskTimer(this, 100L, 100L);
- }
- public void onDisable(){
- //save tracked signs
- FileConfiguration y = new YamlConfiguration();
- for (Set<Location> set : trackedSigns.values()){
- for (Location l : set){
- if (l == null) continue;
- Block b = l.getBlock();
- if (b.getType() != Material.OAK_SIGN && b.getType() != Material.OAK_WALL_SIGN) continue;
- Sign s = (Sign)b.getState();
- Material m = Material.matchMaterial(s.getLine(2));
- if (m == null) continue;
- ConfigurationSection section = y.createSection(String.valueOf(l.hashCode()));
- section.set("name", m.name());
- section.set("material", m.name());
- section.set("starting_price", startingPrices.get(m));
- section.set("x", l.getX());
- section.set("y", l.getY());
- section.set("z", l.getZ());
- section.set("world", l.getWorld().getName());
- }
- }
- try{
- y.save(signsFile);
- }catch(Exception e){
- Bukkit.getLogger().warning("Could not save market signs!");
- e.printStackTrace();
- }
- if (stocksConfig == null){
- stocksConfig = new YamlConfiguration();
- }
- for (Map.Entry<Material, Integer> stock : itemStock.entrySet()){
- stocksConfig.set(stock.getKey().toString(), stock.getValue());
- }
- try{
- stocksConfig.save(stocksFile);
- }catch(Exception e){
- e.printStackTrace();
- }
- /*stocksFile.delete();
- try{
- stocksFile.createNewFile();
- PrintWriter writer = new PrintWriter(new FileWriter(stocksFile));
- for (StockEvent event : stockEvents){
- writer.println(event.getMaterial().toString() + " "+event.getAmount() + " "+event.getTimestamp() + " "+event.getCurrStock());
- }
- writer.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- */
- }
- public void trackSign(Location location, Material material, int price, int amount, boolean isBuy){
- if (!trackedSigns.containsKey(material)) {
- trackedSigns.put(material, new HashSet<Location>());
- }
- trackedSigns.get(material).add(location);
- if (!hasStock(material) || updateStocksEverySign || !Craftable.isCraftable(material)){
- hardSetStockByPrice(material, price, amount, !isBuy);
- }
- }
- public void hardSetStockByPrice(Material material, int price, int amount, boolean sell){
- int stock = 1;
- if (sell){
- stock = (int) Math.floor(goldPrice * getGoldStock() * amount/ (price / sellModifier)) ;
- startingPrices.put(material, (int) ((price / amount) / sellModifier));
- }
- else{
- stock = (int) Math.floor(goldPrice * getGoldStock() * amount / price) ;
- startingPrices.put(material, (price / amount));
- }
- setStock(material, stock);
- //writeStockEvent(material, stock - getStock(material), getStock(material));
- }
- public void softTrackSign(Location location, Material material){
- if (!trackedSigns.containsKey(material)) {
- trackedSigns.put(material, new HashSet<Location>());
- }
- trackedSigns.get(material).add(location);
- }
- public boolean isTracked(Location location, Material material){
- if (!trackedSigns.containsKey(material)) return false;
- return trackedSigns.get(material).contains(location);
- }
- public void untrackSign(Location location, Material material){
- if (trackedSigns.containsKey(material)){
- trackedSigns.get(material).remove(location);
- }
- if (trackedSigns.get(material).isEmpty()) {
- trackedSigns.remove(material);
- startingPrices.remove(material);
- if(hasStock(material)) {
- itemStock.remove(material);
- }
- /*for (StockEvent event : new HashSet<StockEvent>(stockEvents)){
- if (event.getMaterial() == material){
- stockEvents.remove(event);
- }
- }*/
- }
- }
- public int getPrice(Material item, int amount){
- if (Craftable.isCraftable(item)) return getCraftablePrice(amount, item);
- return getStock(item) * amount;
- }
- public int getCraftablePrice(int amount, Material material){
- int out = 0;
- Craftable recipe = Craftable.getCraftable(material);
- for (ItemStack i : recipe.getConstituents()){
- out += getPrice(i.getType(), i.getAmount());
- }
- return out * amount / recipe.getAmountOut();
- }
- public int getGoldStock(){
- return getStock(Material.GOLD_INGOT);
- }
- private Economy setupEconomy() {
- if (getServer().getPluginManager().getPlugin("Vault") == null) {
- return null;
- }
- RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
- if (rsp == null) {
- return null;
- }
- return rsp.getProvider();
- }
- /*public void makeImbalance(Material material, int amount){
- if (!itemImbalances.containsKey(material)){
- itemImbalances.put(material, amount);
- }
- else{
- itemImbalances.put(material, itemImbalances.get(material) + amount);
- }
- }
- public int getImbalance(Material material){
- if (!itemImbalances.containsKey(material)) return 1;
- return itemImbalances.get(material);
- }*/
- public int getStock(Material material){
- if (material == Material.GOLD_INGOT){
- if (itemStock.containsKey(material)){
- if (itemStock.get(material) < defaultGoldStock) {
- itemStock.put(Material.GOLD_INGOT, defaultGoldStock);
- return defaultGoldStock;
- }
- }
- else{
- itemStock.put(Material.GOLD_INGOT, defaultGoldStock);
- return defaultGoldStock;
- }
- }
- if (itemStock.containsKey(material)) return itemStock.get(material);
- return -1;
- }
- public void addStock(Material material, int amount){
- if (!itemStock.containsKey(material)) itemStock.put(material, amount);
- else itemStock.put(material, itemStock.get(material) + amount); //sets amount to whatever is on the sell sign if the first sign created is a sell sign.
- }
- public void removeStock(Material material, int amount){
- if (!itemStock.containsKey(material)) return;
- itemStock.put(material, Math.max(1, itemStock.get(material) - amount));
- }
- public void setStock(Material material, int amount){
- itemStock.put(material, amount);
- }
- public boolean hasStock(Material material){
- return itemStock.containsKey(material);
- }
- public void updateSigns(Material material){
- if (!trackedSigns.containsKey(material)) return;
- for (Location l : trackedSigns.get(material)){
- Material sType = l.getBlock().getType();
- if (sType != Material.OAK_SIGN && sType != Material.OAK_WALL_SIGN) return;
- Sign sign = (Sign)l.getBlock().getState();
- int amount = Integer.valueOf(sign.getLine(1));
- int price;
- if (!itemStock.containsKey(material) && !Craftable.isCraftable(material)){
- int oldPrice = Integer.valueOf(sign.getLine(3).substring(1));
- hardSetStockByPrice(material, oldPrice, amount, sign.getLine(0).contains("Sell"));
- }
- price = marketFormula.changePriceOnTransaction(getStock(material), getStock(Material.GOLD_INGOT), goldPrice, amount);
- if (Craftable.isCraftable(material)){
- price = getCraftablePrice(amount, material);
- }
- if (sign.getLine(0).contains("Buy") || material == Material.GOLD_INGOT){
- sign.setLine(3, "$"+price);
- }
- else if (sign.getLine(0).contains("Sell")){
- sign.setLine(3, "$"+(int)Math.floor(price * sellModifier));
- }
- sign.update(true);
- }
- }
- /*public void writeStockEvent(Material material, int amount, int curr){
- stockEvents.add(new StockEvent(material, amount, System.currentTimeMillis(), curr));
- }*/
- public void validateStocks(Material m, int amount, int signPrice, boolean isBuy){
- int stock = getStock(m);
- int price;
- if (isBuy){
- price = signPrice;
- }
- else {
- price = (int)Math.floor(signPrice / sellModifier);
- }
- if (Math.abs((marketFormula.changePriceOnTransaction(stock, getGoldStock(), goldPrice, amount) - price)) < validationThreshold){
- return;
- }
- //Bukkit.broadcastMessage(""+stock);
- hardSetStockByPrice(m, signPrice, amount, !isBuy);
- }
- public MarketFormula getFormula(){
- return marketFormula;
- }
- public double getGoldPrice(){
- return goldPrice;
- }
- public double getSellModifier(){
- return sellModifier;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement