Initial commit

This commit is contained in:
Scifi9902
2026-10-12 13:57:05 -03:00
commit 4bde3b176a
2576 changed files with 212659 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ProjectCranked</artifactId>
<groupId>net.crankedpvp</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Collectors</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<artifactId>Utils</artifactId>
<groupId>net.crankedpvp</groupId>
</dependency>
<dependency>
<groupId>com.massivecraft</groupId>
<artifactId>Factions</artifactId>
</dependency>
<dependency>
<groupId>net.crankedpvp</groupId>
<artifactId>Spawners</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>net.astropvp</groupId>
<artifactId>FactionsKore</artifactId>
<version>0.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/../.lib/FactionsKore-1.3.431.jar</systemPath>
</dependency>
<dependency>
<groupId>net.crankedpvp</groupId>
<artifactId>StorageUtilsShaded</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar</systemPath>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,79 @@
package net.crankedpvp.collectors;
import lombok.Getter;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.collectors.commands.CollectorGiveCommand;
import net.crankedpvp.collectors.commands.ReloadCommand;
import net.crankedpvp.collectors.commands.RemoveCollectorCommand;
import net.crankedpvp.collectors.listeners.collectorlisteners.BlockBreakListener;
import net.crankedpvp.collectors.listeners.collectorlisteners.BlockPlaceListener;
import net.crankedpvp.collectors.listeners.collectorlisteners.PlayerInteractListener;
import net.crankedpvp.collectors.listeners.collectorlisteners.StackedMobDeathListener;
import net.crankedpvp.collectors.listeners.spawnerlisteners.SpawnerEvents;
import net.crankedpvp.collectors.tasks.CollectorWorthUpdateTask;
import net.crankedpvp.collectors.utils.SpawnerUtil;
import net.crankedpvp.collectors.utils.config.ConfigManager;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.Objects;
public class CollectorsPlugin extends JavaPlugin {
@Getter
private ConfigManager configManager;
@Getter
private SpawnerUtil spawnerUtil;
private final File collectorsFile = new File(this.getDataFolder(), "collectors.json");
public static CollectorsPlugin INSTANCE;
@Override
public void onEnable() {
INSTANCE = this;
this.configManager = new ConfigManager(this);
this.configManager.setupFiles();
this.spawnerUtil = new SpawnerUtil();
CollectorManager.DELEGATE.loadFromFile(collectorsFile);
this.registerCommands();
this.registerListeners();
new CollectorWorthUpdateTask().runTaskTimer(this, 0L, 100L);
Bukkit.getScheduler().runTaskLater(this, () -> {
for (Collector collector : CollectorManager.DELEGATE.collectors.values()) {
collector.clearSpawners();
collector.scanSpawners(Objects.requireNonNull(collector.getLocation()));
}
}, 140L);
Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, () -> CollectorManager.DELEGATE.saveToFile(collectorsFile),60L, 60*20);
}
@Override
public void onDisable() {
CollectorManager.DELEGATE.saveToFile(collectorsFile);
}
private void registerListeners() {
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new BlockPlaceListener(), this);
pm.registerEvents(new BlockBreakListener(this), this);
pm.registerEvents(new PlayerInteractListener(this), this);
//pm.registerEvents(new SpawnerBlockPlaceListener(), this);
//pm.registerEvents(new SpawnerBlockBreakListener(), this);
//pm.registerEvents(new SpawnerExplodeListener(), this);
pm.registerEvents(new StackedMobDeathListener(this), this);
pm.registerEvents(new SpawnerEvents(), this);
}
private void registerCommands() {
getCommand("c").setExecutor(new CollectorGiveCommand());
getCommand("removecollector").setExecutor(new RemoveCollectorCommand());
getCommand("collectorreload").setExecutor(new ReloadCommand());
}
}
@@ -0,0 +1,296 @@
package net.crankedpvp.collectors.collector;
import com.gmail.filoghost.holographicdisplays.api.Hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
import com.gmail.filoghost.holographicdisplays.api.line.TextLine;
import com.google.common.collect.ImmutableList;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import lombok.Getter;
import lombok.Setter;
import net.crankedpvp.collectors.CollectorsPlugin;
import net.crankedpvp.collectors.language.Language;
import net.crankedpvp.crankedutils.utils.CC;
import net.crankedpvp.crankedutils.utils.EconomyUtils;
import net.crankedpvp.crankedutils.utils.LocationUtils;
import net.crankedpvp.crankedutils.utils.NumberUtils;
import net.crankedpvp.spawners.SpawnerPlugin;
import net.crankedpvp.spawners.data.spawners.SpawnerData;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public final class Collector {
@Getter
@Setter
private long lastUpdated;
@Getter
private double worth;
@Getter
private long tnt;
@Getter
private final Map<EntityType, Integer> spawnersInChunk;
private final Reference<World> reference;
private final double x, y, z;
private final Queue<CollectorSellLog> sellLogs;
@Getter
private Hologram hologram;
public Collector(World world, JSONObject data) {
this.reference = new WeakReference<>(world);
Object potentialLocationArray = data.get("Location");
if (!(potentialLocationArray instanceof JSONArray)) {
throw new IllegalArgumentException();
}
JSONArray uncastedLocationArray = (JSONArray) potentialLocationArray;
this.x = Double.parseDouble(String.valueOf(uncastedLocationArray.get(0)));
this.y = Double.parseDouble(String.valueOf(uncastedLocationArray.get(1)));
this.z = Double.parseDouble(String.valueOf(uncastedLocationArray.get(2)));
this.sellLogs = new LinkedBlockingQueue<>(10);
this.lastUpdated = (long) data.get("lastUpdated");
this.spawnersInChunk = new HashMap<>();
Object potentialSpawnerArray = data.get("spawners");
if (!(potentialSpawnerArray instanceof JSONArray)) {
throw new IllegalArgumentException();
}
JSONArray uncastedSpawnerArray = (JSONArray) potentialSpawnerArray;
for (Object o : uncastedSpawnerArray) {
JSONObject jsonObject = ((JSONObject) o);
EntityType type = EntityType.valueOf(String.valueOf(jsonObject.get("type")));
int amount = Integer.parseInt(String.valueOf(jsonObject.get("amount")));
this.spawnersInChunk.put(type, amount);
}
this.worth = (double) data.get("worth");
this.tnt = (long) data.get("tnt");
Location holoLoc = this.getLocation().clone();
holoLoc.add(0.5, 2, 0.5);
this.hologram = HologramsAPI.createHologram(CollectorsPlugin.INSTANCE, holoLoc);
hologram.appendTextLine(CC.translate("&a&lChunk Collector"));
hologram.appendTextLine(CC.translate("&7TnT: &c" + NumberUtils.formatMoney(tnt)));
hologram.appendTextLine(CC.translate("&7Worth: &2$&a" + NumberUtils.formatMoney(getWorth())));
}
public Collector(Location location) {
this.reference = new WeakReference<>(location.getWorld());
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
this.sellLogs = new LinkedBlockingQueue<>(10);
this.lastUpdated = System.currentTimeMillis();
this.spawnersInChunk = new HashMap<>();
this.scanSpawners(location);
this.worth = 0.0;
this.tnt = 0L;
Location holoLoc = this.getLocation().clone();
holoLoc.add(0.5, 2, 0.5);
this.hologram = HologramsAPI.createHologram(CollectorsPlugin.INSTANCE, holoLoc);
hologram.appendTextLine(CC.translate("&b&lChunk Collector"));
hologram.appendTextLine(CC.translate("&7TnT: &c" + NumberUtils.formatMoney(tnt)));
hologram.appendTextLine(CC.translate("&7Worth: &2$&a" + NumberUtils.formatMoney(getWorth())));
}
public void scanSpawners(Location location) {
for (BlockState blockState : location.getChunk().getTileEntities()) {
if (blockState instanceof CreatureSpawner) {
if (SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(blockState.getLocation()) != null) {
SpawnerData data = SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(blockState.getLocation());
if (data.getEntityType() == EntityType.BLAZE) continue;
this.spawnersInChunk.put(data.getEntityType(), data.getSpawnerAmount());
}
}
}
}
public void sellWorth(Player player) {
if (this.worth <= 0) return;
player.playSound(player.getLocation(), Sound.ITEM_PICKUP, 5, 5);
EconomyUtils.depositBalance(player, worth);
Language.COLLECTOR_SELL.send(player, str -> str.replace("%price%", NumberUtils.formatNum((long) this.worth)));
this.worth = 0.0;
}
public void claimTNT(Player player) {
FPlayer fplayer = FPlayers.getInstance().getByPlayer(player);
Faction faction = fplayer.getFaction();
int amount = (int) this.tnt;
if (faction.isWilderness()) {
Language.NEED_FACTION.send(player);
return;
}
if (faction.getMaxTNT() <= faction.getTNTBank()) return;
if (faction.getMaxTNT() < faction.getTNTBank() + amount) {
amount = faction.getMaxTNT() - faction.getTNTBank();
faction.setTNTBank(faction.getTNTBank() + amount);
this.tnt = this.tnt - (amount / 2);
} else {
faction.setTNTBank(faction.getTNTBank() + amount);
this.tnt = 0;
}
int finalAmount = amount;
Language.COLLECTOR_TNT.send(player, str -> str.replace("%tnt%", NumberUtils.formatNum(finalAmount)));
addTNTSellLog(player, amount);
player.playSound(player.getLocation(), Sound.ITEM_PICKUP, 5, 5);
}
private double calculateWorth() {
long current = System.currentTimeMillis();
long secondsPassed = (current - this.getLastUpdated()) / 1000;
double total = 0;
for (Map.Entry<EntityType, Integer> entry : getSpawnersInChunk().entrySet()) {
EntityType type = entry.getKey();
int amountSpawners = entry.getValue();
total += CollectorsPlugin.INSTANCE.getSpawnerUtil().getMoneyPerSecond(type) * secondsPassed * amountSpawners;
}
return total;
}
private int calculateTnt() {
if (!this.getSpawnersInChunk().containsKey(EntityType.CREEPER)) return 0;
long current = System.currentTimeMillis();
long secondsPassed = (current - this.getLastUpdated()) / 1000;
double total = CollectorsPlugin.INSTANCE.getSpawnerUtil().getTntPerSecond() * secondsPassed * this.getSpawnersInChunk().get(EntityType.CREEPER);
return (int) total;
}
public void update() {
this.updateWorth();
this.updateTnt();
this.updateHologram();
this.setLastUpdated(System.currentTimeMillis());
}
public void deleteHologram() {
this.hologram.delete();
}
private void updateWorth() {
this.addWorth(this.calculateWorth());
}
private void updateTnt() {
this.addTnt(this.calculateTnt());
}
private void addWorth(double amount) {
this.worth += amount;
}
private void addTnt(double amount) {
this.tnt += amount;
}
public void addTNTSellLog(Player seller, int amount) {
boolean canOffer = this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.TNT, amount));
if (!canOffer) {
this.sellLogs.poll();
this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.TNT, amount));
}
}
public void addMobDropSellLog(Player seller, double worth) {
boolean canOffer = this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.MOB_DROPS, worth));
if (!canOffer) {
this.sellLogs.poll();
this.sellLogs.offer(new CollectorSellLog(seller.getName(), CollectorSellLog.SellLogType.MOB_DROPS, worth));
}
}
public void updateHologram() {
updateHologramLine(1, CC.translate("&7TnT: &c" + NumberUtils.formatMoney(tnt)));
updateHologramLine(2, CC.translate("&7Worth: &2$&a" + NumberUtils.formatMoney(getWorth())));
}
public List<CollectorSellLog> getSellLogs() {
return ImmutableList.copyOf(sellLogs);
}
public void clearSpawners() {
this.spawnersInChunk.clear();
}
public Location getLocation() {
World world = this.reference.get();
if (world == null) {
return null;
}
return new Location(world, x, y, z);
}
void invalidate() {
this.reference.clear();
}
@SuppressWarnings("unchecked")
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
JSONArray location = new JSONArray();
location.add(x);
location.add(y);
location.add(z);
jsonObject.put("Location", location);
JSONArray spawners = new JSONArray();
for (Map.Entry<EntityType, Integer> spawnerData : this.spawnersInChunk.entrySet()) {
JSONObject spawner = new JSONObject();
spawner.put("type", spawnerData.getKey().name());
spawner.put("amount", spawnerData.getValue());
spawners.add(spawner);
}
jsonObject.put("spawners", spawners);
jsonObject.put("lastUpdated", this.lastUpdated);
jsonObject.put("worth", this.worth);
jsonObject.put("tnt", this.tnt);
return jsonObject;
}
private void updateHologramLine(int line, String newText) {
if (this.hologram.size() == 0 || this.hologram == null) return;
if(this.hologram.isDeleted()) return;
final TextLine textLine = (TextLine)this.hologram.getLine(line);
if(textLine != null) {
textLine.setText(newText);
}
}
}
@@ -0,0 +1,142 @@
package net.crankedpvp.collectors.collector;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
public class CollectorManager {
public static final CollectorManager DELEGATE = new CollectorManager();
public final Map<String, Collector> collectors = new HashMap<>();
private final JSONParser jsonParser = new JSONParser();
private CollectorManager() {}
public void loadFromFile(File file) {
if (!file.exists()) {
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
} finally {
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.write("{}");
fileWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try (FileReader fileReader = new FileReader(file)) {
load((JSONObject)jsonParser.parse(fileReader));
} catch (IOException | ParseException | ClassCastException e) {
e.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
private void load(JSONObject object) {
for (Object obj : object.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
String key = String.valueOf(entry.getKey());
String[] components = key.split(";");
if (components.length != 3) {
continue;
}
World world = Bukkit.getWorld(components[0]);
if (world == null) {
continue;
}
Object value = entry.getValue();
if (!(value instanceof JSONObject)) {
continue;
}
collectors.put(key,new Collector(world, (JSONObject)value));
}
}
public void saveToFile(File file) {
if (!file.exists()) {
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.write(save().toJSONString());
fileWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
private JSONObject save() {
JSONObject jsonObject = new JSONObject();
collectors.forEach((key,collector) -> jsonObject.put(key,collector.toJsonObject()));
return jsonObject;
}
public boolean isCollectorContained(Chunk chunk) {
return collectors.get(chunkToString(chunk)) != null;
}
public boolean isCollectorContained(Location location) {
return collectors.get(chunkToString(location.getChunk())) != null;
}
private String chunkToString(Chunk chunk) {
char c = ';';
return chunk.getWorld().getName() +
c +
chunk.getX() +
c +
chunk.getZ();
}
public Collector getCollector(Chunk chunk) {
return collectors.get(chunkToString(chunk));
}
public Collector getCollector(Location location) {
return collectors.get(chunkToString(location.getChunk()));
}
public void removeCollector(Chunk chunk) {
collectors.remove(chunkToString(chunk)).invalidate();
}
public void removeCollector(Location location) {
collectors.remove(chunkToString(location.getChunk())).invalidate();
}
public Collector newCollector(Location location) {
Collector collector = new Collector(location);
collectors.put(chunkToString(location.getChunk()),collector);
return collector;
}
public void forEach(Consumer<Collector> action) {
for (Collector collector : collectors.values()) {
action.accept(collector);
}
}
}
@@ -0,0 +1,31 @@
package net.crankedpvp.collectors.collector;
import lombok.Getter;
@Getter
public class CollectorSellLog {
private final long sellDate;
private final String sellerName;
private final SellLogType sellLogType;
private final double worth;
public CollectorSellLog(String sellerName, SellLogType sellLogType) {
this.sellerName = sellerName;
this.sellLogType = sellLogType;
this.sellDate = System.currentTimeMillis();
this.worth = 0;
}
public CollectorSellLog(String sellerName, SellLogType sellLogType, double worth) {
this.sellerName = sellerName;
this.sellLogType = sellLogType;
this.sellDate = System.currentTimeMillis();
this.worth = worth;
}
public enum SellLogType {
TNT,
MOB_DROPS
}
}
@@ -0,0 +1,29 @@
package net.crankedpvp.collectors.collector;
import de.tr7zw.nbtapi.NBTItem;
import net.crankedpvp.crankedutils.utils.items.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class CollectorUtils {
private CollectorUtils() { }
public static ItemStack createCollector(int amount) {
ItemStack itemStack = new ItemBuilder(Material.BEACON, amount, (short) 0,
("&b&lChunk Collector"),
("&7This collector will automatically generate"),
("&7money in the same chunk as it's placed in"),("&7based on the spawners placed in this chunk."))
.colorize().build();
NBTItem nbtItem = new NBTItem(itemStack);
nbtItem.setString("crankedCustomItem", "chunkCollector");
return nbtItem.getItem();
}
public static boolean isCollector(ItemStack itemStack) {
if (itemStack == null || itemStack.getType() == Material.AIR) return false;
if (itemStack.getType() != Material.BEACON) return false;
NBTItem nbtItem = new NBTItem(itemStack);
if (!nbtItem.hasKey("crankedCustomItem")) return false;
return nbtItem.getString("crankedCustomItem").equalsIgnoreCase("chunkCollector");
}
}
@@ -0,0 +1,24 @@
package net.crankedpvp.collectors.commands;
import net.crankedpvp.collectors.collector.CollectorUtils;
import net.crankedpvp.collectors.language.Language;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CollectorGiveCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length != 2) {
Language.COLLECTOR_HELP.send(sender);
return true;
}
Player player = Bukkit.getPlayer(args[0]);
int amount = Integer.parseInt(args[1]);
player.getInventory().addItem(CollectorUtils.createCollector(amount));
return true;
}
}
@@ -0,0 +1,21 @@
package net.crankedpvp.collectors.commands;
import net.crankedpvp.collectors.CollectorsPlugin;
import net.crankedpvp.crankedutils.utils.CC;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class ReloadCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(!sender.hasPermission("*")) return true;
CollectorsPlugin.INSTANCE.getConfigManager().reloadFiles();
CollectorsPlugin.INSTANCE.getSpawnerUtil().reloadTntIncomeValue();
CollectorsPlugin.INSTANCE.getSpawnerUtil().reloadMobIncomeMap();
sender.sendMessage(CC.Green + "Reloaded config");
return true;
}
}
@@ -0,0 +1,50 @@
package net.crankedpvp.collectors.commands;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.perms.PermissibleAction;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.crankedutils.utils.CC;
import net.crankedpvp.crankedutils.utils.FactionUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class RemoveCollectorCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
if (!(commandSender instanceof Player)) return true;
Location location = ((Player)commandSender).getLocation();
Player player = ((Player) commandSender).getPlayer();
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
if (!CollectorManager.DELEGATE.isCollectorContained(location.getChunk())) {
player.sendMessage(CC.translate("&c&l(!)&c No collector could be found in this chunk."));
return true;
}
Location collectorLocation = CollectorManager.DELEGATE.getCollector(location).getLocation();
if (FactionUtils.getFaction(player) != FactionUtils.getFactionAt(collectorLocation) && !player.isOp()) {
player.sendMessage(CC.translate("&c&l(!)&c You need to be in the " + FactionUtils.getFactionAt(collectorLocation).getTag()) + " to remove this collector!");
return true;
}
boolean hasAccess = fPlayer.getFaction().hasAccess(fPlayer, PermissibleAction.COLLECTOR_ACCESS);
if (!hasAccess && !fPlayer.isAdminBypassing()) {
player.sendMessage(CC.translate("&c&l(!)&c You need a higher role in your faction to remove this collector."));
return true;
}
assert collectorLocation != null;
CollectorManager.DELEGATE.removeCollector(location);
collectorLocation.getBlock().setType(Material.AIR,true);
commandSender.sendMessage(CC.translate("&a&l(!)&a You have removed the chunk collector in this chunk. You may now place a new one!"));
return true;
}
}
@@ -0,0 +1,226 @@
package net.crankedpvp.collectors.inventories;
import com.golfing8.kore.FactionsKore;
import com.golfing8.kore.feature.OutpostFeature;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import dev.triumphteam.gui.builder.item.ItemBuilder;
import dev.triumphteam.gui.guis.Gui;
import dev.triumphteam.gui.guis.GuiItem;
import lombok.Getter;
import net.crankedpvp.collectors.CollectorsPlugin;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.collectors.collector.CollectorSellLog;
import net.crankedpvp.crankedutils.utils.CC;
import net.crankedpvp.crankedutils.utils.FactionUtils;
import net.crankedpvp.crankedutils.utils.NumberUtils;
import net.crankedpvp.crankedutils.utils.TimeUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class CollectorsUI {
@Getter
private final Gui collectorUI;
private final Collector collector;
public CollectorsUI(CollectorsPlugin plugin, Player player, Location location) {
CollectorManager collectorManager = CollectorManager.DELEGATE;
collector = collectorManager.getCollector(location);
FLocation fLocation = new FLocation(location);
Faction faction = Board.getInstance().getFactionAt(fLocation);
collectorUI = new Gui(5, ChatColor.DARK_GRAY + faction.getTag() + "'s Collector");
BukkitTask runnable = Bukkit.getScheduler().runTaskTimer(plugin, this::updateItems, 20L, 20L);
collectorUI.setCloseGuiAction(event -> runnable.cancel());
collectorUI.setDefaultClickAction(event -> event.setCancelled(true));
ItemStack glass = new net.crankedpvp.crankedutils.utils.items.ItemBuilder(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7)).setName("").build();
collectorUI.getFiller().fillBorder(new GuiItem(glass));
collectorUI.setItem(3,3, ItemBuilder
.from(Material.GOLD_NUGGET)
.setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Mob Drops")
.setLore(getMobDropsLore())
.asGuiItem(event -> {
if (collector.getWorth() == 0) return;
event.setCancelled(true);
collector.addMobDropSellLog(player, collector.getWorth());
collector.sellWorth(player);
updateItems();
}));
collectorUI.setItem(3,4, ItemBuilder
.from(Material.TNT)
.setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "TNT Drops")
.setLore(getTntLore())
.asGuiItem(event -> {
if (collector.getTnt() == 0) return;
event.setCancelled(true);
long amount = collector.getTnt();
if (amount == 0) return;
collector.claimTNT(player);
updateItems();
}));
collectorUI.setItem(3,6, ItemBuilder
.from(Material.PAPER)
.setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Sell Logs")
.setLore(getSellLogLore())
.asGuiItem(event -> event.setCancelled(true)));
collectorUI.setItem(3,7, ItemBuilder
.from(Material.MOB_SPAWNER)
.setName(ChatColor.GOLD + ChatColor.BOLD.toString() + "Active Spawners")
.setLore(getSpawnersLore())
.asGuiItem(event -> event.setCancelled(true)));
if (player.isOp()) {
collectorUI.setItem(5,9, ItemBuilder
.from(Material.HOPPER_MINECART)
.setName(ChatColor.GREEN + ChatColor.BOLD.toString() + CC.translate("Scan Spawners &8(&7Admin Only&8)"))
.setLore(
CC.translate(""),
CC.translate("&7Right-Click this item when having issues with"),
CC.translate("&7missing spawners in the collector,"),
CC.translate("&7this will rescan the chunk to find any missing spawners"),
CC.translate(""),
CC.translate("&c&l(!)&c This item only appears when an admin opens the GUI")
)
.asGuiItem(event -> {
event.setCancelled(true);
this.collector.clearSpawners();
this.collector.scanSpawners(this.collector.getLocation());
player.closeInventory();
}));
}
}
public void updateItems() {
collectorUI.updateItem(3, 3, ItemBuilder
.from(Material.GOLD_NUGGET)
.setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Mob Drops")
.setLore(CC.translate(getMobDropsLore()))
.asGuiItem().getItemStack());
collectorUI.updateItem(3,4, ItemBuilder
.from(Material.TNT)
.setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "TNT Drops")
.setLore(CC.translate(getTntLore()))
.asGuiItem().getItemStack());
collectorUI.updateItem(3,6, ItemBuilder
.from(Material.PAPER)
.setName(ChatColor.GREEN + ChatColor.BOLD.toString() + "Sell Logs")
.setLore(CC.translate(getSellLogLore()))
.asGuiItem().getItemStack());
collectorUI.update();
}
private List<String> getSpawnersLore() {
List<String> lore = new ArrayList<>();
double totalPerHour = 0;
boolean hasDemonicStronghold = FactionsKore.get().getFeature(OutpostFeature.class).getOutpost("demonic").getControllingID().equals(FactionUtils.getFactionAt(collector.getLocation()).getId());
lore.add(CC.translate("&e&lSpawners:"));
for (Map.Entry<EntityType, Integer> entry : collector.getSpawnersInChunk().entrySet()) {
EntityType type = entry.getKey();
int amount = entry.getValue();
if (type == EntityType.BLAZE) continue;
if (type == EntityType.CREEPER) {
lore.add(CC.translate("&e&l * &f" + amount + "x " + getEntityName(type) + " Spawners &8➥ &a" + NumberUtils.formatMoney(CollectorsPlugin.INSTANCE.getSpawnerUtil().getTnTPerHour() * amount) + " TnT/hour"));
} else {
double value = CollectorsPlugin.INSTANCE.getSpawnerUtil().getMoneyPerMinute(type);
if (hasDemonicStronghold) {
value *= 1.5;
}
lore.add(CC.translate("&e&l * &f" + amount + "x " + getEntityName(type) + " Spawners &8➥ &a$" + NumberUtils.formatMoney(value * 60 * amount) + "/hour"));
totalPerHour += value * amount * 60;
}
}
lore.add("");
lore.add(CC.translate("&e&lMultipliers:"));
if(hasDemonicStronghold) {
lore.add(CC.translate("&e&l * &fDemonic Stronghold&7 (1.5x Multiplier)"));
}
/*
if (hasFrozenStronghold) {
lore.add(CC.translate("&e&l * &fFrozen Stronghold&7 (1.25x Multiplier)"));
}
if (hasPlutoOutpost) {
lore.add(CC.translate("&e&l * &fPluto Outpost&7 (1.25x Multiplier)"));
}
*/
lore.add("");
lore.add(CC.translate("&e&lTotal: &a$" + NumberUtils.formatMoney(totalPerHour) + "/hour"));
lore.add("");
lore.add(CC.translate("&7The chunkcollector system allows spawners to"));
lore.add(CC.translate("&7activate while the chunk is unloaded."));
lore.add(CC.translate("&7The amount you make per hour increases depending"));
lore.add(CC.translate("&7on how many and which spawners you have placed."));
return lore;
}
private List<String> getSellLogLore() {
List<CollectorSellLog> sellLogs = collector.getSellLogs();
List<String> sellLogsLore = new ArrayList<>();
if (!sellLogs.isEmpty()) {
sellLogsLore.add("");
}
sellLogs.stream().limit(10).forEach(log -> {
String sellTypeString = log.getSellLogType() == CollectorSellLog.SellLogType.TNT ? "Deposited &c" + NumberUtils.formatNum((long) log.getWorth()) + "&7 TNT" : "Sold &a&2$&a" + NumberUtils.formatNum(log.getWorth()) + "&7 Worth of drops";
sellLogsLore.add(1, CC.translate("&7&o" + log.getSellerName() + "&r&7 " + sellTypeString + " &8(&7" + TimeUtils.formatSeconds((System.currentTimeMillis() - log.getSellDate()) / 1000) + "ago&8)"));
});
return sellLogsLore;
}
private List<String> getTntLore() {
return CC.translate(Arrays.asList("",
"&7Right-Click to deposit your TNT",
"&7into your faction TNT bank",
"",
"&a&l * Amount: &f" + NumberUtils.formatNum(collector.getTnt())
));
}
private List<String> getMobDropsLore() {
return CC.translate(Arrays.asList("",
"&7Right-Click to withdraw the money",
"&7to your own balance",
"",
"&a&l * Worth: &2$&f" + NumberUtils.formatNum(collector.getWorth())));
}
public static String getEntityName(EntityType type) {
if (type == EntityType.IRON_GOLEM) {
return "Iron Golem";
}
if (type == EntityType.MUSHROOM_COW) {
return "Mushroom Cow";
}
return type.getName();
}
}
@@ -0,0 +1,35 @@
package net.crankedpvp.collectors.language;
import net.crankedpvp.crankedutils.utils.CC;
import org.bukkit.command.CommandSender;
import java.util.function.UnaryOperator;
public enum Language {
NEED_FACTION("&c&l(!)&c You need a faction to do this."),
COLLECTOR_HELP("&7/collector &a<player> <amount>"),
COLLECTOR_SELL("&a&l+ $%price%"),
COLLECTOR_TNT("&c&l+ %tnt% TNT"),
PLACED_COLLECTOR("&a&l(!)&a Chunk collector placed, mob deaths will cause compatible mob drops to be automatically collected."),
CAN_NOT_PLACE_HERE("&c&l(!)&c You cannot place another collector in this chunk"),
CAN_NOT_PLACE_IN_WILD("&c&l(!)&c You cannot place a collector in wilderness")
;
private final String message;
Language(String message) {
this.message = message;
}
public String getMessage() {
return CC.translate(message);
}
public void send(CommandSender sender, UnaryOperator<String> function) {
sender.sendMessage(CC.translate(function.apply(message)));
}
public void send(CommandSender sender) {
sender.sendMessage(CC.translate(message));
}
}
@@ -0,0 +1,70 @@
package net.crankedpvp.collectors.listeners.collectorlisteners;
import net.crankedpvp.collectors.CollectorsPlugin;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.collectors.collector.CollectorUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.scheduler.BukkitRunnable;
public class BlockBreakListener implements Listener {
private final CollectorsPlugin plugin;
public BlockBreakListener(CollectorsPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onBreak(BlockBreakEvent event) {
if (event.isCancelled()) return;
removeCollector(event.getBlock());
}
@EventHandler
public void onExplode(BlockExplodeEvent event) {
if (event.isCancelled()) return;
for (Block block : event.blockList()) {
removeCollector(block);
}
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) return;
for (Block block : event.blockList()) {
removeCollector(block);
}
}
@EventHandler
public void onEntityExplode(BlockExplodeEvent event) {
if (event.isCancelled()) return;
for (Block block : event.blockList()) {
removeCollector(block);
}
}
private void removeCollector(Block block) {
if (block.getType() != Material.BEACON) return;
Location location = block.getLocation();
if (!CollectorManager.DELEGATE.isCollectorContained(location)) return;
Location collectorLocation = CollectorManager.DELEGATE.getCollector(location).getLocation();
assert collectorLocation != null;
CollectorManager.DELEGATE.getCollector(location).deleteHologram();
if (!collectorLocation.equals(location)) return;
CollectorManager.DELEGATE.removeCollector(location);
block.setType(Material.AIR,true);
new BukkitRunnable() {
@Override public void run() {
block.getWorld().dropItem(location, CollectorUtils.createCollector(1));
}
}.runTask(plugin);
}
}
@@ -0,0 +1,44 @@
package net.crankedpvp.collectors.listeners.collectorlisteners;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.collectors.collector.CollectorUtils;
import net.crankedpvp.collectors.language.Language;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
public class BlockPlaceListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onCollectorPlace(BlockPlaceEvent event) {
if (!CollectorUtils.isCollector(event.getItemInHand())) return;
if (event.isCancelled()) return;
Location location = event.getBlockPlaced().getLocation();
if (CollectorManager.DELEGATE.isCollectorContained(location)) {
Language.CAN_NOT_PLACE_HERE.send(event.getPlayer());
event.getPlayer().sendMessage(ChatColor.RED + "The collector is located at: " + CollectorManager.DELEGATE.getCollector(location.getChunk()).getLocation().getBlockX() + " "
+ CollectorManager.DELEGATE.getCollector(location.getChunk()).getLocation().getBlockY() + " " + CollectorManager.DELEGATE.getCollector(location.getChunk()).getLocation().getBlockZ());
event.getPlayer().sendMessage(ChatColor.RED + "You can remove this chunk collector by typing: /removecollector");
event.setCancelled(true);
return;
}
FLocation fLocation = new FLocation(location);
if (Board.getInstance().getFactionAt(fLocation).isWilderness() || Board.getInstance().getFactionAt(fLocation).isWarZone()) {
Language.CAN_NOT_PLACE_IN_WILD.send(event.getPlayer());
event.setCancelled(true);
return;
}
CollectorManager.DELEGATE.newCollector(location);
Language.PLACED_COLLECTOR.send(event.getPlayer());
}
}
@@ -0,0 +1,76 @@
package net.crankedpvp.collectors.listeners.collectorlisteners;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.perms.PermissibleAction;
import net.crankedpvp.collectors.CollectorsPlugin;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.collectors.inventories.CollectorsUI;
import net.crankedpvp.crankedutils.utils.CC;
import net.crankedpvp.crankedutils.utils.FactionUtils;
import net.crankedpvp.crankedutils.utils.NumberUtils;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class PlayerInteractListener implements Listener {
private final CollectorsPlugin plugin;
public PlayerInteractListener(CollectorsPlugin plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getClickedBlock() == null ||event.getClickedBlock().getType() == Material.AIR) return;
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
if (event.isCancelled()) return;
if (event.getClickedBlock().getType() == Material.BEACON) {
Player player = event.getPlayer();
Location location = event.getClickedBlock().getLocation();
if (!CollectorManager.DELEGATE.isCollectorContained(location)) return;
if (player.getGameMode().equals(GameMode.SPECTATOR)) return;
event.setCancelled(true);
Location collectorLocation = CollectorManager.DELEGATE.getCollector(location).getLocation();
assert collectorLocation != null;
if (!collectorLocation.equals(location)) return;
Collector collector = CollectorManager.DELEGATE.getCollector(event.getClickedBlock().getLocation());
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
if (FactionUtils.getFaction(event.getPlayer()) != FactionUtils.getFactionAt(collectorLocation) && !event.getPlayer().isOp()) {
event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You need to be in the " + FactionUtils.getFactionAt(collectorLocation).getTag()) + " to open this collector!");
return;
}
boolean hasAccess = fPlayer.getFaction().hasAccess(fPlayer, PermissibleAction.COLLECTOR_ACCESS);
if (!hasAccess) {
event.getPlayer().sendMessage(CC.translate("&c&l(!)&c You need a higher role in your faction to access this collector."));
return;
}
if (player.isSneaking()) {
if (collector.getWorth() == 0) return;
collector.addMobDropSellLog(player, collector.getWorth());
collector.sellWorth(player);
player.sendMessage(CC.translate("&a&l+ $" + NumberUtils.formatMoney(collector.getWorth())));
return;
}
CollectorsUI collectorUI = new CollectorsUI(plugin, player, location);
collectorUI.getCollectorUI().open(player);
}
}
}
@@ -0,0 +1,103 @@
package net.crankedpvp.collectors.listeners.collectorlisteners;
import net.crankedpvp.collectors.CollectorsPlugin;
import net.crankedpvp.spawners.events.StackedMobDeathEvent;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.SpawnerSpawnEvent;
public class StackedMobDeathListener implements Listener {
CollectorsPlugin plugin;
public StackedMobDeathListener(CollectorsPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onStackedEntityDeath(StackedMobDeathEvent e) {
/* Entity entity = e.getEntity();
if (!(entity instanceof LivingEntity)) return;
if (entity instanceof Blaze) return;
int stackSize = SpawnerPlugin.getInstance().getMobStackerUtils().getStackSize(entity);
if (!(e.getDamager() instanceof Player)) {
Location location = entity.getLocation();
if (!CollectorManager.DELEGATE.isCollectorContained(location)) return;
Collector collector = CollectorManager.DELEGATE.getCollector(location);
ItemStack itemStack = e.getDrops(entity.getType());
if (itemStack == null) return;
if (collector.getTotalMobDropAmount() + (stackSize*4) >= Integer.MAX_VALUE) return;
collector.incrementAmount(itemStack.getType(), stackSize);
SpawnerPlugin.getInstance().getMobStackerUtils().removeStackedMob(entity);
}
}
@EventHandler
public void onEntityDeath(EntityDeathEvent e) {
if (!(e.getEntity() instanceof Creature)) return;
if (e.getEntity().getWorld().getName().contains("end")) return;
StackedMobDeathEvent stackedMobDeathEvent = new StackedMobDeathEvent(e.getEntity(), null);
Bukkit.getPluginManager().callEvent(stackedMobDeathEvent);
e.getDrops().clear();
e.setDroppedExp(0);
*/
}
}
/*
public class StackedMobDeathListener implements Listener {
CollectorsPlugin plugin;
List<EntityType> noCollectorMobs;
public StackedMobDeathListener(CollectorsPlugin plugin) {
this.plugin = plugin;
noCollectorMobs = new ArrayList<>();
noCollectorMobs.add(EntityType.BLAZE);
}
@EventHandler
public void onStackedEntityDeath(StackedMobDeathEvent e) {
Entity entity = e.getEntity();
if (!(e.getDamager() instanceof Player)) {
Location location = entity.getLocation();
int amount = SpawnerPlugin.getInstance().getMobStackerUtils().getStackSize(entity);
if (!CollectorManager.DELEGATE.isCollectorContained(location)) return;
Collector collector = CollectorManager.DELEGATE.getCollector(location);
ItemStack itemStack = e.getDrops(entity.getType());
itemStack.setAmount(itemStack.getAmount()*4);
if (itemStack == null) return;
collector.incrementAmount(itemStack.getType(), amount * 200);
SpawnerPlugin.getInstance().getMobStackerUtils().removeStackedMob(entity);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onEntitySpawn(SpawnerSpawnEvent e) {
if (noCollectorMobs.contains(e.getEntityType())) {
return;
}
if (e.getEntity().hasMetadata("end_grinding_mob") || e.getEntity().hasMetadata("end_skeleton_mob") || e.getEntity().hasMetadata("end_creeper_mob")) {
return;
}
if (!(e.getEntity() instanceof Creature)) return;
//if (!SpawnerPlugin.getInstance().getMobStackerUtils().isStackedMob(e.getEntity())) return;
final StackedMobDeathEvent stackedMobDeathEvent = new StackedMobDeathEvent(e.getEntity(), null);
Bukkit.getPluginManager().callEvent(stackedMobDeathEvent);
e.setCancelled(true);
}
}
*/
@@ -0,0 +1,25 @@
package net.crankedpvp.collectors.listeners.spawnerlisteners;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.spawners.SpawnerPlugin;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
public class SpawnerBlockBreakListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void onBreak(BlockBreakEvent e) {
if (SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(e.getBlock().getLocation()) != null) {
if (CollectorManager.DELEGATE.isCollectorContained(e.getBlock().getLocation())) {
Collector collector = CollectorManager.DELEGATE.getCollector(e.getBlock().getLocation());
CreatureSpawner spawner = (CreatureSpawner) e.getBlock().getState();
EntityType type = spawner.getSpawnedType();
collector.getSpawnersInChunk().remove(type);
}
}
}
}
@@ -0,0 +1,42 @@
package net.crankedpvp.collectors.listeners.spawnerlisteners;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.crankedutils.utils.CC;
import net.crankedpvp.spawners.SpawnerPlugin;
import net.crankedpvp.spawners.items.ItemSpawner;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
public class SpawnerBlockPlaceListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void blockPlace(BlockPlaceEvent e) {
if (e.getBlock().getType() == Material.MOB_SPAWNER) {
if (SpawnerPlugin.coolDownSpawnerPlace.contains(e.getPlayer())) {
e.getPlayer().sendMessage(CC.translate("&c&l(!)&c Please be patient, you are still on spawner place cooldown."));
e.setCancelled(true);
return;
}
if (ItemSpawner.getSpawnerAmount(e.getItemInHand()) == -1) return;
int amount = ItemSpawner.getSpawnerAmount(e.getItemInHand());
EntityType type = ItemSpawner.getEntityTypeFromItem(e.getItemInHand());
if (type == EntityType.BLAZE) return;
if (CollectorManager.DELEGATE.isCollectorContained(e.getBlock().getLocation())) {
Collector collector = CollectorManager.DELEGATE.getCollector(e.getBlock().getLocation());
if (collector.getSpawnersInChunk().containsKey(type)) {
int oldAmount = collector.getSpawnersInChunk().get(type);
int newAmount = oldAmount+amount;
collector.getSpawnersInChunk().put(type, newAmount);
} else {
collector.getSpawnersInChunk().put(type, amount);
}
}
}
}
}
@@ -0,0 +1,29 @@
package net.crankedpvp.collectors.listeners.spawnerlisteners;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.spawners.events.SpawnerBreakEvent;
import net.crankedpvp.spawners.events.SpawnerPlaceEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class SpawnerEvents implements Listener {
@EventHandler
public void onSpawnerBreakEvent(SpawnerBreakEvent event) {
if (CollectorManager.DELEGATE.isCollectorContained(event.getLocation())) {
Collector collector = CollectorManager.DELEGATE.getCollector(event.getLocation());
collector.clearSpawners();
collector.scanSpawners(collector.getLocation());
}
}
@EventHandler
public void onSpawnerPlaceEvent(SpawnerPlaceEvent event) {
if (CollectorManager.DELEGATE.isCollectorContained(event.getLocation())) {
Collector collector = CollectorManager.DELEGATE.getCollector(event.getLocation());
collector.clearSpawners();
collector.scanSpawners(collector.getLocation());
}
}
}
@@ -0,0 +1,34 @@
package net.crankedpvp.collectors.listeners.spawnerlisteners;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import net.crankedpvp.spawners.SpawnerPlugin;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.util.List;
public class SpawnerExplodeListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void onBreak(EntityExplodeEvent e) {
List<Block> broken = e.blockList();
for (Block block : broken) {
if (block.getType() != Material.MOB_SPAWNER) continue;
if (SpawnerPlugin.getInstance().getSpawnerManager().getSpawnerData(block.getLocation()) != null) {
if (CollectorManager.DELEGATE.isCollectorContained(block.getLocation())) {
Collector collector = CollectorManager.DELEGATE.getCollector(block.getLocation());
CreatureSpawner spawner = (CreatureSpawner) block.getState();
EntityType type = spawner.getSpawnedType();
collector.getSpawnersInChunk().remove(type);
}
}
}
}
}
@@ -0,0 +1,19 @@
package net.crankedpvp.collectors.tasks;
import net.crankedpvp.collectors.collector.Collector;
import net.crankedpvp.collectors.collector.CollectorManager;
import org.bukkit.scheduler.BukkitRunnable;
public class CollectorWorthUpdateTask extends BukkitRunnable {
private final CollectorManager collectorManager;
public CollectorWorthUpdateTask() {
this.collectorManager = CollectorManager.DELEGATE;
}
@Override
public void run() {
this.collectorManager.forEach(Collector::update);
}
}
@@ -0,0 +1,16 @@
package net.crankedpvp.collectors.utils;
import org.bukkit.Location;
public class ChunkUtil {
public static boolean isLocationAInSameChunkAsLocationB(Location aLocation, Location bLocation) {
double aX = Math.floor(aLocation.getBlockX() / 16);
double aZ = Math.floor(aLocation.getBlockZ() / 16);
double bX = Math.floor(bLocation.getBlockX() / 16);
double bZ = Math.floor(bLocation.getBlockZ() / 16);
return aX == bX && aZ == bZ;
}
}
@@ -0,0 +1,65 @@
package net.crankedpvp.collectors.utils;
import net.crankedpvp.collectors.CollectorsPlugin;
import net.crankedpvp.collectors.utils.config.ConfigManager;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import java.util.EnumMap;
public class SpawnerUtil {
private final ConfigManager configManager;
private final EnumMap<EntityType, Integer> mobIncomeMap;
private int tntPerHour;
public SpawnerUtil() {
this.configManager = CollectorsPlugin.INSTANCE.getConfigManager();
this.mobIncomeMap = new EnumMap<>(EntityType.class);
this.reloadMobIncomeMap();
this.reloadTntIncomeValue();
}
public void reloadMobIncomeMap() {
this.mobIncomeMap.clear();
ConfigurationSection configurationSection = this.configManager.getConfig(ConfigManager.ConfigFile.SETTINGS).getConfigurationSection("spawner-income-per-minute");
for (String key : configurationSection.getKeys(false)) {
int value = configurationSection.getInt(key);
EntityType entityType = EntityType.valueOf(key);
mobIncomeMap.put(entityType, value);
}
}
public void reloadTntIncomeValue() {
this.tntPerHour = configManager.getConfig(ConfigManager.ConfigFile.SETTINGS).getInt("tnt-per-minute");
}
public double getMoneyPerMinute(EntityType type) {
try {
return this.mobIncomeMap.get(type);
} catch (Exception e) {
return 0;
}
}
public double getTnTPerHour() {
try {
return configManager.getConfig(ConfigManager.ConfigFile.SETTINGS).getInt("tnt-per-minute");
} catch (Exception e) {
return 0;
}
}
public double getMoneyPerSecond(EntityType type) {
return getMoneyPerMinute(type) / 60;
}
public double getTntPerMinute() {
return this.tntPerHour;
}
public double getTntPerSecond() {
return getTntPerMinute() / 60;
}
}
@@ -0,0 +1,108 @@
package net.crankedpvp.collectors.utils.config;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class AbstractConfig {
private final JavaPlugin plugin;
private final String path;
private FileConfiguration config;
private final File configFile;
public AbstractConfig(JavaPlugin plugin, String path) {
this.plugin = plugin;
this.path = path;
this.configFile = new File(plugin.getDataFolder(), path);
}
public boolean setupConfigFile() {
boolean copyDefaults = !configFile.exists();
this.saveDefaultConfig();
config = YamlConfiguration.loadConfiguration(configFile);
if (copyDefaults) this.copyDefaults();
boolean result = this.saveConfig();
if (result) this.loadConfigFromDisk();
return result;
}
public boolean saveConfig() {
try {
config.save(configFile);
return true;
} catch (IOException e) {
plugin.getLogger().severe("Could not save config file for " + path + "!");
e.printStackTrace();
}
return false;
}
public void saveDefaultConfig() {
if (!configFile.exists()) {
InputStream defConfig = plugin.getResource(path);
if (defConfig != null) {
plugin.saveResource(path,false);
} else {
try {
configFile.getParentFile().mkdirs();
configFile.createNewFile();
} catch (IOException e) {
plugin.getLogger().severe("Could not create config file for " + path + "!");
e.printStackTrace();
}
}
}
}
public boolean reloadConfig() {
boolean copyDefaults = !configFile.exists();
this.saveDefaultConfig();
config = YamlConfiguration.loadConfiguration(configFile);
if (copyDefaults) this.copyDefaults();
this.saveConfig();
return this.loadConfigFromDisk();
}
public boolean loadConfigFromDisk() {
try {
config.load(configFile);
return true;
} catch (IOException | InvalidConfigurationException e) {
plugin.getLogger().severe("Could not load config for " + path + "!");
e.printStackTrace();
}
return false;
}
public void copyDefaults() {
InputStream defConfig = plugin.getResource(path);
if (defConfig != null) {
config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig)));
}
config.options().copyDefaults(true);
}
public FileConfiguration getConfig() {
return config;
}
public String getPath() {
return path;
}
}
@@ -0,0 +1,51 @@
package net.crankedpvp.collectors.utils.config;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.Map;
public class ConfigManager {
@Getter
private final Map<ConfigFile, AbstractConfig> configs = new HashMap<>();
public ConfigManager(JavaPlugin plugin) {
for (ConfigFile configFile : ConfigFile.values()) {
AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName());
configs.put(configFile, abstractConfig);
}
}
public void setupFiles() {
configs.values().forEach(AbstractConfig::setupConfigFile);
}
public void reloadFiles() {
configs.values().forEach(AbstractConfig::reloadConfig);
}
public AbstractConfig getAbstractConfig(ConfigFile configFile) {
return configs.get(configFile);
}
public FileConfiguration getConfig(ConfigFile configFile) {
return getAbstractConfig(configFile).getConfig();
}
@Getter
@RequiredArgsConstructor
public enum ConfigFile {
SETTINGS("settings.yml"),
;
private final String fileName;
}
}
@@ -0,0 +1,7 @@
NEED_FACTION: "&c&l:(!)&c You need a faction to do this."
COLLECTOR_HELP: "&7/collector &a<player> <amount>"
COLLECTOR_SELL: "&a&l+ $%price%"
COLLECTOR_TNT: "&c&l+ %tnt% TNT"
PLACED_COLLECTOR: "&a&l(!)&a Chunk collector placed, mob deaths will cause compatible mob drops to be automatically collected."
CAN_NOT_PLACE_HERE: "&c&l(!)&c You cannot place another collector in this chunk"
CAN_NOT_PLACE_IN_WILD: "&c&l(!)&c You cannot place a collector in wilderness")
+20
View File
@@ -0,0 +1,20 @@
name: CrankedCollectors
main: net.crankedpvp.collectors.CollectorsPlugin
version: ${git.total.commit.count}.0
description: "§fCommit ID: §a${git.commit.id.abbrev}"
website: https://crankedpvp.net/
depend:
- CrankedUtils
- CrankedSpawners
- Factions
- FactionsKore
commands:
c:
aliases: [collector]
permission: cranked.admin
permission-message: Permission denied
removecollector:
aliases: [removechunkcollector]
collectorreload:
permission: cranked.admin
permission-message: Permission denied
@@ -0,0 +1,10 @@
spawner-income-per-minute:
IRON_GOLEM: 16000
VILLAGER: 50000
PIG_ZOMBIE: 1500
ZOMBIE: 383
SKELETON: 383
SPIDER: 316
CAVE_SPIDER: 316
CREEPER: 0
tnt-per-minute: 85