forked from unimatrix/web
Extract DuneNPC with admin GUI and timed illuminated quest camps
This commit is contained in:
parent
f5bbe09227
commit
a4bb6c97e0
25 changed files with 740 additions and 83 deletions
34
.github/workflows/build.yml
vendored
34
.github/workflows/build.yml
vendored
|
|
@ -1,5 +1,5 @@
|
|||
|
||||
name: Build DuneCore, DuneEss, and DuneTerrain
|
||||
name: Build DuneCore, DuneNPC, DuneEss, and DuneTerrain
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
|
@ -91,9 +91,35 @@ jobs:
|
|||
path: DuneEss/build/libs/*.jar
|
||||
if-no-files-found: error
|
||||
|
||||
build-npc:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: DuneNPC
|
||||
steps:
|
||||
- name: Checkout source
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Java 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: '8.14'
|
||||
- name: Compile and test DuneNPC
|
||||
run: gradle clean build
|
||||
- name: Upload compiled JAR
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: DuneNPC-Plugin
|
||||
path: DuneNPC/build/libs/*.jar
|
||||
if-no-files-found: error
|
||||
|
||||
package-server:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-core, build-ess, build-terrain]
|
||||
needs: [build-core, build-ess, build-terrain, build-npc]
|
||||
steps:
|
||||
- name: Checkout source
|
||||
uses: actions/checkout@v4
|
||||
|
|
@ -118,10 +144,10 @@ jobs:
|
|||
cat > DuneRealms-Server-Package/README.txt <<'EOF'
|
||||
DuneRealms Paper server package
|
||||
|
||||
Contents: Vault 2.5.0, DuneCore, DuneEss, and DuneTerrain plugin JARs, plus DuneResourcePack.zip.
|
||||
Contents: Vault 2.5.0, DuneCore, DuneNPC, DuneEss, and DuneTerrain plugin JARs, plus DuneResourcePack.zip.
|
||||
The illustrated user manual and Project-README.md are included for players and administrators.
|
||||
|
||||
Install all four plugin JARs in the Paper server's plugins/ folder and restart the server.
|
||||
Install all five plugin JARs in the Paper server's plugins/ folder and restart the server.
|
||||
Install the included resource pack on vanilla or Fabric 1.21.4 clients for sandworm, haunted Fremen, and spice textures.
|
||||
On Fabric, put the ZIP in .minecraft/resourcepacks and enable it in Options > Resource Packs; do not put it in mods/.
|
||||
DuneEss provides the Solaris economy through the included Vault API plugin.
|
||||
|
|
|
|||
57
DuneNPC/README.md
Normal file
57
DuneNPC/README.md
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
# DuneNPC for Paper 1.21.4
|
||||
|
||||
Install DuneNPC 1.0.0 alongside DuneCore 1.0.8, DuneTerrain 1.0.7, DuneEss and Vault on Java 21.
|
||||
DuneNPC owns Guild Navigator placement/interactions and all Arrakis smuggler NPCs, missions,
|
||||
quest camps, invisible lights, particles and mission deadlines. DuneCore retains politics,
|
||||
faction rules, the sanctioned 33% spice-sale bonus, sandworms and hostile combat mobs.
|
||||
|
||||
## Admin GUI
|
||||
Open the Imperial Admin Scepter's menu and choose **DuneNPC Management**, or use `/dunenpc admin`.
|
||||
Operators can place a Guild Navigator, place an Arrakis Smuggler, view loaded NPC and contract
|
||||
counts, and return to the Dune admin menu. GUI actions check operator status again when executed.
|
||||
`/dunenpc guildnpc` preserves the existing `dune.admin` permission; `/dune guildnpc` is an alias.
|
||||
`/dunenpc smuggler` spawns a smuggler at an operator's current Arrakis position.
|
||||
|
||||
## Missions and camps
|
||||
Right-click an Arrakis Smuggler to accept **The Unmarked Spice Run** (64 tagged spice) or
|
||||
**Water for the Hidden Sietch** (4 finite-source water buckets). Default gross rewards are
|
||||
1,392 and 41 Solaris respectively, less the existing Trust levy. Deliver to a different
|
||||
smuggler at least 64 horizontal blocks from the departure point. Only the required tagged
|
||||
cargo is taken; water runs return empty buckets. Existing bounty rules apply on delivery.
|
||||
Spice Steward and House of Water members cannot accept/deliver smuggling missions; they get
|
||||
the 33% increase on ordinary spice sales instead. Appointments are rechecked at interaction.
|
||||
|
||||
- Green particles: no open contracts, NPC can roam.
|
||||
- Purple particles: one or more open contracts issued by this NPC.
|
||||
- During an open contract its source NPC stays stationary, cannot be pushed, is invulnerable,
|
||||
cannot naturally despawn, and has invisible level-15 lights around its camp.
|
||||
- Completion, cancellation or expiry restores the NPC and clears the lights when its last contract ends.
|
||||
- Every contract expires after **30 real minutes**, including offline time and server downtime.
|
||||
- Expiry keeps cargo and pays no reward. Time remaining appears in the GUI and status command.
|
||||
|
||||
`/dunenpc smuggle status|cancel` and the legacy `/dune smuggle status|cancel` are player commands.
|
||||
Contracts are local to the Arrakis backend and persist in `plugins/DuneNPC/smuggling.yml`.
|
||||
Camp restoration is journaled in `smuggler-camps.yml`; only air is replaced, existing terrain
|
||||
and light blocks are preserved, overlapping camps share ownership, and unloaded chunks are
|
||||
cleaned when they become available. Normal shutdown clears loaded camps; outstanding
|
||||
contracts reactivate on startup. Terrain is not force-loaded for temporary camp cleanup.
|
||||
|
||||
## Upgrade and configuration
|
||||
Replace DuneCore and DuneTerrain with the matching versions and add DuneNPC, then restart.
|
||||
Do not run an older Core's smuggler implementation alongside DuneNPC. The new plugin copies
|
||||
legacy mission/camp files only when its own destination files are missing. Originals remain
|
||||
as backups. Existing NPC tags are retained for compatibility. On first configuration it imports
|
||||
legacy Core smuggler options and Terrain's Guild NPC enabled flag. Existing undated contracts
|
||||
receive one initial 30-minute window; later restarts retain the saved deadline.
|
||||
|
||||
Edit `plugins/DuneNPC/config.yml` and restart:
|
||||
`guild-npc.enabled`, `smugglers.enabled`, `smugglers.max-traders`, `smugglers.spice-amount`,
|
||||
`smugglers.water-amount`. Mission duration is fixed at the requested 30 minutes.
|
||||
Enable DuneResourcePack.zip for the smuggler skin. Standard resource packs change all wandering
|
||||
trader appearances; NPC missions only run on Arrakis. Without the pack they look like vanilla traders.
|
||||
|
||||
## Build
|
||||
Run `gradle clean build` in DuneNPC. Its Gradle project compiles the sibling DuneCore dependency;
|
||||
DuneNPC's JAR contains only NPC classes, and DuneCore must also be installed on the server.
|
||||
Run `gradle build :DuneCore:build` to include Core's tests in the same invocation.
|
||||
Live Paper testing of NPC navigation, particles and block lighting remains required.
|
||||
22
DuneNPC/build.gradle.kts
Normal file
22
DuneNPC/build.gradle.kts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
plugins { java }
|
||||
group = "com.example"
|
||||
version = "1.0.0"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
maven("https://jitpack.io")
|
||||
}
|
||||
dependencies {
|
||||
compileOnly(project(":DuneCore"))
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
compileOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") }
|
||||
testImplementation(project(":DuneCore"))
|
||||
testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testImplementation("org.mockito:mockito-core:5.15.2")
|
||||
testRuntimeOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") }
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
}
|
||||
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
|
||||
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
|
||||
tasks.test { useJUnitPlatform() }
|
||||
3
DuneNPC/settings.gradle.kts
Normal file
3
DuneNPC/settings.gradle.kts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
rootProject.name = "DuneNPC"
|
||||
include(":DuneCore")
|
||||
project(":DuneCore").projectDir = file("../DuneRealms-minecraft-only")
|
||||
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 + "Spacing Guild 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("Guild Navigator 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 Guild Navigators, " + 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 Guild Navigator", "Spawn at your position; opens Guild 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; }
|
||||
}
|
||||
}
|
||||
7
DuneNPC/src/main/resources/config.yml
Normal file
7
DuneNPC/src/main/resources/config.yml
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
guild-npc:
|
||||
enabled: true
|
||||
smugglers:
|
||||
enabled: true
|
||||
max-traders: 6
|
||||
spice-amount: 64
|
||||
water-amount: 4
|
||||
11
DuneNPC/src/main/resources/plugin.yml
Normal file
11
DuneNPC/src/main/resources/plugin.yml
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
name: DuneNPC
|
||||
version: 1.0.0
|
||||
main: com.example.dunenpc.DuneNPC
|
||||
api-version: '1.21'
|
||||
depend: [DuneCore, DuneEss, Vault]
|
||||
softdepend: [DuneTerrain]
|
||||
description: Guild Navigators, roaming smugglers, timed missions and quest camps
|
||||
commands:
|
||||
dunenpc:
|
||||
description: NPC administration and smuggling mission status
|
||||
usage: /dunenpc admin | smuggle status | smuggle cancel
|
||||
18
DuneNPC/src/test/java/com/example/dunenpc/NpcAdminTest.java
Normal file
18
DuneNPC/src/test/java/com/example/dunenpc/NpcAdminTest.java
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
package com.example.dunenpc;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class NpcAdminTest {
|
||||
@Test void npcManagementGuiRequiresOperatorStatusEvenWithDuneAdminPermission() {
|
||||
DuneNPC plugin = mock(DuneNPC.class);
|
||||
Player player = mock(Player.class);
|
||||
when(player.hasPermission("dune.admin")).thenReturn(true);
|
||||
doCallRealMethod().when(plugin).openAdmin(player);
|
||||
plugin.openAdmin(player);
|
||||
verify(player).sendMessage(contains("Operators only"));
|
||||
verify(player, never()).openInventory(any(org.bukkit.inventory.Inventory.class));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
package com.example.dunenpc;
|
||||
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.block.data.type.Light;
|
||||
import org.bukkit.entity.WanderingTrader;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.MockedStatic;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class SmugglerCampsTest {
|
||||
@TempDir Path directory;
|
||||
|
||||
@Test void overlappingCampsKeepLightsUntilLastQuestEndsAndRestoreNpcState() {
|
||||
DuneNPC plugin = mock(DuneNPC.class);
|
||||
when(plugin.getDataFolder()).thenReturn(directory.toFile());
|
||||
World world = mock(World.class);
|
||||
UUID worldId = UUID.randomUUID(), first = UUID.randomUUID(), second = UUID.randomUUID();
|
||||
when(world.getUID()).thenReturn(worldId);
|
||||
when(world.getMaxHeight()).thenReturn(320);
|
||||
when(world.isChunkLoaded(anyInt(), anyInt())).thenReturn(true);
|
||||
BlockData air = mock(BlockData.class);
|
||||
when(air.getAsString()).thenReturn("minecraft:air");
|
||||
Light light = mock(Light.class);
|
||||
when(light.getLevel()).thenReturn(15);
|
||||
Map<String, AtomicReference<BlockData>> states = new HashMap<>();
|
||||
when(world.getBlockAt(anyInt(), anyInt(), anyInt())).thenAnswer(call -> {
|
||||
String key = call.getArgument(0) + "/" + call.getArgument(1) + "/" + call.getArgument(2);
|
||||
AtomicReference<BlockData> state = states.computeIfAbsent(key, ignored -> new AtomicReference<>(air));
|
||||
Block block = mock(Block.class);
|
||||
when(block.getType()).thenAnswer(ignored -> state.get() == air ? Material.AIR : Material.LIGHT);
|
||||
when(block.isEmpty()).thenAnswer(ignored -> state.get() == air);
|
||||
when(block.getBlockData()).thenAnswer(ignored -> state.get());
|
||||
doAnswer(change -> { state.set(change.getArgument(0)); return null; }).when(block).setBlockData(any(), eq(true));
|
||||
return block;
|
||||
});
|
||||
WanderingTrader traderA = trader(world), traderB = trader(world);
|
||||
try (MockedStatic<Bukkit> bukkit = mockStatic(Bukkit.class)) {
|
||||
bukkit.when(() -> Bukkit.getEntity(first)).thenReturn(traderA);
|
||||
bukkit.when(() -> Bukkit.getEntity(second)).thenReturn(traderB);
|
||||
bukkit.when(() -> Bukkit.getWorld(worldId)).thenReturn(world);
|
||||
bukkit.when(() -> Bukkit.createBlockData(Material.LIGHT)).thenReturn(light);
|
||||
bukkit.when(() -> Bukkit.createBlockData("minecraft:air")).thenReturn(air);
|
||||
SmugglerCamps camps = new SmugglerCamps(plugin);
|
||||
camps.sync(Set.of(first, second));
|
||||
assertEquals(5, states.size());
|
||||
assertTrue(states.values().stream().allMatch(state -> state.get() == light));
|
||||
verify(traderA).setAI(false);
|
||||
verify(traderA).setDespawnDelay(Integer.MAX_VALUE);
|
||||
camps.sync(Set.of(second));
|
||||
assertTrue(states.values().stream().allMatch(state -> state.get() == light));
|
||||
verify(traderA).setAI(true);
|
||||
verify(traderA).setGravity(true);
|
||||
verify(traderA).setInvulnerable(false);
|
||||
// Reloading the journal retains both ownership and the original air blocks.
|
||||
camps = new SmugglerCamps(plugin);
|
||||
camps.sync(Set.of());
|
||||
assertTrue(states.values().stream().allMatch(state -> state.get() == air));
|
||||
verify(traderB).setAI(true);
|
||||
verify(traderB).setDespawnDelay(12345);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void restorationOnlyRecognizesOwnedLevelFifteenUnwaterloggedLights() {
|
||||
assertFalse(SmugglerCamps.isCampLight(mock(BlockData.class)));
|
||||
Light light = mock(Light.class);
|
||||
when(light.getLevel()).thenReturn(14);
|
||||
assertFalse(SmugglerCamps.isCampLight(light));
|
||||
when(light.getLevel()).thenReturn(15);
|
||||
assertTrue(SmugglerCamps.isCampLight(light));
|
||||
when(light.isWaterlogged()).thenReturn(true);
|
||||
assertFalse(SmugglerCamps.isCampLight(light));
|
||||
}
|
||||
|
||||
private WanderingTrader trader(World world) {
|
||||
WanderingTrader trader = mock(WanderingTrader.class);
|
||||
when(trader.getWorld()).thenReturn(world);
|
||||
when(trader.getLocation()).thenReturn(new Location(world, 100, 70, 100));
|
||||
when(trader.hasAI()).thenReturn(true);
|
||||
when(trader.hasGravity()).thenReturn(true);
|
||||
when(trader.isCollidable()).thenReturn(true);
|
||||
when(trader.getDespawnDelay()).thenReturn(12345);
|
||||
return trader;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package com.example.dunenpc;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.UUID;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
class SmugglerMissionsTest {
|
||||
@Test void realTimeDeadlineExpiresAtThirtyMinutesAndSurvivesOfflineElapsedTime() {
|
||||
long start = 1000000L;
|
||||
Smugglers.Contract contract = new Smugglers.Contract("water", 4, 41, UUID.randomUUID(), 0, 0,
|
||||
start + Smugglers.MISSION_MILLIS);
|
||||
assertFalse(contract.expired(start + 29 * 60 * 1000L));
|
||||
assertFalse(contract.expired(start + Smugglers.MISSION_MILLIS - 1));
|
||||
assertTrue(contract.expired(start + Smugglers.MISSION_MILLIS));
|
||||
assertTrue(contract.expired(start + 24 * 60 * 60 * 1000L));
|
||||
}
|
||||
@Test void deliveryNeedsDifferentTraderAndSixtyFourBlockRoute() {
|
||||
UUID source = UUID.randomUUID(), other = UUID.randomUUID();
|
||||
Smugglers.Contract contract = new Smugglers.Contract("spice", 64, 1392, source, 10, -20);
|
||||
assertFalse(Smugglers.validDestination(contract, source, 1000, 1000));
|
||||
assertFalse(Smugglers.validDestination(contract, other, 73, -20));
|
||||
assertTrue(Smugglers.validDestination(contract, other, 74, -20));
|
||||
assertTrue(Smugglers.validDestination(contract, other, 10, -84));
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
The detailed [player and administrator manual](../docs/Dune-User-Manual.pdf) includes the complete Arrakis guide, command reference, configuration defaults, and reserved chapters for all other planets. DuneCore 1.0.5 renders sandworms as Sniffers while retaining native zombie AI through invisible Husk controllers; `/dune summon sandworm [x y z]` is available to admins.
|
||||
|
||||
Requires Java 21 and Gradle 8+. Build each project folder separately. Install Vault, then `DuneEss`, `DuneCore`, and `DuneTerrain` into Paper's `plugins/` directory. The downloadable server package includes Vault 2.5.0. DuneEss owns Solaris and Guild/admin travel and registers its economy through Vault; DuneCore provides factions, spice gameplay, politics, and jobs; DuneTerrain generates the planet worlds. Remove the old `DuneRealms.jar` when upgrading.
|
||||
Requires Java 21 and Gradle 8+. Build each project folder separately. Install Vault, then `DuneEss`, `DuneCore`, `DuneNPC`, and `DuneTerrain` into Paper's `plugins/` directory. The downloadable server package includes Vault 2.5.0. DuneEss owns Solaris and Guild/admin travel and registers its economy through Vault; DuneCore provides factions, spice gameplay, politics, and jobs; DuneTerrain generates the planet worlds. Remove the old `DuneRealms.jar` when upgrading.
|
||||
|
||||
Commands: `/dune choose fremen|harkonnen|corrino|atreides|ordos`, `/dune kit`, `/dune guildnpc` (OP), `/dune givespice` (OP), `/duneess balance`, `/duneess sell`, `/duneess travel [planet]`, and `/duneess admin ...`. Use `/dune help` or `/duneess help` for the spaced, boxed chat guide with clickable Previous/Next links. `/duneess help <page>` opens a page directly and `/duneess help menu` opens the inventory guide.
|
||||
|
||||
|
|
@ -87,3 +87,10 @@ The trims are Minecraft's built-in vanilla patterns, not custom resource-pack mo
|
|||
|
||||
## Proxy mode
|
||||
See `NETWORK_SETUP.md` for the five-server Velocity topology, required per-server config, and critical shared-data limitations.
|
||||
|
||||
Contracts now have a **30-minute real-time deadline**, including offline time and server downtime.
|
||||
The remaining time appears in the mission menu and `/dune smuggle status`.
|
||||
Expired missions consume no cargo and pay no reward. When the last mission expires, the source
|
||||
smuggler returns to green particles and normal roaming, and its temporary lighting is removed.
|
||||
Contracts created before 1.0.8 receive one initial 30-minute window when first upgraded; subsequent
|
||||
restarts preserve their saved deadline.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
plugins { java }
|
||||
group = "com.example"
|
||||
version = "1.0.7"
|
||||
version = "1.0.8"
|
||||
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://jitpack.io") }
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ final class AdminGui implements Listener {
|
|||
private final NamespacedKey rodKey;
|
||||
private static final Map<Integer, String> COMMANDS = Map.of(
|
||||
10, "summon sandworm", 12, "guildnpc", 14, "givespice",
|
||||
16, "guireload", 20, "kit", 24, "politics status");
|
||||
16, "guireload", 20, "kit", 22, "npcadmin", 24, "politics status");
|
||||
|
||||
private static final class Menu implements InventoryHolder {
|
||||
private Inventory inventory;
|
||||
|
|
@ -68,6 +68,7 @@ final class AdminGui implements Listener {
|
|||
holder.inventory.setItem(14, icon(Material.ORANGE_DYE, "Give Test Spice", "Receive one tagged spice item."));
|
||||
holder.inventory.setItem(16, icon(Material.COMPARATOR, "Reload Menus", "Reload gui.yml from disk."));
|
||||
holder.inventory.setItem(20, icon(Material.NETHERITE_CHESTPLATE, "Receive Faction Kit", "Receive your selected faction's kit."));
|
||||
holder.inventory.setItem(22, icon(Material.WANDERING_TRADER_SPAWN_EGG, "DuneNPC Management", "Open NPC spawning and mission status controls."));
|
||||
holder.inventory.setItem(24, icon(Material.WRITABLE_BOOK, "Imperial Status", "View politics, appointments and Trust status."));
|
||||
holder.inventory.setItem(31, icon(Material.BARRIER, "Close"));
|
||||
player.openInventory(holder.inventory);
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
private final String[] factions = {"Fremen", "Harkonnen", "Corrino", "Atreides", "Ordos"};
|
||||
private final Map<UUID, String> selected = new HashMap<>();
|
||||
private Economy economy;
|
||||
private NamespacedKey itemKey, npcKey, wormKey, armorFactionKey, raiderKey;
|
||||
private NamespacedKey itemKey, wormKey, armorFactionKey, raiderKey;
|
||||
private File dataFile;
|
||||
private final Map<UUID, Job> jobs = new HashMap<>();
|
||||
private final Map<UUID, UUID> activeWorkers = new HashMap<>();
|
||||
|
|
@ -59,10 +59,11 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
private final Map<UUID, Integer> sunExposureSeconds = new HashMap<>();
|
||||
private ConfigurableGui gui;
|
||||
private AdminGui adminGui;
|
||||
private Smugglers smugglers;
|
||||
|
||||
private Politics politics;
|
||||
private SharedDatabase sharedDatabase;
|
||||
public SharedDatabase sharedDatabase(){return sharedDatabase;}
|
||||
public Politics politics(){return politics;}
|
||||
public String factionOf(Player player){return selected.getOrDefault(player.getUniqueId(),"");}
|
||||
public void persistPlayers(){savePlayers();}
|
||||
private ArrakisWater arrakisWater;
|
||||
|
|
@ -75,7 +76,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
|
||||
@Override public void onEnable() {
|
||||
migrateLegacyData();
|
||||
saveDefaultConfig(); itemKey = new NamespacedKey("dunerealms", "item"); npcKey = new NamespacedKey("dunerealms", "guild"); wormKey = new NamespacedKey("dunerealms", "sandworm"); armorFactionKey = new NamespacedKey("dunerealms", "armor_faction"); raiderKey = new NamespacedKey("dunerealms", "spice_raider");
|
||||
saveDefaultConfig(); itemKey = new NamespacedKey("dunerealms", "item"); wormKey = new NamespacedKey("dunerealms", "sandworm"); armorFactionKey = new NamespacedKey("dunerealms", "armor_faction"); raiderKey = new NamespacedKey("dunerealms", "spice_raider");
|
||||
dataFile = new File(getDataFolder(), "players.yml"); data = YamlConfiguration.loadConfiguration(dataFile);
|
||||
for (String key : data.getKeys(false)) try {
|
||||
UUID id = UUID.fromString(key); selected.put(id, data.getString(key + ".faction", ""));
|
||||
|
|
@ -108,7 +109,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
duneCommand.setTabCompleter(this);
|
||||
Bukkit.getPluginManager().registerEvents(this, this);
|
||||
adminGui = new AdminGui(this);
|
||||
smugglers = new Smugglers(this, economy, politics);
|
||||
|
||||
announcements = new ArrakisAnnouncements(this);
|
||||
sandwormMobs = new SandwormMobs(this, wormKey);
|
||||
World loadedArrakis = Bukkit.getWorld("arrakis");
|
||||
|
|
@ -119,6 +120,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
getLogger().info("DuneCore enabled. Gameplay, faction travel, Arrakis threats, and spice raiders ready.");
|
||||
}
|
||||
@Override public void onDisable() {
|
||||
|
||||
for (UUID playerId : new ArrayList<>(ordosCloakedArmor.keySet())) restoreOrdosArmor(playerId);
|
||||
if(serverJobs!=null)serverJobs.save(); savePlayers();
|
||||
}
|
||||
|
|
@ -490,7 +492,8 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
selected.put(p.getUniqueId(), match); economy.createPlayerAccount(p); savePlayers(); kit(p); factionArrival(p, planets[Arrays.asList(factions).indexOf(match)]);
|
||||
p.sendMessage(ChatColor.GREEN + "You joined " + match + "!");
|
||||
}
|
||||
case "smuggle" -> smugglers.command(p, args);
|
||||
case "smuggle" -> forwardNpc(p, "smuggle " + String.join(" ", Arrays.copyOfRange(args, 1, args.length)));
|
||||
case "npcadmin" -> forwardNpc(p, "admin");
|
||||
case "elytra" -> mergeElytra(p);
|
||||
case "kit" -> { if (!selected.containsKey(p.getUniqueId())) { p.sendMessage("Choose a faction first."); break; } kit(p); }
|
||||
case "politics", "trust" -> politics.command(p, args);
|
||||
|
|
@ -502,17 +505,18 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
case "exchange" -> gui.open(p, "exchange");
|
||||
case "serverjobs" -> serverJobs.command(p, args);
|
||||
case "job" -> jobCommand(p, args);
|
||||
case "guildnpc" -> {
|
||||
if (!p.hasPermission("dune.admin")) { p.sendMessage("Admin only."); break; }
|
||||
Villager v = p.getWorld().spawn(p.getLocation(), Villager.class); v.setCustomName(ChatColor.LIGHT_PURPLE + "Spacing Guild Navigator"); v.setCustomNameVisible(true);
|
||||
v.setProfession(Villager.Profession.CLERIC); v.setAI(false); v.getPersistentDataContainer().set(npcKey, PersistentDataType.BYTE, (byte)1);
|
||||
}
|
||||
case "guildnpc" -> forwardNpc(p, "guildnpc");
|
||||
case "givespice" -> { if (p.hasPermission("dune.admin")) p.getInventory().addItem(spiceDrop(p, 1)); }
|
||||
default -> p.sendMessage("Use /dune help");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void forwardNpc(Player player, String command) {
|
||||
org.bukkit.plugin.Plugin npc = Bukkit.getPluginManager().getPlugin("DuneNPC");
|
||||
if (npc == null || !npc.isEnabled()) { player.sendMessage(ChatColor.RED + "Install and enable DuneNPC for NPC controls and smuggling missions."); return; }
|
||||
Bukkit.dispatchCommand(player, "dunenpc " + command.trim());
|
||||
}
|
||||
private void sendHelp(CommandSender sender) {
|
||||
sender.sendMessage(ChatColor.GOLD + "=== DuneCore command guide ===");
|
||||
helpSection(sender, "General");
|
||||
|
|
@ -720,9 +724,6 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
|
|||
World w = Bukkit.getWorld(planets[index]);
|
||||
if (w != null) e.setRespawnLocation(w.getSpawnLocation().clone());
|
||||
}
|
||||
@EventHandler public void onNpc(PlayerInteractEntityEvent e) {
|
||||
if (e.getRightClicked().getPersistentDataContainer().has(npcKey, PersistentDataType.BYTE)) { e.setCancelled(true); Bukkit.dispatchCommand(e.getPlayer(), "duneess travel"); }
|
||||
}
|
||||
@EventHandler public void onSpice(BlockBreakEvent e) {
|
||||
Block block = e.getBlock();
|
||||
if (!block.getWorld().getName().equals("arrakis") || block.getType() != Material.SUSPICIOUS_SAND) return;
|
||||
|
|
|
|||
|
|
@ -61,9 +61,4 @@ database:
|
|||
username: "dune"
|
||||
password: "CHANGE_ME"
|
||||
|
||||
# Roaming Arrakis traders: native wandering-trader AI and local persistent delivery contracts.
|
||||
smugglers:
|
||||
enabled: true
|
||||
max-traders: 6
|
||||
spice-amount: 64
|
||||
water-amount: 4
|
||||
# NPC settings are now managed by DuneNPC/config.yml.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
name: DuneCore
|
||||
version: 1.0.7
|
||||
version: 1.0.8
|
||||
main: com.example.dunerealms.DuneCore
|
||||
api-version: '1.21'
|
||||
depend: [Vault, DuneEss]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
package com.example.dunerealms;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.UUID;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class SpiceSaleTest {
|
||||
@Test void ordinarySaleOnlyBonusesSanctionedPlayersAndHandlesRoundingAndOverflow() {
|
||||
assertEquals(1995, DuneCore.sanctionedSpiceGross(1500, true));
|
||||
assertEquals(1500, DuneCore.sanctionedSpiceGross(1500, false));
|
||||
assertEquals(20, DuneCore.sanctionedSpiceGross(15, true));
|
||||
assertEquals(0, DuneCore.sanctionedSpiceGross(-100, true));
|
||||
assertEquals(Integer.MAX_VALUE, DuneCore.sanctionedSpiceGross(Integer.MAX_VALUE, true));
|
||||
}
|
||||
@Test void sanctionedNormalSaleAppliesBonusBeforeLevyAndDoesNotReportSmuggling() throws Exception {
|
||||
for (boolean spiceAppointment : new boolean[]{true, false}) {
|
||||
DuneCore plugin = mock(DuneCore.class);
|
||||
Player player = mock(Player.class);
|
||||
Politics politics = mock(Politics.class);
|
||||
when(plugin.factionOf(player)).thenReturn("Atreides");
|
||||
when(politics.isAuthorizedSpice("Atreides")).thenReturn(spiceAppointment);
|
||||
when(politics.isAuthorizedWater("Atreides")).thenReturn(!spiceAppointment);
|
||||
when(politics.levy(player.getUniqueId(), 1995)).thenReturn(25);
|
||||
Field field = DuneCore.class.getDeclaredField("politics");
|
||||
field.setAccessible(true); field.set(plugin, politics);
|
||||
when(plugin.processSpiceSale(player, 1500)).thenCallRealMethod();
|
||||
assertEquals(1970, plugin.processSpiceSale(player, 1500));
|
||||
verify(plugin, never()).reportSmuggling(any(), anyString(), anyInt());
|
||||
verify(politics).levy(player.getUniqueId(), 1995);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -34,3 +34,8 @@ The generator applies to newly generated chunks. Existing chunks are never repla
|
|||
Arrakis uses the Desert biome throughout and has no vanilla vegetation. Sparse persistent-leaf oasis trees remain about 300 blocks apart. A larger underground cave sietch generates about every 2,000 blocks; it has a broad stone-arched cave entrance, connected sleeping and kitchen chambers, a gently winding descent to a larger bottom reservoir with a waterfall, and a personal cache per player containing at least 250 tagged spice, enchanted gold armor, planks, and bread. Raised darkstone islands generate about every 750 blocks, with broad flat sand plateaus and steep, exposed blackstone and basalt sides. Spice blows also generate about every 2,000 blocks as a magma cluster; touching one with a living entity or hitting it with an arrow or trident releases a rich suspicious-sand field worth about 15,000 Solaris at the default 15 Solaris per spice. Admins can use `/dune admin spiceblow [player]` to teleport to the nearest generated or erupted spice blow. Set `sietches.spacing`, `spice-blow.spacing`, and `planets.arrakis.darkstone-islands.spacing` to adjust structure intervals. Random spice patches generate about 35% of 600-by-600-block regions; each patch has roughly 5,000 Solaris in deposits at the default price. Adjust `spice-deposits.patches` for patch frequency, size, or value.
|
||||
|
||||
DuneCore sends new players who have not chosen a faction from Paper's default `world` to the local planet spawn, so they arrive in the world generated by DuneTerrain.
|
||||
|
||||
As of DuneTerrain 1.0.7, Guild Navigator NPC creation is handled exclusively by DuneNPC.
|
||||
Install DuneNPC with DuneCore for automatic Navigators and their travel menus. Existing tagged
|
||||
Navigators are reused. `guild-npc.enabled` now belongs in `plugins/DuneNPC/config.yml`; its legacy
|
||||
DuneTerrain value is imported when DuneNPC is first configured.
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff