Fresh production baseline [skip ci]
This commit is contained in:
commit
0a11a18274
3 changed files with 229644 additions and 0 deletions
171
DuneNPC/src/main/java/com/example/dunenpc/DuneNPC.java
Normal file
171
DuneNPC/src/main/java/com/example/dunenpc/DuneNPC.java
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
package com.example.dunenpc;
|
||||
|
||||
import com.example.dunerealms.DuneCore;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.entity.*;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.inventory.*;
|
||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||
import org.bukkit.event.world.WorldLoadEvent;
|
||||
import org.bukkit.inventory.*;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
|
||||
public final class DuneNPC extends JavaPlugin implements Listener, CommandExecutor, TabCompleter {
|
||||
private DuneCore core;
|
||||
private Smugglers smugglers;
|
||||
private NamespacedKey guildKey;
|
||||
private static final Set<String> PLANETS = Set.of("arrakis", "caladan", "kaitain", "giedi_prime", "sigma_draconis_iv");
|
||||
private static final class Menu implements InventoryHolder {
|
||||
private Inventory inventory;
|
||||
@Override public Inventory getInventory() { return inventory; }
|
||||
}
|
||||
public DuneCore core() { return core; }
|
||||
|
||||
@Override public void onEnable() {
|
||||
core = (DuneCore) Bukkit.getPluginManager().getPlugin("DuneCore");
|
||||
boolean firstConfig = !new File(getDataFolder(), "config.yml").exists();
|
||||
saveDefaultConfig();
|
||||
try { migrateData(); }
|
||||
catch (IOException exception) {
|
||||
getLogger().severe("NPC data migration failed: " + exception.getMessage());
|
||||
Bukkit.getPluginManager().disablePlugin(this); return;
|
||||
}
|
||||
if (firstConfig) {
|
||||
var old = core.getConfig().getConfigurationSection("smugglers");
|
||||
if (old != null) for (String key : old.getKeys(false)) getConfig().set("smugglers." + key, old.get(key));
|
||||
var terrain = Bukkit.getPluginManager().getPlugin("DuneTerrain");
|
||||
if (terrain instanceof JavaPlugin javaPlugin)
|
||||
getConfig().set("guild-npc.enabled", javaPlugin.getConfig().getBoolean("guild-npc.enabled", true));
|
||||
saveConfig();
|
||||
}
|
||||
var registration = Bukkit.getServicesManager().getRegistration(Economy.class);
|
||||
if (registration == null) { getLogger().severe("Vault economy unavailable."); Bukkit.getPluginManager().disablePlugin(this); return; }
|
||||
guildKey = new NamespacedKey("dunerealms", "guild");
|
||||
smugglers = new Smugglers(this, registration.getProvider(), core.politics());
|
||||
Objects.requireNonNull(getCommand("dunenpc")).setExecutor(this);
|
||||
Objects.requireNonNull(getCommand("dunenpc")).setTabCompleter(this);
|
||||
Bukkit.getPluginManager().registerEvents(this, this);
|
||||
Bukkit.getScheduler().runTask(this, () -> Bukkit.getWorlds().forEach(this::ensureGuildNpc));
|
||||
}
|
||||
@Override public void onDisable() { if (smugglers != null) smugglers.shutdown(); }
|
||||
private void migrateData() throws IOException {
|
||||
for (String name : List.of("smuggling.yml", "smuggler-camps.yml")) {
|
||||
File source = new File(core.getDataFolder(), name), destination = new File(getDataFolder(), name);
|
||||
if (source.isFile() && !destination.exists()) {
|
||||
Files.copy(source.toPath(), destination.toPath());
|
||||
getLogger().info("Copied " + name + " from DuneCore; legacy file kept as backup.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@EventHandler public void worldLoaded(WorldLoadEvent event) {
|
||||
Bukkit.getScheduler().runTask(this, () -> ensureGuildNpc(event.getWorld()));
|
||||
}
|
||||
private void ensureGuildNpc(World world) {
|
||||
if (!PLANETS.contains(world.getName().toLowerCase(Locale.ROOT)) || !getConfig().getBoolean("guild-npc.enabled", true)) return;
|
||||
Location spawn = world.getSpawnLocation();
|
||||
world.getChunkAt(spawn).load();
|
||||
for (Entity entity : world.getNearbyEntities(spawn, 12, 8, 12))
|
||||
if (entity instanceof Villager && entity.getPersistentDataContainer().has(guildKey, PersistentDataType.BYTE)) return;
|
||||
int x = spawn.getBlockX() + 2, z = spawn.getBlockZ();
|
||||
for (int dx = -3; dx <= 3; dx++) for (int dz = -3; dz <= 3; dz++) {
|
||||
int bx = x + dx, bz = z + dz;
|
||||
int y = world.getHighestBlockYAt(bx, bz);
|
||||
Material ground = world.getBlockAt(bx, y, bz).getType();
|
||||
Location location = new Location(world, bx + .5, y + 1, bz + .5);
|
||||
if (y + 2 < world.getMaxHeight() && ground.isSolid() && ground != Material.CACTUS && ground != Material.MAGMA_BLOCK
|
||||
&& world.getBlockAt(bx, y + 1, bz).isPassable() && world.getBlockAt(bx, y + 2, bz).isPassable()
|
||||
&& !world.getBlockAt(bx, y + 1, bz).isLiquid() && world.getWorldBorder().isInside(location)) {
|
||||
spawnNavigator(location); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
private void spawnNavigator(Location location) {
|
||||
location.getWorld().spawn(location, Villager.class, villager -> {
|
||||
villager.setCustomName(ChatColor.LIGHT_PURPLE + "Vaerkring Navigator");
|
||||
villager.setCustomNameVisible(true); villager.setProfession(Villager.Profession.CLERIC);
|
||||
villager.setAI(false); villager.setInvulnerable(true); villager.setSilent(true); villager.setPersistent(true);
|
||||
villager.getPersistentDataContainer().set(guildKey, PersistentDataType.BYTE, (byte) 1);
|
||||
});
|
||||
}
|
||||
@EventHandler public void navigator(PlayerInteractEntityEvent event) {
|
||||
if (!(event.getRightClicked() instanceof Villager)
|
||||
|| !event.getRightClicked().getPersistentDataContainer().has(guildKey, PersistentDataType.BYTE)) return;
|
||||
event.setCancelled(true);
|
||||
if (event.getHand() == EquipmentSlot.HAND) Bukkit.dispatchCommand(event.getPlayer(), "duneess travel");
|
||||
}
|
||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (!(sender instanceof Player player)) { sender.sendMessage("Run this command in-game."); return true; }
|
||||
if (args.length > 0 && args[0].equalsIgnoreCase("smuggle")) { smugglers.command(player, args); return true; }
|
||||
if (args.length > 0 && args[0].equalsIgnoreCase("guildnpc")) {
|
||||
if (!player.hasPermission("dune.admin")) { player.sendMessage("Admin only."); return true; }
|
||||
spawnNavigator(player.getLocation()); player.sendMessage("Vaerkring Routekeeper placed."); return true;
|
||||
}
|
||||
if (!player.isOp()) { player.sendMessage(ChatColor.RED + "Operators only. Right-click an Arrakis Smuggler for missions."); return true; }
|
||||
if (args.length == 0 || args[0].equalsIgnoreCase("admin")) { openAdmin(player); return true; }
|
||||
if (args[0].equalsIgnoreCase("smuggler")) {
|
||||
if (!getConfig().getBoolean("smugglers.enabled", true)) { player.sendMessage("Smugglers are disabled in DuneNPC/config.yml."); return true; }
|
||||
if (!player.getWorld().getName().equalsIgnoreCase("arrakis")) { player.sendMessage("Spawn smugglers on Arrakis."); return true; }
|
||||
smugglers.spawnAt(player.getLocation()); player.sendMessage("Arrakis Smuggler placed."); return true;
|
||||
}
|
||||
if (args[0].equalsIgnoreCase("status")) { status(player); return true; }
|
||||
player.sendMessage("/dunenpc admin | guildnpc | smuggler | status | smuggle status | smuggle cancel"); return true;
|
||||
}
|
||||
private void status(Player player) {
|
||||
int guild = 0, traders = 0;
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
for (Villager villager : world.getEntitiesByClass(Villager.class))
|
||||
if (villager.getPersistentDataContainer().has(guildKey, PersistentDataType.BYTE)) guild++;
|
||||
for (WanderingTrader trader : world.getEntitiesByClass(WanderingTrader.class))
|
||||
if (trader.getPersistentDataContainer().has(new NamespacedKey("dunecore", "smuggler"), PersistentDataType.BYTE)) traders++;
|
||||
}
|
||||
player.sendMessage(ChatColor.GOLD + "DuneNPC: " + guild + " loaded Vaerkring Routekeepers, " + traders + " loaded smugglers, " + smugglers.activeCount() + " open contracts.");
|
||||
}
|
||||
void openAdmin(Player player) {
|
||||
if (!player.isOp()) { player.sendMessage(ChatColor.RED + "Operators only."); return; }
|
||||
Menu menu = new Menu();
|
||||
menu.inventory = Bukkit.createInventory(menu, 27, ChatColor.GOLD + "DuneNPC | NPC Administration");
|
||||
for (int slot = 0; slot < 27; slot++) menu.inventory.setItem(slot, icon(Material.BLACK_STAINED_GLASS_PANE, " "));
|
||||
menu.inventory.setItem(10, icon(Material.VILLAGER_SPAWN_EGG, "Place Vaerkring Routekeeper", "Spawn at your position; opens Vaerkring travel."));
|
||||
menu.inventory.setItem(12, icon(Material.WANDERING_TRADER_SPAWN_EGG, "Place Arrakis Smuggler", "Spawn at your position on Arrakis."));
|
||||
menu.inventory.setItem(14, icon(Material.WRITABLE_BOOK, "NPC and Mission Status", "Show loaded NPC counts and active contracts."));
|
||||
menu.inventory.setItem(16, icon(Material.CLOCK, "Quest Camp Guide", "Green: free to roam. Purple: active mission.", "Active contacts are stationary and lit.", "Missions expire after 30 real minutes."));
|
||||
menu.inventory.setItem(22, icon(Material.BLAZE_ROD, "Back to Dune Admin"));
|
||||
player.openInventory(menu.inventory);
|
||||
}
|
||||
private ItemStack icon(Material material, String name, String... lore) {
|
||||
ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(ChatColor.GOLD + name);
|
||||
meta.setLore(Arrays.stream(lore).map(line -> ChatColor.GRAY + line).toList());
|
||||
item.setItemMeta(meta); return item;
|
||||
}
|
||||
@EventHandler public void click(InventoryClickEvent event) {
|
||||
if (!(event.getView().getTopInventory().getHolder() instanceof Menu)) return;
|
||||
event.setCancelled(true);
|
||||
if (!(event.getWhoClicked() instanceof Player player) || event.getClickedInventory() != event.getView().getTopInventory()) return;
|
||||
String action = switch (event.getRawSlot()) { case 10 -> "guildnpc"; case 12 -> "smuggler"; case 14 -> "status"; case 22 -> "back"; default -> ""; };
|
||||
if (action.isEmpty()) return;
|
||||
Bukkit.getScheduler().runTask(this, () -> {
|
||||
if (!player.isOnline()) return;
|
||||
player.closeInventory(); if (!player.isOp()) return;
|
||||
Bukkit.dispatchCommand(player, action.equals("back") ? "dune admin" : "dunenpc " + action);
|
||||
});
|
||||
}
|
||||
@EventHandler public void drag(InventoryDragEvent event) {
|
||||
if (event.getView().getTopInventory().getHolder() instanceof Menu) event.setCancelled(true);
|
||||
}
|
||||
@Override public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length == 1) return (sender.isOp() ? List.of("admin", "guildnpc", "smuggler", "status", "smuggle") : List.of("smuggle"))
|
||||
.stream().filter(item -> item.startsWith(args[0].toLowerCase(Locale.ROOT))).toList();
|
||||
if (args.length == 2 && args[0].equalsIgnoreCase("smuggle")) return List.of("status", "cancel").stream()
|
||||
.filter(item -> item.startsWith(args[1].toLowerCase(Locale.ROOT))).toList();
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
146
DuneNPC/src/main/java/com/example/dunenpc/SmugglerCamps.java
Normal file
146
DuneNPC/src/main/java/com/example/dunenpc/SmugglerCamps.java
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
package com.example.dunenpc;
|
||||
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.type.Light;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.*;
|
||||
import org.bukkit.util.Vector;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/** Journals temporary camp lighting before changing blocks; never overwrites terrain. */
|
||||
final class SmugglerCamps {
|
||||
private final DuneNPC plugin;
|
||||
private final File file;
|
||||
private final YamlConfiguration journal;
|
||||
private final Map<UUID, Camp> camps = new HashMap<>();
|
||||
private final Map<String, Lamp> lamps = new HashMap<>();
|
||||
private boolean pendingSave;
|
||||
private record Camp(UUID world, boolean ai, boolean gravity, boolean collidable,
|
||||
boolean invulnerable, int despawn) {}
|
||||
private record Lamp(UUID world, int x, int y, int z, String original, Set<UUID> owners) {}
|
||||
|
||||
SmugglerCamps(DuneNPC plugin) {
|
||||
this.plugin = plugin;
|
||||
file = new File(plugin.getDataFolder(), "smuggler-camps.yml");
|
||||
journal = YamlConfiguration.loadConfiguration(file);
|
||||
var section = journal.getConfigurationSection("camps");
|
||||
if (section != null) for (String key : section.getKeys(false)) try {
|
||||
String path = "camps." + key + ".";
|
||||
camps.put(UUID.fromString(key), new Camp(UUID.fromString(journal.getString(path + "world", "")),
|
||||
journal.getBoolean(path + "ai"), journal.getBoolean(path + "gravity"),
|
||||
journal.getBoolean(path + "collidable"), journal.getBoolean(path + "invulnerable"),
|
||||
journal.getInt(path + "despawn", 48000)));
|
||||
} catch (IllegalArgumentException ignored) { }
|
||||
section = journal.getConfigurationSection("lamps");
|
||||
if (section != null) for (String key : section.getKeys(false)) try {
|
||||
String path = "lamps." + key + ".";
|
||||
Set<UUID> owners = new HashSet<>();
|
||||
for (String owner : journal.getStringList(path + "owners")) owners.add(UUID.fromString(owner));
|
||||
lamps.put(key, new Lamp(UUID.fromString(journal.getString(path + "world", "")),
|
||||
journal.getInt(path + "x"), journal.getInt(path + "y"), journal.getInt(path + "z"),
|
||||
journal.getString(path + "original", "minecraft:air"), owners));
|
||||
} catch (IllegalArgumentException ignored) { }
|
||||
}
|
||||
|
||||
void sync(Set<UUID> active) {
|
||||
boolean changed = false;
|
||||
for (UUID id : active) {
|
||||
Entity entity = Bukkit.getEntity(id);
|
||||
if (!(entity instanceof WanderingTrader trader)) continue;
|
||||
if (!camps.containsKey(id)) {
|
||||
camps.put(id, new Camp(trader.getWorld().getUID(), trader.hasAI(), trader.hasGravity(),
|
||||
trader.isCollidable(), trader.isInvulnerable(), trader.getDespawnDelay()));
|
||||
planLights(id, trader.getLocation());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
// Save the restoration journal before applying any new lighting or entity changes.
|
||||
if (changed) pendingSave = true;
|
||||
if (pendingSave && !save()) return;
|
||||
for (UUID id : active) {
|
||||
if (!camps.containsKey(id)) continue;
|
||||
Entity entity = Bukkit.getEntity(id);
|
||||
if (entity instanceof WanderingTrader trader) {
|
||||
trader.setAI(false);
|
||||
trader.setGravity(false);
|
||||
trader.setCollidable(false);
|
||||
trader.setInvulnerable(true);
|
||||
trader.setVelocity(new Vector());
|
||||
trader.setDespawnDelay(Integer.MAX_VALUE);
|
||||
}
|
||||
}
|
||||
for (var iterator = camps.entrySet().iterator(); iterator.hasNext();) {
|
||||
var entry = iterator.next();
|
||||
if (active.contains(entry.getKey())) continue;
|
||||
Entity entity = Bukkit.getEntity(entry.getKey());
|
||||
if (entity instanceof WanderingTrader trader) {
|
||||
Camp camp = entry.getValue();
|
||||
trader.setAI(camp.ai()); trader.setGravity(camp.gravity()); trader.setCollidable(camp.collidable());
|
||||
trader.setInvulnerable(camp.invulnerable()); trader.setDespawnDelay(camp.despawn());
|
||||
iterator.remove(); changed = true;
|
||||
}
|
||||
// Keep unloaded trader records until its chunk is loaded, so AI can be restored then.
|
||||
}
|
||||
for (var iterator = lamps.entrySet().iterator(); iterator.hasNext();) {
|
||||
Lamp lamp = iterator.next().getValue();
|
||||
World world = Bukkit.getWorld(lamp.world());
|
||||
if (world == null || !world.isChunkLoaded(lamp.x() >> 4, lamp.z() >> 4)) continue;
|
||||
Block block = world.getBlockAt(lamp.x(), lamp.y(), lamp.z());
|
||||
boolean inUse = lamp.owners().stream().anyMatch(active::contains);
|
||||
if (inUse) {
|
||||
if (block.isEmpty()) {
|
||||
Light light = (Light) Bukkit.createBlockData(Material.LIGHT);
|
||||
light.setLevel(15);
|
||||
block.setBlockData(light, true);
|
||||
}
|
||||
} else {
|
||||
if (isCampLight(block.getBlockData())) block.setBlockData(Bukkit.createBlockData(lamp.original()), true);
|
||||
// If another system/player changed the block, keep that new block intact.
|
||||
iterator.remove(); changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) { pendingSave = true; save(); }
|
||||
}
|
||||
|
||||
static boolean isCampLight(org.bukkit.block.data.BlockData data) {
|
||||
return data instanceof Light light && light.getLevel() == 15 && !light.isWaterlogged();
|
||||
}
|
||||
|
||||
private void planLights(UUID owner, Location location) {
|
||||
World world = location.getWorld();
|
||||
int y = location.getBlockY() + 2;
|
||||
if (y >= world.getMaxHeight()) return;
|
||||
int[][] offsets = {{0, 0}, {-4, -4}, {-4, 4}, {4, -4}, {4, 4}};
|
||||
for (int[] offset : offsets) {
|
||||
int x = location.getBlockX() + offset[0], z = location.getBlockZ() + offset[1];
|
||||
if (!world.isChunkLoaded(x >> 4, z >> 4)) continue;
|
||||
Block block = world.getBlockAt(x, y, z);
|
||||
String key = world.getUID() + "_" + x + "_" + y + "_" + z;
|
||||
Lamp existing = lamps.get(key);
|
||||
if (existing != null) existing.owners().add(owner);
|
||||
else if (block.isEmpty()) lamps.put(key, new Lamp(world.getUID(), x, y, z,
|
||||
block.getBlockData().getAsString(), new HashSet<>(Set.of(owner))));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean save() {
|
||||
journal.set("camps", null); journal.set("lamps", null);
|
||||
camps.forEach((id, camp) -> {
|
||||
String path = "camps." + id + ".";
|
||||
journal.set(path + "world", camp.world().toString()); journal.set(path + "ai", camp.ai());
|
||||
journal.set(path + "gravity", camp.gravity()); journal.set(path + "collidable", camp.collidable());
|
||||
journal.set(path + "invulnerable", camp.invulnerable()); journal.set(path + "despawn", camp.despawn());
|
||||
});
|
||||
lamps.forEach((id, lamp) -> {
|
||||
String path = "lamps." + id + ".";
|
||||
journal.set(path + "world", lamp.world().toString()); journal.set(path + "x", lamp.x());
|
||||
journal.set(path + "y", lamp.y()); journal.set(path + "z", lamp.z()); journal.set(path + "original", lamp.original());
|
||||
journal.set(path + "owners", lamp.owners().stream().map(UUID::toString).toList());
|
||||
});
|
||||
try { journal.save(file); pendingSave = false; return true; }
|
||||
catch (IOException exception) { plugin.getLogger().severe("Cannot save smuggler camp restoration journal: " + exception.getMessage()); return false; }
|
||||
}
|
||||
}
|
||||
339
DuneNPC/src/main/java/com/example/dunenpc/Smugglers.java
Normal file
339
DuneNPC/src/main/java/com/example/dunenpc/Smugglers.java
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
package com.example.dunenpc;
|
||||
|
||||
import com.example.dunerealms.Politics;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.*;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.entity.CreatureSpawnEvent;
|
||||
import org.bukkit.event.entity.EntityTeleportEvent;
|
||||
import org.bukkit.event.inventory.*;
|
||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||
import org.bukkit.inventory.*;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/** Local Arrakis delivery contracts; cargo is the existing tagged trade items. */
|
||||
final class Smugglers implements Listener {
|
||||
private final DuneNPC plugin;
|
||||
private final Economy economy;
|
||||
private final Politics politics;
|
||||
private final NamespacedKey traderKey, spiceKey, waterKey;
|
||||
private final File file;
|
||||
private final YamlConfiguration data;
|
||||
private final Map<UUID, Contract> contracts = new HashMap<>();
|
||||
private final Random random = new Random();
|
||||
private final SmugglerCamps camps;
|
||||
static final long MISSION_MILLIS = 30 * 60 * 1000L;
|
||||
record Contract(String commodity, int amount, int reward, UUID source, double x, double z, long expiresAt) {
|
||||
Contract(String commodity, int amount, int reward, UUID source, double x, double z) {
|
||||
this(commodity, amount, reward, source, x, z, System.currentTimeMillis() + MISSION_MILLIS);
|
||||
}
|
||||
boolean expired(long now) { return now >= expiresAt; }
|
||||
}
|
||||
private static final class Menu implements InventoryHolder {
|
||||
private Inventory inventory;
|
||||
private final UUID trader;
|
||||
Menu(UUID trader) { this.trader = trader; }
|
||||
@Override public Inventory getInventory() { return inventory; }
|
||||
}
|
||||
|
||||
Smugglers(DuneNPC plugin, Economy economy, Politics politics) {
|
||||
this.plugin = plugin; this.economy = economy; this.politics = politics;
|
||||
traderKey = new NamespacedKey("dunecore", "smuggler");
|
||||
spiceKey = new NamespacedKey("dunerealms", "item");
|
||||
waterKey = new NamespacedKey("dunerealms", "finite_arrakis_water");
|
||||
file = new File(plugin.getDataFolder(), "smuggling.yml");
|
||||
data = YamlConfiguration.loadConfiguration(file);
|
||||
boolean migrated = false;
|
||||
for (String key : data.getKeys(false)) try {
|
||||
String commodity = data.getString(key + ".commodity", "");
|
||||
int amount = data.getInt(key + ".amount"), reward = data.getInt(key + ".reward");
|
||||
if (!Set.of("spice", "water").contains(commodity) || amount < 1 || reward < 1) continue;
|
||||
contracts.put(UUID.fromString(key), new Contract(commodity, amount, reward,
|
||||
UUID.fromString(data.getString(key + ".source", "")), data.getDouble(key + ".x"), data.getDouble(key + ".z"),
|
||||
data.getLong(key + ".expires-at", System.currentTimeMillis() + MISSION_MILLIS)));
|
||||
if (!data.contains(key + ".expires-at")) migrated = true;
|
||||
} catch (IllegalArgumentException ignored) { }
|
||||
if (migrated) save();
|
||||
camps = new SmugglerCamps(plugin);
|
||||
Bukkit.getPluginManager().registerEvents(this, plugin);
|
||||
Bukkit.getScheduler().runTaskTimer(plugin, this::populate, 100L, 1200L);
|
||||
Bukkit.getScheduler().runTaskTimer(plugin, this::updateCamps, 1L, 20L);
|
||||
}
|
||||
private Set<UUID> activeSources() {
|
||||
Set<UUID> ids = new HashSet<>();
|
||||
for (Contract contract : contracts.values()) ids.add(contract.source());
|
||||
return ids;
|
||||
}
|
||||
private void updateCamps() {
|
||||
expireContracts();
|
||||
Set<UUID> active = plugin.getConfig().getBoolean("smugglers.enabled", true) ? activeSources() : Set.of();
|
||||
camps.sync(active);
|
||||
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
|
||||
World world = Bukkit.getWorld("arrakis");
|
||||
if (world == null) return;
|
||||
for (WanderingTrader trader : world.getEntitiesByClass(WanderingTrader.class)) if (tagged(trader)) {
|
||||
Color color = active.contains(trader.getUniqueId()) ? Color.fromRGB(170, 60, 230) : Color.fromRGB(50, 220, 80);
|
||||
world.spawnParticle(Particle.DUST, trader.getLocation().add(0, 2.1, 0), 8, .35, .25, .35, 0,
|
||||
new Particle.DustOptions(color, 1.2f));
|
||||
}
|
||||
}
|
||||
private void expireContracts() {
|
||||
long now = System.currentTimeMillis();
|
||||
Map<UUID, Contract> expired = new HashMap<>();
|
||||
contracts.forEach((id, contract) -> { if (contract.expired(now)) expired.put(id, contract); });
|
||||
if (expired.isEmpty()) return;
|
||||
expired.keySet().forEach(contracts::remove);
|
||||
if (!save()) { contracts.putAll(expired); return; }
|
||||
for (UUID id : expired.keySet()) {
|
||||
Player player = Bukkit.getPlayer(id);
|
||||
if (player != null) player.sendMessage(ChatColor.GOLD + "Smuggler: 'The patrols have changed. Your 30-minute window is gone.' Mission expired; cargo kept, no reward.");
|
||||
}
|
||||
}
|
||||
private String timeLeft(Contract contract) {
|
||||
long seconds = Math.max(0, (contract.expiresAt() - System.currentTimeMillis() + 999) / 1000);
|
||||
return "Time left: " + seconds / 60 + "m " + seconds % 60 + "s (real time, including offline).";
|
||||
}
|
||||
void shutdown() { camps.sync(Set.of()); }
|
||||
@EventHandler public void teleport(EntityTeleportEvent event) {
|
||||
if (activeSources().contains(event.getEntity().getUniqueId())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
private boolean sanctioned(Player player) {
|
||||
String house = plugin.core().factionOf(player);
|
||||
return politics.isAuthorizedSpice(house) || politics.isAuthorizedWater(house);
|
||||
}
|
||||
int activeCount() { expireContracts(); return contracts.size(); }
|
||||
void spawnAt(Location location) {
|
||||
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
|
||||
location.getWorld().spawn(location, WanderingTrader.class, this::mark);
|
||||
}
|
||||
private boolean tagged(Entity entity) {
|
||||
return entity instanceof WanderingTrader && entity.getPersistentDataContainer().has(traderKey, PersistentDataType.BYTE);
|
||||
}
|
||||
private void mark(WanderingTrader trader) {
|
||||
trader.getPersistentDataContainer().set(traderKey, PersistentDataType.BYTE, (byte) 1);
|
||||
trader.setCustomName(ChatColor.GOLD + "Arrakis Smuggler");
|
||||
trader.setCustomNameVisible(true);
|
||||
trader.setRecipes(List.of());
|
||||
trader.setAI(true);
|
||||
trader.setCanDrinkPotion(false);
|
||||
trader.setDespawnDelay(48000);
|
||||
}
|
||||
@EventHandler(ignoreCancelled = true) public void spawn(CreatureSpawnEvent event) {
|
||||
if (plugin.getConfig().getBoolean("smugglers.enabled", true)
|
||||
&& event.getLocation().getWorld().getName().equalsIgnoreCase("arrakis")
|
||||
&& event.getEntity() instanceof WanderingTrader trader) mark(trader);
|
||||
}
|
||||
private void populate() {
|
||||
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
|
||||
World world = Bukkit.getWorld("arrakis");
|
||||
if (world == null || world.getPlayers().isEmpty()) return;
|
||||
int count = 0;
|
||||
for (WanderingTrader trader : world.getEntitiesByClass(WanderingTrader.class)) {
|
||||
if (!tagged(trader)) mark(trader);
|
||||
roam(trader);
|
||||
count++;
|
||||
}
|
||||
int maximum = Math.max(2, Math.min(20, plugin.getConfig().getInt("smugglers.max-traders", 6)));
|
||||
// At most two new traders per minute, only in already-loaded chunks near players.
|
||||
for (int attempt = 0, added = 0; attempt < 20 && count < maximum && added < 2; attempt++) {
|
||||
Player player = world.getPlayers().get(random.nextInt(world.getPlayers().size()));
|
||||
double angle = random.nextDouble() * Math.PI * 2;
|
||||
int radius = 24 + random.nextInt(25);
|
||||
int x = player.getLocation().getBlockX() + (int) (Math.cos(angle) * radius);
|
||||
int z = player.getLocation().getBlockZ() + (int) (Math.sin(angle) * radius);
|
||||
if (!world.isChunkLoaded(x >> 4, z >> 4)) continue;
|
||||
int y = world.getHighestBlockYAt(x, z);
|
||||
Location location = new Location(world, x + .5, y + 1, z + .5);
|
||||
if (y + 2 >= world.getMaxHeight() || !world.getBlockAt(x, y, z).getType().isSolid()
|
||||
|| !world.getBlockAt(x, y + 1, z).isPassable() || !world.getBlockAt(x, y + 2, z).isPassable()
|
||||
|| !world.getWorldBorder().isInside(location)) continue;
|
||||
WanderingTrader trader = world.spawn(location, WanderingTrader.class, this::mark);
|
||||
roam(trader);
|
||||
if (trader.isValid()) { count++; added++; }
|
||||
}
|
||||
}
|
||||
private void roam(WanderingTrader trader) {
|
||||
if (activeSources().contains(trader.getUniqueId())) return;
|
||||
Location here = trader.getLocation();
|
||||
int x = here.getBlockX() + random.nextInt(49) - 24;
|
||||
int z = here.getBlockZ() + random.nextInt(49) - 24;
|
||||
World world = trader.getWorld();
|
||||
if (!world.isChunkLoaded(x >> 4, z >> 4)) return;
|
||||
int y = world.getHighestBlockYAt(x, z);
|
||||
Location destination = new Location(world, x + .5, y + 1, z + .5);
|
||||
if (y + 2 < world.getMaxHeight() && world.getBlockAt(x, y, z).getType().isSolid()
|
||||
&& world.getBlockAt(x, y + 1, z).isPassable() && world.getWorldBorder().isInside(destination))
|
||||
trader.setWanderingTowards(destination);
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled = true) public void interact(PlayerInteractEntityEvent event) {
|
||||
if (!tagged(event.getRightClicked())) return;
|
||||
event.setCancelled(true);
|
||||
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
|
||||
if (event.getHand() != EquipmentSlot.HAND) return;
|
||||
Player player = event.getPlayer();
|
||||
if (sanctioned(player)) {
|
||||
player.sendMessage(ChatColor.GOLD + "Smuggler: 'The Emperor's seal is on your house. I won't risk my routes for an Imperial agent. Sell through your charter: /duneess sell pays +33% before the Trust levy.'");
|
||||
return;
|
||||
}
|
||||
open(player, event.getRightClicked());
|
||||
}
|
||||
private ItemStack icon(Material type, String title, String... lines) {
|
||||
ItemStack item = new ItemStack(type);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(ChatColor.GOLD + title);
|
||||
meta.setLore(Arrays.stream(lines).map(line -> ChatColor.GRAY + line).toList());
|
||||
item.setItemMeta(meta); return item;
|
||||
}
|
||||
private void open(Player player, Entity trader) {
|
||||
Menu holder = new Menu(trader.getUniqueId());
|
||||
holder.inventory = Bukkit.createInventory(holder, 27, ChatColor.GOLD + "Arrakis | Smuggler Contracts");
|
||||
for (int i = 0; i < 27; i++) holder.inventory.setItem(i, icon(Material.BROWN_STAINED_GLASS_PANE, " "));
|
||||
Contract active = contracts.get(player.getUniqueId());
|
||||
if (active == null) {
|
||||
Contract spice = offer("spice", trader), water = offer("water", trader);
|
||||
holder.inventory.setItem(11, icon(Material.ORANGE_DYE, "The Unmarked Spice Run",
|
||||
"'Imperial patrols count every grain of melange.'",
|
||||
"'Our hidden buyers need a shipment without a seal.'",
|
||||
"Deliver " + spice.amount() + " tagged spice to another smuggler.", "Reward: " + spice.reward() + " Solaris before levy.", "Deadline: 30 real minutes, including offline time."));
|
||||
holder.inventory.setItem(15, icon(Material.WATER_BUCKET, "Water for the Hidden Sietch",
|
||||
"'A sietch beyond the patrol routes is running dry.'",
|
||||
"'Carry its water quietly. On Arrakis, water is life.'",
|
||||
"Deliver " + water.amount() + " finite-source water buckets.", "Reward: " + water.reward() + " Solaris before levy.", "Deadline: 30 real minutes, including offline time."));
|
||||
} else {
|
||||
holder.inventory.setItem(13, icon(Material.CHEST, "Deliver " + active.commodity(),
|
||||
"Required cargo: " + active.amount(), "Reward: " + active.reward() + " Solaris before levy.",
|
||||
timeLeft(active),
|
||||
"Use a different smuggler, 64+ blocks from the starting point.",
|
||||
"Departure: X " + (int) active.x() + " / Z " + (int) active.z(),
|
||||
active.commodity().equals("spice") ? "'Keep the melange beyond the Emperor's ledgers.'" : "'The hidden sietch is counting on you.'",
|
||||
"Illegal delivery triggers the existing bounty system."));
|
||||
holder.inventory.setItem(22, icon(Material.BARRIER, "Cancel Contract", "No cargo or Solaris is taken."));
|
||||
}
|
||||
player.openInventory(holder.inventory);
|
||||
}
|
||||
private Contract offer(String commodity, Entity trader) {
|
||||
int amount = Math.max(1, Math.min(commodity.equals("spice") ? 4096 : 36,
|
||||
plugin.getConfig().getInt("smugglers." + commodity + "-amount", commodity.equals("spice") ? 64 : 4)));
|
||||
int base = commodity.equals("spice") ? plugin.core().spiceSellPrice() : Math.max(1, plugin.core().spiceSellPrice() / 2);
|
||||
int reward = (int) Math.min(Integer.MAX_VALUE, Math.round((double) amount * base * 1.45));
|
||||
return new Contract(commodity, amount, reward, trader.getUniqueId(), trader.getLocation().getX(), trader.getLocation().getZ());
|
||||
}
|
||||
|
||||
@EventHandler public void click(InventoryClickEvent event) {
|
||||
if (!(event.getView().getTopInventory().getHolder() instanceof Menu menu)) return;
|
||||
event.setCancelled(true);
|
||||
if (!(event.getWhoClicked() instanceof Player player) || event.getClickedInventory() != event.getView().getTopInventory()) return;
|
||||
int slot = event.getRawSlot();
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
if (!player.isOnline()) return;
|
||||
player.closeInventory();
|
||||
expireContracts();
|
||||
if (!plugin.getConfig().getBoolean("smugglers.enabled", true)) return;
|
||||
if (sanctioned(player)) { player.sendMessage(ChatColor.RED + "Imperial sanction: smuggling contracts are unavailable."); return; }
|
||||
Entity trader = Bukkit.getEntity(menu.trader);
|
||||
if (trader == null || !trader.isValid() || !tagged(trader)
|
||||
|| !trader.getWorld().getName().equalsIgnoreCase("arrakis") || player.getWorld() != trader.getWorld()
|
||||
|| player.getLocation().distanceSquared(trader.getLocation()) > 64) {
|
||||
player.sendMessage(ChatColor.RED + "Return to the smuggler to trade."); return;
|
||||
}
|
||||
Contract active = contracts.get(player.getUniqueId());
|
||||
if (active == null && (slot == 11 || slot == 15)) {
|
||||
contracts.put(player.getUniqueId(), offer(slot == 11 ? "spice" : "water", trader));
|
||||
if (!save()) { contracts.remove(player.getUniqueId()); player.sendMessage("Contract could not be saved. Try again."); return; }
|
||||
updateCamps();
|
||||
player.sendMessage(ChatColor.GOLD + (slot == 11
|
||||
? "Smuggler: 'The melange must vanish from the Imperial ledger. My distant contact will pay for your silence.'"
|
||||
: "Smuggler: 'The hidden sietch has no water to spare. Reach my distant contact, and its people will remember.'"));
|
||||
player.sendMessage("Carry the cargo to another smuggler 64+ blocks from here. /dune smuggle status shows your contract.");
|
||||
player.sendMessage("You have 30 real minutes, including offline time. Your contact will wait at this lit camp until the contract ends.");
|
||||
} else if (active != null && slot == 22) {
|
||||
contracts.remove(player.getUniqueId());
|
||||
if (!save()) contracts.put(player.getUniqueId(), active);
|
||||
else { updateCamps(); player.sendMessage("Smuggling contract cancelled."); }
|
||||
} else if (active != null && slot == 13) deliver(player, trader, active);
|
||||
});
|
||||
}
|
||||
@EventHandler public void drag(InventoryDragEvent event) {
|
||||
if (event.getView().getTopInventory().getHolder() instanceof Menu) event.setCancelled(true);
|
||||
}
|
||||
static boolean validDestination(Contract contract, UUID trader, double x, double z) {
|
||||
return !contract.source().equals(trader) && Math.pow(x - contract.x(), 2) + Math.pow(z - contract.z(), 2) >= 4096;
|
||||
}
|
||||
private boolean cargo(ItemStack item, String commodity) {
|
||||
if (item == null || !item.hasItemMeta()) return false;
|
||||
if (commodity.equals("spice")) return "spice".equals(item.getItemMeta().getPersistentDataContainer().get(spiceKey, PersistentDataType.STRING));
|
||||
return item.getType() == Material.WATER_BUCKET && item.getItemMeta().getPersistentDataContainer().has(waterKey, PersistentDataType.BYTE);
|
||||
}
|
||||
private void deliver(Player player, Entity trader, Contract contract) {
|
||||
if (contract.expired(System.currentTimeMillis())) { updateCamps(); player.sendMessage("The 30-minute delivery window has expired."); return; }
|
||||
if (!validDestination(contract, trader.getUniqueId(), trader.getLocation().getX(), trader.getLocation().getZ())) {
|
||||
player.sendMessage("Find a different smuggler at least 64 blocks from the starting point."); return;
|
||||
}
|
||||
ItemStack[] original = player.getInventory().getStorageContents();
|
||||
ItemStack[] remaining = Arrays.stream(original).map(item -> item == null ? null : item.clone()).toArray(ItemStack[]::new);
|
||||
int needed = contract.amount();
|
||||
for (int i = 0; i < remaining.length && needed > 0; i++) if (cargo(remaining[i], contract.commodity())) {
|
||||
int taken = Math.min(needed, remaining[i].getAmount());
|
||||
needed -= taken;
|
||||
if (remaining[i].getAmount() == taken) remaining[i] = null;
|
||||
else remaining[i].setAmount(remaining[i].getAmount() - taken);
|
||||
}
|
||||
if (needed > 0) { player.sendMessage("You still need " + needed + " tagged " + contract.commodity() + "."); return; }
|
||||
// Persist completion before paying, preventing replay of a completed contract after restart.
|
||||
contracts.remove(player.getUniqueId());
|
||||
if (!save()) { contracts.put(player.getUniqueId(), contract); player.sendMessage("Delivery could not be saved. Try again."); return; }
|
||||
int net = Math.max(0, contract.reward() - politics.levyAmount(contract.reward()));
|
||||
if (!economy.depositPlayer(player, net).transactionSuccess()) {
|
||||
contracts.put(player.getUniqueId(), contract); save();
|
||||
player.sendMessage("Payment failed. Cargo kept; try delivery again."); return;
|
||||
}
|
||||
politics.levy(player.getUniqueId(), contract.reward());
|
||||
updateCamps();
|
||||
player.getInventory().setStorageContents(remaining);
|
||||
if (contract.commodity().equals("water")) {
|
||||
for (ItemStack bucket : player.getInventory().addItem(new ItemStack(Material.BUCKET, contract.amount())).values())
|
||||
player.getWorld().dropItemNaturally(player.getLocation(), bucket);
|
||||
}
|
||||
plugin.core().reportSmuggling(player, contract.commodity().toUpperCase(Locale.ROOT), contract.reward());
|
||||
player.sendMessage(ChatColor.GOLD + (contract.commodity().equals("spice")
|
||||
? "Smuggler: 'No seal, no names. The melange is already on its way. The Emperor's men may have noticed you.'"
|
||||
: "Smuggler: 'Tonight the sietch drinks. Keep your route secret; the water monopoly has long eyes.'"));
|
||||
player.sendMessage(ChatColor.GOLD + "Smuggling delivery complete: " + net + " Solaris after the Trust levy.");
|
||||
}
|
||||
void command(Player player, String[] args) {
|
||||
expireContracts();
|
||||
Contract contract = contracts.get(player.getUniqueId());
|
||||
if (contract == null) { player.sendMessage("No smuggling contract. Seek a roaming Arrakis Smuggler."); return; }
|
||||
if (args.length > 1 && args[1].equalsIgnoreCase("cancel")) {
|
||||
contracts.remove(player.getUniqueId());
|
||||
if (!save()) contracts.put(player.getUniqueId(), contract);
|
||||
else { updateCamps(); player.sendMessage("Contract cancelled. Cargo kept."); }
|
||||
return;
|
||||
}
|
||||
player.sendMessage(ChatColor.GOLD + (contract.commodity().equals("spice") ? "The Unmarked Spice Run" : "Water for the Hidden Sietch"));
|
||||
player.sendMessage(timeLeft(contract));
|
||||
player.sendMessage("Deliver " + contract.amount() + " tagged " + contract.commodity() + " to another Arrakis Smuggler, 64+ blocks from X "
|
||||
+ (int) contract.x() + " / Z " + (int) contract.z() + ". Reward: " + contract.reward() + " Solaris before levy. /dune smuggle cancel abandons it.");
|
||||
if (sanctioned(player)) player.sendMessage("Your Imperial sanction blocks delivery. Cancel the contract or wait for the appointment to expire.");
|
||||
}
|
||||
private boolean save() {
|
||||
for (String key : new HashSet<>(data.getKeys(false))) data.set(key, null);
|
||||
contracts.forEach((id, contract) -> {
|
||||
String key = id.toString();
|
||||
data.set(key + ".commodity", contract.commodity()); data.set(key + ".amount", contract.amount());
|
||||
data.set(key + ".reward", contract.reward()); data.set(key + ".source", contract.source().toString());
|
||||
data.set(key + ".x", contract.x()); data.set(key + ".z", contract.z());
|
||||
data.set(key + ".expires-at", contract.expiresAt());
|
||||
});
|
||||
try { data.save(file); return true; }
|
||||
catch (IOException exception) { plugin.getLogger().severe("Cannot save smuggling contracts: " + exception.getMessage()); return false; }
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff