diff --git a/DuneRealms-minecraft-only/ARRAKIS_TRAVEL_RULES.md b/DuneRealms-minecraft-only/ARRAKIS_TRAVEL_RULES.md new file mode 100644 index 00000000..826a4d80 --- /dev/null +++ b/DuneRealms-minecraft-only/ARRAKIS_TRAVEL_RULES.md @@ -0,0 +1,5 @@ +# Unsanctioned travel to Arrakis + +All arrivals to Arrakis without a single-use Emperor permit are marked as smuggling. An Emperor-issued free-transport decree for the traveler’s faction causes a two-minute database permit to be created when using `/dune` travel; Arrakis consumes it upon arrival. Unpermitted arrivals trigger an Arrakis-wide alert and a one-time bounty claimable on PvP kill, equal to the configured one-bucket smuggler sale value (half the spice price, plus 45%). + +**Security and gameplay limitations:** This does not yet implement a proxy-side trusted arrival gate. Proxy redirects, server restarts, direct joins and returning Arrakis players without a fresh permit will be treated as smugglers. Only Emperor free-travel decrees count as sanctions; there is no separate imperial visa command. Alerts go to online players on Arrakis, not to offline users. The current bounty system has no expiry or anti-collusion protection. Permits are issued before transfer success is confirmed, and there is no refund/rollback handshake. The prior shared politics YAML still has race conditions. This is source-only and has not been compiled or tested. diff --git a/DuneRealms-minecraft-only/ARRAKIS_WATER.md b/DuneRealms-minecraft-only/ARRAKIS_WATER.md new file mode 100644 index 00000000..4df8464d --- /dev/null +++ b/DuneRealms-minecraft-only/ARRAKIS_WATER.md @@ -0,0 +1,17 @@ +# Arrakis Water & Sietch prototype + +New Arrakis chunks can generate sandstone **sietches** with a cave and small water reservoir beneath. Existing chunks will not be retroactively populated. Generation is approximately 1 in 90 chunks (hard-coded in the populator; config field is informational for now). + +- `/dune water guild` - become an official Spacing Guild water seller. +- `/dune water smuggler` - become a smuggler. +- `/dune water status` - show career and rates. +- `/dune water sell` - sell tagged Arrakis water buckets at half the configured spice unit price. Smugglers receive 45% more gross pay, but have a configurable 30% chance of angering locals and spawning hostile Husks if on Arrakis. +- All water sales contribute the same 1.21% Spacing Trust levy as spice sales. +- On Arrakis, water flow is canceled, bucket placement is blocked, and ice/cauldron water formation is limited. Collected water is tagged and source blocks are consumed. + +## Limitations / unfinished +- This is an early prototype and is **not tested or compiled**. +- Careers are in memory and reset on server restart; make them persistent in a shared database. +- Water sold is separate from the existing CHOAM hourly contract templates. The water career system is available through `/dune water`, but water-collection quotas are not yet integrated into the CHOAM job rotation. +- Finite water is not fully enforced against every vanilla mechanism (dispensers, bottles, structure generation, commands, ice import, cross-server inventory transfers, etc.). Harden these before a production launch. +- No shared player inventory or balance across proxy servers yet. diff --git a/DuneRealms-minecraft-only/FACTION_ABILITIES.md b/DuneRealms-minecraft-only/FACTION_ABILITIES.md new file mode 100644 index 00000000..060da10f --- /dev/null +++ b/DuneRealms-minecraft-only/FACTION_ABILITIES.md @@ -0,0 +1,11 @@ +# Faction full-set bonuses + +Full set = faction-tagged stillsuit helmet, leggings and boots plus either a faction-tagged stillsuit chestplate or the faction's merged Elytra-stillsuit in the chest slot. Mixed house sets do not qualify. + +- Fremen: base Unbreaking III on all four pieces, Swift Sneak III on leggings (these are permanent item enchantments). +- Corrino: base Protection III on all four pieces. +- Harkonnen: full-set Strength II potion effect (amplifier 1); refreshed every second while equipped. +- Ordos: with a full set, right-clicking an Ender Pearl grants five seconds of invisibility and still throws the pearl. +- Atreides: full set adds eight maximum health points (+4 hearts) through a player attribute modifier, removed when the set breaks. + +This is source-only, not compiled or tested. Important: the current `onOrdosPearl` activation may not fire in all interaction contexts (e.g. cancelled interaction); verify on Paper 1.21.4. Harkonnen Strength may persist up to ~1.25 seconds after removal due to potion refresh. Existing network synchronization limitations remain. diff --git a/DuneRealms-minecraft-only/IMPERIAL_APPOINTMENTS.md b/DuneRealms-minecraft-only/IMPERIAL_APPOINTMENTS.md new file mode 100644 index 00000000..a761b579 --- /dev/null +++ b/DuneRealms-minecraft-only/IMPERIAL_APPOINTMENTS.md @@ -0,0 +1,9 @@ +# Imperial appointments + +The elected Emperor may make **one appointment of each type per weekly election term**: +- `/dune politics steward `: appoints the Steward of Dune. Only this faction has legal spice-trading privileges; it is also the faction exempted from Arrakis travel-smuggling classification. +- `/dune politics houseofwater `: appoints the House of Water. Only this faction has legal water-selling privileges. + +All other factions are treated as smugglers when selling the corresponding resource, with planet-wide warnings and bounty registration. Unauthorized Arrakis arrivals remain flagged as travel smugglers. Appointments expire when the weekly election changes or a different Emperor becomes the winner. + +IMPORTANT: This is source-only, uncompiled and untested. The existing political YAML snapshot stored in PostgreSQL is not transaction-safe across concurrent servers. The existing water-career selection remains available but imperial appointment overrides its legal status. The plugin still requires reliable proxy transfer handling, inventory locking, and stronger anti-exploit protections. diff --git a/DuneRealms-minecraft-only/MINECRAFT_ONLY_SCOPE.md b/DuneRealms-minecraft-only/MINECRAFT_ONLY_SCOPE.md new file mode 100644 index 00000000..13f91acb --- /dev/null +++ b/DuneRealms-minecraft-only/MINECRAFT_ONLY_SCOPE.md @@ -0,0 +1,8 @@ +# Minecraft-only item scope +This edition deliberately excludes fictional vehicle items, custom consumables, decorative building sets, special utility gadgets and transport tokens. No such items were found in the inspected Java source, so no fictional item registrations needed removal. + +Retained actual Minecraft materials with plugin metadata: dyed leather faction stillsuits, merged Elytra, netherite shovel (Efficiency V, Unbreaking III) for spice harvesting, orange dye for spice, nether star for the Dune Navigator menu, ender pearls used as travel GUI buttons, water buckets, and ordinary vanilla materials used by the existing gameplay. + +The game does not include ornithopters, sandcrawlers, sand bikes, faction banners, shield cores, spice analyzers, water vials, fictional consumables, or fictional decoration blocks. The Spacing Guild remains a travel service, not a vehicle item. + +Important: source is uncompiled and untested; earlier multiplayer race conditions and other prototype limitations remain. diff --git a/DuneRealms-minecraft-only/NETWORK_SETUP.md b/DuneRealms-minecraft-only/NETWORK_SETUP.md new file mode 100644 index 00000000..f64af1a5 --- /dev/null +++ b/DuneRealms-minecraft-only/NETWORK_SETUP.md @@ -0,0 +1,34 @@ +# DuneRealms — proxy server deployment (prototype) + +Five separate Paper 1.21.x backend servers connect through a **Velocity** proxy. Each backend installs the same plugin JAR and uses a different `network.local-planet` value in its `config.yml`. Configure `network.servers` with the **exact Velocity server names**. The plugin now generates only its local planet when `network.enabled: true`. + +| Backend | `network.local-planet` | Velocity server name | +|---|---|---| +| Arrakis | `arrakis` | `arrakis` | +| Giedi Prime | `giedi_prime` | `giedi-prime` | +| Kaitain | `kaitain` | `kaitain` | +| Caladan | `caladan` | `caladan` | +| Sigma Draconis IV | `sigma_draconis_iv` | `sigma-draconis-iv` | + +Example Velocity `velocity.toml` excerpt: + +```toml +[servers] +arrakis = "127.0.0.1:25566" +giedi-prime = "127.0.0.1:25567" +kaitain = "127.0.0.1:25568" +caladan = "127.0.0.1:25569" +sigma-draconis-iv = "127.0.0.1:25570" +try = ["arrakis"] + +[advanced] +bungee-plugin-message-channel = true +``` + +Enable Velocity modern forwarding and configure each Paper backend for Velocity forwarding with the same forwarding secret. Block direct external access to backend ports. Players should connect only through the proxy. Check Velocity's current documentation for the exact forwarding options on your versions. + +The Spacing Guild menu uses the `BungeeCord` `Connect` plugin message to ask Velocity to switch servers. This is an asynchronous request **without delivery acknowledgment**. The current plugin deducts travel fare when requesting a transfer, even if the destination is offline. + +**Critical limitation — not production ready:** `players.yml`, hourly jobs, exchange listings, balances, and inventory are currently local to each backend. They do **not** synchronize across servers. A production network needs a shared authoritative database (e.g., MariaDB/PostgreSQL), transactional fare charges and payouts, cross-server inventory/player-data synchronization, and a proxy-side first-join/homeworld router. Without these, Solaris and contracts will differ between planets, and faction homeworld routing is not reliable. Do not deploy with a live economy until shared state and transfer confirmation are implemented. + +Sandworms and burning sun only activate in the world named `arrakis`. Server job definitions remain per-backend until centralized. diff --git a/DuneRealms-minecraft-only/POLITICS_SETUP.md b/DuneRealms-minecraft-only/POLITICS_SETUP.md new file mode 100644 index 00000000..d7671066 --- /dev/null +++ b/DuneRealms-minecraft-only/POLITICS_SETUP.md @@ -0,0 +1,20 @@ +# Spacing Trust and Politics (prototype) + +This release adds actual Paper plugin code (`Politics.java`) and `/dune politics` commands. + +- Spice sales contribute 1.21% of gross Solaris earnings to the Spacing Trust (rounded up). +- `/dune politics deposit ` deposits extra Solaris. +- `/dune politics status` shows treasury, current election winners and invasion. +- `/dune politics vote ` elects a faction leader, one vote per voter per UTC-based 7-day epoch window. +- `/dune politics emperorvote ` elects an Emperor, one vote per player per election window. +- `/dune politics invasion ` allows current faction leader to spend a configurable Trust cost and open an invasion. +- `/dune politics defend` allows a defending faction member to contribute once; configured count repels the invasion. +- `/dune politics grantarrakis ` lets the current Emperor issue one weekly temporary free-transport decree to Arrakis. + +**IMPORTANT LIMITATIONS** +1. Politics state and player wallets are currently saved to local YAML files, not shared between servers. The system is NOT network-consistent and must not be used as-is for cross-server politics. Implement transactional MySQL/PostgreSQL shared storage and proxy routing first. +2. Invasion defense is a command-based contribution prototype, not objective-based PvP or territory capture. +3. Elections use a rolling epoch-aligned 7-day window; votes immediately influence winners, without nomination or election-close certification. +4. Arrakis free-travel decree applies to GUI command travel path; review all NPC travel paths before release. +5. There is no safe refund on failed proxy transfers in the pre-existing travel system. +6. Code is provided as source and has not been compiled/tested against a live Paper/Velocity network. diff --git a/DuneRealms-minecraft-only/README.md b/DuneRealms-minecraft-only/README.md new file mode 100644 index 00000000..afa21a99 --- /dev/null +++ b/DuneRealms-minecraft-only/README.md @@ -0,0 +1,83 @@ +# DuneRealms for Paper 1.21.4 + +Requires Java 21 and Gradle 8+. Run `gradle build` and copy `build/libs/DuneRealms-1.0.0.jar` into your Paper server's `plugins/` directory. Restart the server. This project is source code, not a precompiled JAR. + +Commands: `/dune choose fremen|harkonnen|corrino|atreides`, `/dune kit`, `/dune balance`, `/dune sell`, `/dune travel`, `/dune guildnpc` (OP), `/dune givespice` (OP). + +Worlds are generated on first server start: `arrakis`, `giedi_prime`, `kaitain`, `caladan`. Custom generator selection only applies when a world is first generated. Existing worlds with these names will not be replaced. For safety, back up your server before installing. + +Red sand in Arrakis is harvestable spice. You need all four stillsuit pieces equipped and the custom netherite spice shovel in hand. Spice can be sold with `/dune sell` and Solaris spent at Guild NPCs or `/dune travel`. Each faction has a passive perk; Fremen harvest double spice. Player faction and balances persist in `plugins/DuneRealms/players.yml`. + +Limitations: this is a gameplay prototype, not a fully polished mod. Custom equipment uses vanilla items and colored names, not resource-pack models. Worlds have themed terrain, but no cities, unique buildings, or detailed biome decorations. Guild NPCs are placed by operators. No permissions-based faction change for ordinary players. The plugin has not been compiled or tested against a running Paper server in this environment. + +## Sandworms (Shai-Hulud) + +Hostile, oversized husks representing sandworms spawn on sandy surfaces near players **only on Arrakis**, roughly every 10 seconds with a configurable chance. They target players, have 500 health and 30 base melee attack damage (Warden-level values), and play a Warden roar when emerging. They cannot teleport to other worlds. Settings are under `sandworms` in `config.yml`. The worm is represented by a scaled vanilla husk; a true animated worm model would require a resource pack or model plugin. + +## Spice contracts and sandworm blooms +- On Arrakis, defeating a sandworm generates a broad patch of red-sand spice deposits with a target base harvest value of 100,000 Solaris (actual value depends on available sandy terrain and faction bonuses). +- Players begin on their faction's homeworld after choosing a faction and respawn there. +- `/dune exchange` shows open spice contracts. +- `/dune job post ` creates a contract. +- `/dune job accept ` accepts another player's contract and transports the worker to Arrakis. +- Contract harvesting pays 15% of spice sale value to the worker and 85% to the sponsor automatically, with no double sale of contracted spice. +- `/dune job finish` leaves a job; `/dune job cancel` cancels an unclaimed listing. +- A sponsor's job remains listed across restarts, but active worker assignments must be reaccepted after restart. + +This is source code, not a tested compiled JAR. + +## Hourly server-issued CHOAM jobs +Edit `plugins/DuneRealms/server-jobs.yml` to configure job `title`, `spice-required`, `pay`, and `time-limit-minutes`. `offers-per-hour` controls how many are randomly selected. Listings rotate every hour at UTC hour boundaries. Existing accepted contracts persist through restarts, including their original deadlines; if a definition is removed while active, that contract expires without a fine. + +Commands: `/dune serverjobs` (list), `/dune serverjobs accept ` (accept), `/dune serverjobs reload` (admin; reload definitions). Harvesting spice with the stillsuit and axe advances the active server contract. Successful completion pays the configured amount. Failure after the deadline incurs a **5% fine on the configured pay**, rounded up. Fines can produce negative Solaris balances (debt). Contracts expire even while players are offline, checked every 10 seconds while the server is running. + +Server-issued contracts are separate from player-to-player exchange contracts. Harvesting can advance both simultaneously; server jobs pay their own fixed completion reward, and normal spice drops/player contract earnings remain unchanged. + +## Chest-style GUI +`/dune` or `/dune gui` opens the native Minecraft chest inventory menu. It has navigation for guild travel, faction choice, harvesting kit, spice sales, balance, hourly server contracts, and player-to-player spice jobs. GUI clicks invoke the same permission-checked commands or existing travel logic. The exchange supports preset 100/500/1000-spice postings; arbitrary amounts remain available through `/dune job post `. No external ChestCommands plugin dependency is required. + +## Dune Navigator menu item +Each joining player receives a persistent-data-tagged Nether Star named **Dune Navigator** (unless already present). Left-click or right-click while holding it in the main hand opens the main chest GUI. Interaction is cancelled to avoid accidentally hitting or activating blocks. `/dune menuitem` gives a replacement when missing; `/dune` and `/dune gui` still work. The menu item is recognized by its plugin tag, not its display name. + +## Fully configurable GUI (`gui.yml`) +The GUI is now configured by `plugins/DuneRealms/gui.yml`, copied from resources on first startup. Every menu has an editable title, chest size (9–54 in multiples of 9), and items with icon, slot, name, lore, and action. Use `/dune guireload` (admin) after editing. Supported actions are `open:`, `dune:`, `close`, and `none`. Arbitrary console commands are intentionally not supported. Dynamic CHOAM jobs, factions, and planets use editable `dynamic` sections, including icon, starting slot, step, lore, and action. Placeholders: `%player%`, `%balance%`, `%travel_cost%`, `%active_job%`, `%id%` (dynamic). Menu opener item continues to work with either mouse button. + +NOTE: Player-to-player exchange listings can still be accepted through `/dune job accept `; the configurable exchange menu currently includes configurable posting/cancel/leave controls but does not yet render dynamic player listings. + +## Faction-colored glass pane backgrounds +The chest menus use configurable stained glass panes as the backdrop, based on the player's selected faction: Harkonnen red, Ordos/Fremen green, Atreides blue, Corrino purple. Unassigned players get gray. Interactive items overwrite background panes. On the faction selector, each faction choice is itself represented by its corresponding colored glass pane. Colors can be changed under `backgrounds:` in `gui.yml`, and individual menus can disable the backdrop with `faction-background: false`. `/dune choose ordos` is accepted as an alias for Fremen; this does not change existing saved faction data. + +## Faction-colored stillsuits +`/dune kit` now grants four leather armor pieces dyed to match the player's faction GUI background: Harkonnen red, Ordos/Fremen green, Atreides blue, Corrino purple. The items keep their `stillsuit` persistent-data identifier, so full-set spice harvesting continues to work. Existing already-issued armor is not recolored automatically; use `/dune kit` to obtain a newly dyed set. + +## Expanded faction palette +Fremen now have orange armor and orange glass; Ordos is a distinct green faction with green armor and green glass. Harkonnen remains red, Atreides blue, Corrino purple. Spacing Guild is reserved as a black visual/armor color (`spacing_guild`) but is not a selectable player faction, so no Guild armor is issued through `/dune kit` yet. Ordos currently shares Arrakis as a starting planet. Color values are hardcoded for dyed armor; GUI glass materials are configured in `gui.yml`. + +## Netherite-strength armor and winged stillsuit +Each stillsuit armor piece has the same armor points (3/8/6/3), armor toughness (+3 per piece), and knockback resistance (+0.1 per piece) as vanilla netherite armor. Leather stillsuit pieces retain their faction dyes; vanilla leather durability is unchanged. + +`/dune elytra` or the main menu's **Winged Stillsuit Upgrade** merges the currently worn stillsuit chestplate with one Elytra from inventory for **1,000,000 Solaris**. The worn chestplate and Elytra are consumed and replaced with a real Elytra that has netherite chestplate defense and retains the `stillsuit` tag, allowing harvesting with the full suit. Elytra flight works normally. The winged chestpiece is an Elytra item and therefore cannot display the leather chestplate's faction dye without a resource pack. It uses a faction-colored display name instead. Existing armor needs reissuing with `/dune kit` to gain the new attributes. + +IMPORTANT: Code is source-only and not yet compiled or in-game tested. + +## Arrakis burning sun +Players on Arrakis without all four stillsuit pieces (including a winged stillsuit Elytra chestpiece) ignite visually when standing in direct daytime sunlight. A 300-second continuous exposure timer kills them when it expires. Shade beneath a solid roof, caves, night, rain, wearing a full stillsuit, and leaving Arrakis stop exposure and reset the timer. Creative/spectator players are exempt. The burning effect is visual during the countdown: fire-tick damage is suppressed while exposed, so the countdown lasts the configured five minutes. The timer is in memory and resets on restart. Configure `arrakis-sun` in config.yml. + +## Contrasting faction armor trims and Ordos homeworld +Each newly issued leather stillsuit piece receives a distinctive vanilla smithing armor trim, contrasting with its faction dye: + +| Faction | Base dye | Trim pattern | Trim material / visual color | +|---|---|---|---| +| Harkonnen | Red | Rib | Diamond / cyan | +| Ordos | Green | Sentry | Redstone / red | +| Atreides | Blue | Coast | Copper / orange | +| Corrino | Purple | Spire | Gold / yellow | +| Fremen | Orange | Dune | Lapis / blue | +| Spacing Guild (reserved) | Black | Eye | Quartz / white | + +Ordos now starts and respawns on its own generated planet `sigma_draconis_iv` (Sigma Draconis IV), instead of Arrakis or Caladan. The world is automatically generated using the project's existing generic world generator; custom biome/terrain styling for Sigma Draconis IV is not yet implemented. The Spacing Guild remains a non-playable faction and does not receive its own kit through normal gameplay. Existing armor is not automatically upgraded; issue a fresh kit. + +The trims are Minecraft's built-in vanilla patterns, not custom resource-pack models. This source has not been compiled or tested on Paper. + +## Proxy mode +See `NETWORK_SETUP.md` for the five-server Velocity topology, required per-server config, and critical shared-data limitations. diff --git a/DuneRealms-minecraft-only/SHARED_DATABASE_SETUP.md b/DuneRealms-minecraft-only/SHARED_DATABASE_SETUP.md new file mode 100644 index 00000000..4213e5a3 --- /dev/null +++ b/DuneRealms-minecraft-only/SHARED_DATABASE_SETUP.md @@ -0,0 +1,16 @@ +# Shared PostgreSQL network prototype + +Set `database.enabled: true` and identical JDBC settings on every Paper backend. Create a PostgreSQL database and user with schema privileges. The plugin creates `dune_players`, `dune_politics`, and `dune_bounties`. + +`SharedDatabase` stores faction, Solaris and serialized full player inventory (including armor/offhand) across planetary servers. `Politics` loads and writes the common political YAML state. Bounties are issued on smuggler water COLLECTION, not sale, on any planet; online players in that planet receive the alert. Player kills claim the bounty once through an atomic SQL UPDATE. + +**CRITICAL LIMITATIONS / NOT PRODUCTION READY** +- The politics YAML snapshot is NOT transactionally locked. Simultaneous votes/invasions from different servers can overwrite each other. Replace with normalized SQL tables and atomic transactions before public deployment. +- Player inventories are saved on quit and on `savePlayers()`. Concurrent sessions or a crashed backend can cause duplication or stale state. Implement proxy transfer handshakes, single-session leases, and atomic write/version checks. +- Database operations are synchronous on the Paper main thread. Move to async workers with safe main-thread inventory application. +- Smuggler career remains local-memory only; it must be persisted to shared storage. +- A water bucket on non-Arrakis worlds does not automatically become a tagged Arrakis water bucket and cannot be sold through the existing water seller mechanic. +- Bounty reward is based on ONE water bucket's smuggler gross proceeds, not total inventory; adjust for bulk smuggling contracts. +- Local NPC retaliation is immediate on collection; spawned Husks may be affected by local biome/daylight rules. +- The existing lobby routing and travel refund limitations remain. +- This source was not compiled or tested. Test against Paper 1.21.4 and PostgreSQL before deployment. diff --git a/DuneRealms-minecraft-only/build.gradle.kts b/DuneRealms-minecraft-only/build.gradle.kts new file mode 100644 index 00000000..e8c2a089 --- /dev/null +++ b/DuneRealms-minecraft-only/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { java } +group = "com.example" +version = "1.0.0" +repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") } +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + implementation("org.postgresql:postgresql:42.7.4") +} +tasks.jar { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + from(configurations.runtimeClasspath.get().map { if(it.isDirectory) it else zipTree(it) }) +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } diff --git a/DuneRealms-minecraft-only/settings.gradle.kts b/DuneRealms-minecraft-only/settings.gradle.kts new file mode 100644 index 00000000..a0ce7c12 --- /dev/null +++ b/DuneRealms-minecraft-only/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneRealms" diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ArrakisWater.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ArrakisWater.java new file mode 100644 index 00000000..0e4bff75 --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ArrakisWater.java @@ -0,0 +1,119 @@ +package com.example.dunerealms; + +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.block.*; +import org.bukkit.event.player.*; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.generator.*; +import java.util.*; + +/** Finite, naturally generated Arrakis water caches and two water-trading careers. */ +public final class ArrakisWater implements Listener { + private final DuneRealms plugin; + private final NamespacedKey waterKey; + private final Map careers = new HashMap<>(); + private final Map money; + private final Runnable save; + private final Politics politics; + ArrakisWater(DuneRealms plugin,Map money,Runnable save,Politics politics) { + this.plugin=plugin;this.money=money;this.save=save;this.politics=politics; + waterKey=new NamespacedKey(plugin,"finite_arrakis_water"); + } + private boolean arrakis(World w){return w.getName().equalsIgnoreCase("arrakis");} + public static final class SietchPopulator extends BlockPopulator { + @Override public void populate(WorldInfo world, Random random, int cx,int cz,LimitedRegion region) { + if(!world.getName().equalsIgnoreCase("arrakis") || random.nextInt(90)!=0)return; + int x=cx*16+4+random.nextInt(8), z=cz*16+4+random.nextInt(8); + int y=region.getHighestBlockYAt(x,z); + if(y<65 || y>world.getMaxHeight()-12 || y-12=-9 && dy<=-5 && Math.abs(dx)<=3 && Math.abs(dz)<=3; + if(cave)region.setType(ax,ay,az,dy<=-8?Material.WATER:Material.AIR); + else if(dy>=0 && dy<=3 && Math.abs(dx)<=3 && Math.abs(dz)<=3) { + boolean wall=Math.abs(dx)==3 || Math.abs(dz)==3 || dy==3; + region.setType(ax,ay,az,wall?Material.SANDSTONE:Material.AIR); + } + } + // A marked entrance and ladder descending to the water chamber. + for(int dy=-7;dy<=2;dy++){ + if(region.isInRegion(x,y+dy,z))region.setType(x,y+dy,z,Material.AIR); + if(region.isInRegion(x+1,y+dy,z))region.setType(x+1,y+dy,z,Material.LADDER); + } + if(region.isInRegion(x,y+4,z))region.setType(x,y+4,z,Material.ORANGE_BANNER); + } + } + private boolean tagged(ItemStack i){return i!=null && i.hasItemMeta() && i.getItemMeta().getPersistentDataContainer().has(waterKey,PersistentDataType.BYTE);} + @EventHandler public void onFill(PlayerBucketFillEvent e){ + if(!arrakis(e.getBlockClicked().getWorld()))return; + Block water=e.getBlockClicked().getRelative(e.getBlockFace()); + if(water.getType()!=Material.WATER || !(water.getBlockData() instanceof org.bukkit.block.data.Levelled level) || level.getLevel()!=0)return; + // Vanilla consumes the source block; turn the resulting bucket into a saleable, tagged item. + ItemStack result=new ItemStack(Material.WATER_BUCKET);ItemMeta m=result.getItemMeta(); + m.setDisplayName(ChatColor.AQUA+"Arrakis Water - Finite Source"); + m.getPersistentDataContainer().set(waterKey,PersistentDataType.BYTE,(byte)1); + result.setItemMeta(m);e.setItemStack(result); + } + @EventHandler public void onFlow(BlockFromToEvent e){ + if(arrakis(e.getBlock().getWorld()) && e.getBlock().getType()==Material.WATER)e.setCancelled(true); + } + @EventHandler public void onPlace(PlayerBucketEmptyEvent e){ + if(arrakis(e.getBlock().getWorld()) && e.getBucket()==Material.WATER_BUCKET){e.setCancelled(true);e.getPlayer().sendMessage(ChatColor.RED+"Water cannot be placed on Arrakis. Every natural source is finite.");} + } + @EventHandler public void onIce(BlockFormEvent e){if(arrakis(e.getBlock().getWorld()) && (e.getNewState().getType()==Material.ICE || e.getNewState().getType()==Material.SNOW))e.setCancelled(true);} + @EventHandler public void onCauldron(org.bukkit.event.block.CauldronLevelChangeEvent e){if(arrakis(e.getBlock().getWorld()) && e.getNewState().getType()==Material.WATER_CAULDRON)e.setCancelled(true);} + public void command(Player p,String[] args){ + if(args.length<2){p.sendMessage(ChatColor.AQUA+"/dune water guild|smuggler|sell|status");return;} + String mode=args[1].toLowerCase(Locale.ROOT); + if(mode.equals("guild")||mode.equals("smuggler")){ + careers.put(p.getUniqueId(),mode);p.sendMessage(ChatColor.GREEN+"Water career selected: "+mode);return; + } + if(mode.equals("status")){p.sendMessage("Water career: "+careers.getOrDefault(p.getUniqueId(),"guild")+". Water is worth half of spice; smuggling pays +45% with local retaliation risk.");return;} + if(!mode.equals("sell")){p.sendMessage("/dune water guild|smuggler|sell|status");return;} + int count=0; + for(ItemStack item:p.getInventory().getStorageContents())if(tagged(item))count+=item.getAmount(); + if(count==0){p.sendMessage(ChatColor.RED+"You have no collected Arrakis water buckets.");return;} + int spice=plugin.getConfig().getInt("spice-sell-price",100); + int base=Math.max(1,spice/2); + boolean appointed=politics.isAuthorizedWater(plugin.factionOf(p)); + boolean smuggler=!appointed; + int gross=(int)Math.round(count*base*(smuggler?1.45:1.0)); + if(smuggler)plugin.reportSmuggling(p,"WATER",gross); + int levy=politics.levy(p.getUniqueId(),gross); + for(int i=0;i=plugin.getConfig().getDouble("arrakis-water.smuggler-retaliation-chance",0.30))return; + int spice=plugin.getConfig().getInt("spice-sell-price",100); + int profit=(int)Math.round(Math.max(1,spice/2)*1.45); + String world=p.getWorld().getName(); + try{ + if(plugin.sharedDatabase()!=null)plugin.sharedDatabase().issueBounty(p.getUniqueId(),world,profit); + else p.sendMessage(ChatColor.RED+"Bounty tracking requires shared database."); + }catch(Exception ex){plugin.getLogger().warning("Could not issue bounty: "+ex.getMessage());return;} + for(Player local:p.getWorld().getPlayers()) + local.sendMessage(ChatColor.RED+"WATER SMUGGLER ACTIVE: "+p.getName()+"! Bounty: "+profit+" Solaris. Hunt them down!"); + for(int i=0;i<2;i++){ + Location at=p.getLocation().clone().add((Math.random()-.5)*8,0,(Math.random()-.5)*8); + try{Husk hostile=p.getWorld().spawn(at,Husk.class); + hostile.setCustomName(ChatColor.RED+"Angry Local");hostile.setTarget(p); + }catch(Exception ignored){} + } + } +} diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java new file mode 100644 index 00000000..0a6076cc --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java @@ -0,0 +1,136 @@ +package com.example.dunerealms; + +import org.bukkit.*; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.java.JavaPlugin; +import java.io.File; +import java.util.*; + +/** Data-driven chest GUI with allowlisted actions; never executes arbitrary console commands. */ +final class ConfigurableGui { + private final DuneRealms plugin; + private final ServerJobs serverJobs; + private final Map money; + private final Map jobs; + private final String[] planets, factions; + private final Map selected; + private YamlConfiguration config; + private final Map opened = new HashMap<>(); + private final Map> actions = new HashMap<>(); + + ConfigurableGui(DuneRealms plugin, ServerJobs serverJobs, Map money, + Map jobs, String[] planets, String[] factions, Map selected) { + this.plugin=plugin; this.serverJobs=serverJobs; this.money=money; this.jobs=jobs; + this.planets=planets; this.factions=factions; this.selected=selected; + if(!new File(plugin.getDataFolder(),"gui.yml").exists()) plugin.saveResource("gui.yml",false); + reload(); + } + void reload() { config=YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(),"gui.yml")); } + private String color(String input) { return ChatColor.translateAlternateColorCodes('&',input); } + private String replace(String text, Player p) { + return color(text.replace("%player%",p.getName()) + .replace("%balance%",String.valueOf(money.getOrDefault(p.getUniqueId(),0))) + .replace("%travel_cost%",String.valueOf(plugin.getConfig().getInt("travel-price",100))) + .replace("%active_job%",serverJobs.activeDescription(p))); + } + private ItemStack item(Player p, String icon, String title, List lore) { + Material material=Material.matchMaterial(icon.toUpperCase(Locale.ROOT)); + if(material==null || !material.isItem()) material=Material.PAPER; + ItemStack stack=new ItemStack(material); + ItemMeta meta=stack.getItemMeta(); + meta.setDisplayName(replace(title,p)); + meta.setLore(lore.stream().map(line->replace(line,p)).toList()); + stack.setItemMeta(meta); return stack; + } + void open(Player p,String page) { + ConfigurationSection section=config.getConfigurationSection("menus."+page); + if(section==null) { p.sendMessage(ChatColor.RED+"Unknown GUI page: "+page); return; } + int size=section.getInt("size",54); + if(size<9 || size>54 || size%9!=0) { plugin.getLogger().warning("Invalid GUI size for "+page); return; } + String title=replace(section.getString("title","Dune | "+page),p); + Inventory inv=Bukkit.createInventory(null,size,title); + // Fill the inventory first; interactive icons are placed on top. + ConfigurationSection backgrounds=config.getConfigurationSection("backgrounds"); + if(backgrounds!=null && config.getBoolean("menus."+page+".faction-background",true)) { + String faction=selected.getOrDefault(p.getUniqueId(),""); + String key=faction.toLowerCase(Locale.ROOT); + String icon=backgrounds.getString(key,backgrounds.getString("default","GRAY_STAINED_GLASS_PANE")); + for(int i=0;i slots=new HashMap<>(); + ConfigurationSection items=section.getConfigurationSection("items"); + if(items!=null) for(String id:items.getKeys(false)) { + String path=id+"."; + int slot=items.getInt(path+"slot",-1); + if(slot<0 || slot>=size) continue; + inv.setItem(slot,item(p,items.getString(path+"icon","PAPER"),items.getString(path+"name",id),items.getStringList(path+"lore"))); + slots.put(slot,items.getString(path+"action","none")); + } + ConfigurationSection dynamic=section.getConfigurationSection("dynamic"); + if(dynamic!=null) { + String type=dynamic.getString("type",""); + List ids=new ArrayList<>(); + if(type.equals("server_jobs")) ids.addAll(serverJobs.offerIds()); + if(type.equals("factions")) ids.addAll(Arrays.asList(factions)); + if(type.equals("planets")) ids.addAll(Arrays.asList(planets)); + int start=dynamic.getInt("start-slot",10), step=Math.max(1,dynamic.getInt("step",1)), max=Math.min(54,dynamic.getInt("max-items",27)); + for(int i=0;i=size || slots.containsKey(slot)) continue; + String id=ids.get(i); + String label=type.equals("server_jobs")?serverJobs.describe(id):id; + String name=dynamic.getString("name","&e%id%").replace("%id%",id); + List lore=dynamic.getStringList("lore").stream().map(line->line.replace("%description%",label).replace("%id%",id)).toList(); + String icon=dynamic.getString("icon","PAPER"); + if(type.equals("factions")) { + String key=id.toLowerCase(Locale.ROOT); + icon=config.getString("backgrounds."+key,icon); + + } + inv.setItem(slot,item(p,icon,name,lore)); + slots.put(slot,dynamic.getString("action","none").replace("%id%",id).replace("%index%",String.valueOf(i))); + } + } + opened.put(p.getUniqueId(),page); + actions.put(p.getUniqueId(),slots); + p.openInventory(inv); + } + void click(InventoryClickEvent e) { + if(!(e.getWhoClicked() instanceof Player p)) return; + String page=opened.get(p.getUniqueId()); + if(page==null) return; + String title=config.getString("menus."+page+".title","Dune | "+page); + if(!e.getView().getTitle().equals(replace(title,p))) return; + e.setCancelled(true); + if(e.getClickedInventory()!=e.getView().getTopInventory()) return; + String action=actions.getOrDefault(p.getUniqueId(),Map.of()).get(e.getRawSlot()); + if(action==null || action.equals("none")) return; + // Defer inventory changes until after InventoryClickEvent. + Bukkit.getScheduler().runTask(plugin,()-> execute(p,action)); + } + void drag(InventoryDragEvent e) { + if(!(e.getWhoClicked() instanceof Player p)) return; + String page=opened.get(p.getUniqueId()); + if(page==null) return; + if(!e.getView().getTitle().equals(replace(config.getString("menus."+page+".title","Dune | "+page),p))) return; + if(e.getRawSlots().stream().anyMatch(slot->slot selected = new HashMap<>(); + private final Map money = new HashMap<>(); + private NamespacedKey itemKey, npcKey, wormKey, armorFactionKey; + private File dataFile; + private final Map jobs = new HashMap<>(); + private final Map activeWorkers = new HashMap<>(); + private record Job(UUID owner, int quota, int harvested) {} + private YamlConfiguration data; + private ServerJobs serverJobs; + private final Map sunExposureSeconds = new HashMap<>(); + private ConfigurableGui gui; + private Politics politics; + private SharedDatabase sharedDatabase; + public SharedDatabase sharedDatabase(){return sharedDatabase;} + public String factionOf(Player player){return selected.getOrDefault(player.getUniqueId(),"");} + public Map walletMap(){return money;} + public void persistPlayers(){savePlayers();} + private ArrakisWater arrakisWater; + + @Override public void onEnable() { + saveDefaultConfig(); itemKey = new NamespacedKey(this, "item"); npcKey = new NamespacedKey(this, "guild"); wormKey = new NamespacedKey(this, "sandworm"); armorFactionKey = new NamespacedKey(this, "armor_faction"); + 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", "")); money.put(id, data.getInt(key + ".solaris", 0)); + } catch (IllegalArgumentException ignored) { } + for (String id : data.getConfigurationSection("jobs") == null ? Set.of() : data.getConfigurationSection("jobs").getKeys(false)) { + try { + UUID owner = UUID.fromString(id); + int quota = data.getInt("jobs." + id + ".quota"); + int harvested = data.getInt("jobs." + id + ".harvested"); + if (quota > harvested) jobs.put(owner, new Job(owner, quota, harvested)); + } catch (IllegalArgumentException ignored) {} + } + if (!getConfig().getBoolean("network.enabled", true)) { + for (String name : planets) { + WorldCreator creator = new WorldCreator(name).environment(World.Environment.NORMAL).generator(new PlanetGenerator(name)); + World world = Bukkit.createWorld(creator); + if (world != null) { world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !name.equals("arrakis")); world.setTime(name.equals("giedi_prime") ? 18000 : 6000); } + } + } else { + String localPlanet = getConfig().getString("network.local-planet", "arrakis"); + if (!Arrays.asList(planets).contains(localPlanet)) throw new IllegalStateException("Invalid network.local-planet: " + localPlanet); + Bukkit.createWorld(new WorldCreator(localPlanet).environment(World.Environment.NORMAL).generator(new PlanetGenerator(localPlanet))); + getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + } + if(getConfig().getBoolean("database.enabled",false)) { + try { sharedDatabase=new SharedDatabase(this); } + catch(Exception ex){getLogger().severe("Shared database required but unavailable: "+ex.getMessage());getServer().getPluginManager().disablePlugin(this);return;} + } + politics = new Politics(this, selected, money, this::savePlayers, sharedDatabase); + arrakisWater = new ArrakisWater(this,money,this::savePlayers,politics); + Bukkit.getPluginManager().registerEvents(arrakisWater,this); + serverJobs = new ServerJobs(this, money, this::savePlayers); + serverJobs.load(); + Bukkit.getScheduler().runTaskTimer(this, this::checkArrakisSun, 20L, 20L); + Bukkit.getScheduler().runTaskTimer(this, this::applyFactionSetEffects, 20L, 20L); + gui = new ConfigurableGui(this, serverJobs, money, jobs, planets, factions, selected); + Objects.requireNonNull(getCommand("dune")).setExecutor(this); + Bukkit.getPluginManager().registerEvents(this, this); + Bukkit.getScheduler().runTaskTimer(this, this::spawnSandworms, 200L, 200L); + getLogger().info("DuneRealms enabled. Four worlds and Arrakis sandworms ready."); + } + @Override public void onDisable() { if(serverJobs!=null)serverJobs.save(); savePlayers(); } + private void savePlayers() { + if(sharedDatabase!=null){ + for(Player player:Bukkit.getOnlinePlayers())try{sharedDatabase.savePlayer(player,selected,money);} + catch(Exception ex){getLogger().severe("Shared save failed for "+player.getName()+": "+ex.getMessage());} + return; + } + for (UUID id : money.keySet()) { data.set(id + ".solaris", money.get(id)); data.set(id + ".faction", selected.getOrDefault(id, "")); } + data.set("jobs", null); + for (Job job : jobs.values()) { + data.set("jobs." + job.owner() + ".quota", job.quota()); + data.set("jobs." + job.owner() + ".harvested", job.harvested()); + } + try { data.save(dataFile); } catch (IOException ex) { getLogger().warning("Cannot save players: " + ex.getMessage()); } + } + private ItemStack custom(Material material, String name, String id) { + ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.GOLD + name); meta.getPersistentDataContainer().set(itemKey, PersistentDataType.STRING, id); + item.setItemMeta(meta); return item; + } + private boolean is(ItemStack item, String id) { return item != null && item.hasItemMeta() && id.equals(item.getItemMeta().getPersistentDataContainer().get(itemKey, PersistentDataType.STRING)); } + private ItemStack menuItem() { + ItemStack item = custom(Material.NETHER_STAR, "Dune Navigator", "menu_opener"); + ItemMeta meta = item.getItemMeta(); + meta.setLore(List.of(ChatColor.YELLOW + "Left or right click to open DuneRealms")); + item.setItemMeta(meta); + return item; + } + private void giveMenuItem(Player p) { + for (ItemStack item : p.getInventory().getContents()) if (is(item, "menu_opener")) return; + Map leftover = p.getInventory().addItem(menuItem()); + if (!leftover.isEmpty()) p.sendMessage(ChatColor.RED + "Your inventory is full. Use /dune menuitem later."); + } + @EventHandler public void onMenuItemUse(PlayerInteractEvent event) { + if (event.getHand() != EquipmentSlot.HAND) return; + Action action = event.getAction(); + if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK + && action != Action.LEFT_CLICK_AIR && action != Action.LEFT_CLICK_BLOCK) return; + if (!is(event.getItem(), "menu_opener")) return; + event.setCancelled(true); + gui.open(event.getPlayer(), "main"); + } + private Color factionArmorColor(String faction) { + return switch (faction.toLowerCase(Locale.ROOT)) { + case "harkonnen" -> Color.fromRGB(190, 35, 45); + case "fremen" -> Color.fromRGB(235, 125, 25); + case "ordos" -> Color.fromRGB(45, 155, 75); + case "spacing_guild", "guild" -> Color.fromRGB(20, 20, 20); + case "atreides" -> Color.fromRGB(45, 105, 210); + case "corrino" -> Color.fromRGB(135, 65, 180); + default -> Color.fromRGB(95, 83, 67); + }; + } + private void checkArrakisSun() { + if (!getConfig().getBoolean("arrakis-sun.enabled", true)) return; + int lethalSeconds = Math.max(1, getConfig().getInt("arrakis-sun.lethal-seconds", 300)); + int warningInterval = Math.max(1, getConfig().getInt("arrakis-sun.warning-interval-seconds", 30)); + for (Player player : Bukkit.getOnlinePlayers()) { + UUID id = player.getUniqueId(); + boolean exposed = player.getWorld().getName().equalsIgnoreCase("arrakis") + && player.getGameMode() != GameMode.CREATIVE + && player.getGameMode() != GameMode.SPECTATOR + && !player.isDead() + && !wearingStillsuit(player) + && player.getWorld().isClearWeather() + && player.getWorld().getTime() < 12300 + && player.getWorld().getHighestBlockYAt(player.getLocation()) <= player.getLocation().getBlockY(); + if (!exposed) { + // Taking shelter, reaching night, or putting on a stillsuit resets exposure. + if (sunExposureSeconds.remove(id) != null) player.setFireTicks(0); + continue; + } + int seconds = sunExposureSeconds.merge(id, 1, Integer::sum); + // The visible burning effect is cosmetic until the exposure timer expires. + player.setFireTicks(Math.max(player.getFireTicks(), 40)); + // Cancel fire damage from this cosmetic effect in the dedicated damage listener. + if (seconds == 1 || seconds % warningInterval == 0) { + player.sendMessage(ChatColor.RED + "Arrakis sun exposure: " + + Math.max(0, lethalSeconds - seconds) + " seconds until fatal heatstroke! Find shade or wear a stillsuit."); + } + if (seconds >= lethalSeconds) { + sunExposureSeconds.remove(id); + player.setHealth(0.0); + } + } + } + @EventHandler public void onSunDamage(org.bukkit.event.entity.EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player player)) return; + if (event.getCause() != org.bukkit.event.entity.EntityDamageEvent.DamageCause.FIRE_TICK) return; + if (sunExposureSeconds.containsKey(player.getUniqueId())) event.setCancelled(true); + } + private void applyNetheriteStats(ItemMeta meta, String piece) { + // Match vanilla netherite armor points, toughness and knockback resistance. + double armor = switch(piece) { + case "HELMET" -> 3.0; + case "CHESTPLATE" -> 8.0; + case "LEGGINGS" -> 6.0; + default -> 3.0; + }; + EquipmentSlotGroup slot = switch(piece) { + case "HELMET" -> EquipmentSlotGroup.HEAD; + case "CHESTPLATE" -> EquipmentSlotGroup.CHEST; + case "LEGGINGS" -> EquipmentSlotGroup.LEGS; + default -> EquipmentSlotGroup.FEET; + }; + meta.addAttributeModifier(Attribute.ARMOR, + new AttributeModifier(new NamespacedKey(this,"stillsuit_armor_"+piece.toLowerCase(Locale.ROOT)), + armor, AttributeModifier.Operation.ADD_NUMBER, slot)); + meta.addAttributeModifier(Attribute.ARMOR_TOUGHNESS, + new AttributeModifier(new NamespacedKey(this,"stillsuit_toughness_"+piece.toLowerCase(Locale.ROOT)), + 3.0, AttributeModifier.Operation.ADD_NUMBER, slot)); + meta.addAttributeModifier(Attribute.KNOCKBACK_RESISTANCE, + new AttributeModifier(new NamespacedKey(this,"stillsuit_knockback_"+piece.toLowerCase(Locale.ROOT)), + 0.1, AttributeModifier.Operation.ADD_NUMBER, slot)); + } + private void mergeElytra(Player p) { + final int price=1_000_000; + if(money.getOrDefault(p.getUniqueId(),0) { pattern = TrimPattern.RIB; material = TrimMaterial.DIAMOND; } + case "ordos" -> { pattern = TrimPattern.SENTRY; material = TrimMaterial.REDSTONE; } + case "atreides" -> { pattern = TrimPattern.COAST; material = TrimMaterial.COPPER; } + case "corrino" -> { pattern = TrimPattern.SPIRE; material = TrimMaterial.GOLD; } + case "fremen" -> { pattern = TrimPattern.DUNE; material = TrimMaterial.LAPIS; } + case "spacing_guild", "guild" -> { pattern = TrimPattern.EYE; material = TrimMaterial.QUARTZ; } + default -> { pattern = TrimPattern.DUNE; material = TrimMaterial.LAPIS; } + } + armorMeta.setTrim(new ArmorTrim(material, pattern)); + } + private void kit(Player p) { + String faction = selected.getOrDefault(p.getUniqueId(), "Fremen"); + Color armorColor = factionArmorColor(faction); + ItemStack shovel=custom(Material.NETHERITE_SHOVEL,"Spice Harvest Shovel","shovel"); + shovel.addUnsafeEnchantment(Enchantment.EFFICIENCY,5); + shovel.addUnsafeEnchantment(Enchantment.UNBREAKING,3); + p.getInventory().addItem(shovel); + for (Material m : new Material[]{Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS}) { + ItemStack armor = custom(m, "Stillsuit " + m.name().toLowerCase(Locale.ROOT), "stillsuit"); + org.bukkit.inventory.meta.LeatherArmorMeta meta = (org.bukkit.inventory.meta.LeatherArmorMeta) armor.getItemMeta(); + meta.setColor(armorColor); + meta.setDisplayName(ChatColor.GOLD + faction + " Stillsuit " + m.name().replace("LEATHER_", "").toLowerCase(Locale.ROOT)); + applyNetheriteStats(meta,m.name().replace("LEATHER_","")); + applyFactionTrim(meta,faction); + meta.getPersistentDataContainer().set(armorFactionKey,PersistentDataType.STRING,faction.toLowerCase(Locale.ROOT)); + if(faction.equalsIgnoreCase("Fremen")) { + meta.addEnchant(Enchantment.UNBREAKING,3,true); + if(m==Material.LEATHER_LEGGINGS)meta.addEnchant(Enchantment.SWIFT_SNEAK,3,true); + } + if(faction.equalsIgnoreCase("Corrino"))meta.addEnchant(Enchantment.PROTECTION,3,true); + armor.setItemMeta(meta); + p.getInventory().addItem(armor); + } + } + private String fullSetFaction(Player player) { + String faction=selected.getOrDefault(player.getUniqueId(),"").toLowerCase(Locale.ROOT); + if(faction.isEmpty())return ""; + ItemStack[] armor=player.getInventory().getArmorContents(); + if(armor.length!=4)return ""; + for(ItemStack piece:armor) { + if(!is(piece,"stillsuit"))return ""; + String tagged=piece.getItemMeta().getPersistentDataContainer().get(armorFactionKey,PersistentDataType.STRING); + if(!faction.equals(tagged))return ""; + } + // The chest slot may hold either the stillsuit chestplate or a merged winged stillsuit. + return faction; + } + private void applyFactionSetEffects() { + for(Player p:Bukkit.getOnlinePlayers()) { + String faction=fullSetFaction(p); + if(faction.equals("harkonnen")) + p.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH,25,1,true,false,true)); + // No permanent potion refresh: the attribute is removed immediately when the set breaks. + var health=p.getAttribute(Attribute.MAX_HEALTH); + if(health!=null) { + NamespacedKey key=new NamespacedKey(this,"atreides_full_set_hearts"); + AttributeModifier existing=null; + for(AttributeModifier modifier:health.getModifiers()) + if(modifier.getKey().equals(key)){existing=modifier;break;} + if(existing!=null && !faction.equals("atreides")) { + health.removeModifier(existing); + if(p.getHealth()>health.getValue())p.setHealth(health.getValue()); + } else if(existing==null && faction.equals("atreides")) + health.addModifier(new AttributeModifier(key,8.0,AttributeModifier.Operation.ADD_NUMBER)); + } + } + } + @EventHandler public void onOrdosPearl(org.bukkit.event.player.PlayerInteractEvent e) { + Player p=e.getPlayer(); + if(!fullSetFaction(p).equals("ordos"))return; + if(e.getHand()!=EquipmentSlot.HAND)return; + if(e.getAction()!=Action.RIGHT_CLICK_AIR && e.getAction()!=Action.RIGHT_CLICK_BLOCK)return; + ItemStack held=e.getItem(); + if(held==null||held.getType()!=Material.ENDER_PEARL)return; + // Trigger on activation; vanilla pearl throw remains intact. + p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY,100,0,true,false,true)); + p.sendMessage(ChatColor.DARK_GREEN+"Shadow Step: invisible for five seconds."); + } + private boolean wearingStillsuit(Player p) { + for (ItemStack armor : p.getInventory().getArmorContents()) if (!is(armor, "stillsuit")) return false; + return true; + } + private boolean emperorSanctioned(Player p,String planet) { + return planet.equalsIgnoreCase("arrakis") && politics.isSpiceSteward(selected.getOrDefault(p.getUniqueId(),"")); + } + public void reportSmuggling(Player p,String commodity,int bounty) { + if(sharedDatabase==null){p.sendMessage(ChatColor.RED+"Smuggling bounty unavailable without shared PostgreSQL.");return;} + try { + sharedDatabase.issueBounty(p.getUniqueId(),p.getWorld().getName(),Math.max(1,bounty)); + for(Player witness:p.getWorld().getPlayers()) + witness.sendMessage(ChatColor.RED+commodity+" SMUGGLING: "+p.getName()+ + " is wanted! Bounty: "+Math.max(1,bounty)+" Solaris."); + }catch(Exception ex){getLogger().severe("Smuggling bounty failure: "+ex.getMessage());} + } + private void checkArrakisArrival(Player p) { + if(!p.getWorld().getName().equalsIgnoreCase("arrakis"))return; + if(sharedDatabase==null){getLogger().warning("Arrakis smuggler arrival enforcement requires PostgreSQL.");return;} + try { + if(politics.isSpiceSteward(selected.getOrDefault(p.getUniqueId(),"")))return; + if(sharedDatabase.consumeArrakisPermit(p.getUniqueId()))return; + int bounty=Math.max(1,(int)Math.round(Math.max(1,getConfig().getInt("spice-sell-price",100)/2.0)*1.45)); + sharedDatabase.issueBounty(p.getUniqueId(),"arrakis",bounty); + for(Player local:p.getWorld().getPlayers())local.sendMessage(ChatColor.RED+ + "UNSANCTIONED ARRIVAL ON ARRAKIS: "+p.getName()+" is wanted for smuggling! Bounty: "+bounty+" Solaris."); + p.sendMessage(ChatColor.RED+"Your arrival was not sanctioned by the Emperor. You are wanted on Arrakis!"); + }catch(Exception ex){getLogger().severe("Arrakis travel authorization failed: "+ex.getMessage());p.kickPlayer("Arrival authorization unavailable. Please reconnect.");} + } + private void teleport(Player p, String planet) { + if (!Arrays.asList(planets).contains(planet)) { p.sendMessage(ChatColor.RED + "Unknown planet."); return; } + if (getConfig().getBoolean("network.enabled", true)) { + String local = getConfig().getString("network.local-planet", "arrakis"); + if (planet.equals(local)) { p.sendMessage(ChatColor.YELLOW + "You are already on " + planet); return; } + String target = getConfig().getString("network.servers." + planet); + if (target == null || target.isBlank()) { p.sendMessage(ChatColor.RED + "Planet server not configured."); return; } + try { + // Only the current Steward of Dune has legal spice travel privileges. + if(emperorSanctioned(p,planet)) { + if(sharedDatabase==null){p.sendMessage(ChatColor.RED+"Emperor-sanctioned travel requires shared database.");return;} + sharedDatabase.issueArrakisPermit(p.getUniqueId(),System.currentTimeMillis()+120000L); + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream data = new DataOutputStream(bytes); + data.writeUTF("Connect"); data.writeUTF(target); + p.sendPluginMessage(this, "BungeeCord", bytes.toByteArray()); + p.sendMessage(ChatColor.AQUA + "Spacing Guild transfer requested: " + planet); + } catch (IOException ex) { getLogger().warning("Proxy transfer failed: " + ex.getMessage()); } + return; + } + World w = Bukkit.getWorld(planet); if (w == null) { p.sendMessage("World unavailable."); return; } + int y = w.getHighestBlockYAt(0, 0) + 2; + p.teleport(new Location(w, 0.5, Math.max(y, 66), 0.5)); + if(planet.equals("arrakis"))Bukkit.getScheduler().runTaskLater(this,()->checkArrakisArrival(p),1L); + p.sendMessage(ChatColor.AQUA + "Spacing Guild arrival: " + planet); + } + private boolean isLocalPlanet(String planet) { + return !getConfig().getBoolean("network.enabled", true) + || planet.equals(getConfig().getString("network.local-planet", "arrakis")); + } + private void travelMenu(Player p) { + Inventory inv = Bukkit.createInventory(null, 9, "Spacing Guild Travel"); + for (int i = 0; i < planets.length; i++) inv.setItem(i, custom(Material.ENDER_PEARL, planets[i] + " - " + getConfig().getInt("travel-price") + " Solaris", "travel:" + planets[i])); + p.openInventory(inv); + } + @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { + if (!(sender instanceof Player p)) { sender.sendMessage("Run this command in-game."); return true; } + if (args.length == 0) { gui.open(p, "main"); return true; } + if (args[0].equalsIgnoreCase("help")) { + p.sendMessage(ChatColor.GOLD + "/dune choose , kit, balance, sell, water, travel, politics, exchange, serverjobs, serverjobs accept , job post , job accept , job finish, guildnpc (admin)"); return true; + } + switch (args[0].toLowerCase(Locale.ROOT)) { + case "choose" -> { + if (args.length < 2) { p.sendMessage("Choose a faction name."); break; } + String choice = args[1]; + String match = Arrays.stream(factions).filter(f -> f.equalsIgnoreCase(choice)).findFirst().orElse(null); + if (match == null) { p.sendMessage("Unknown faction."); break; } + if (selected.containsKey(p.getUniqueId()) && !selected.get(p.getUniqueId()).isEmpty() && !p.hasPermission("dune.admin")) { p.sendMessage("Faction already selected."); break; } + selected.put(p.getUniqueId(), match); money.putIfAbsent(p.getUniqueId(), 0); savePlayers(); kit(p); teleport(p, planets[Arrays.asList(factions).indexOf(match)]); + p.sendMessage(ChatColor.GREEN + "You joined " + match + "!"); + } + 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); + case "water" -> arrakisWater.command(p,args); + case "balance" -> p.sendMessage(ChatColor.YELLOW + "Solaris: " + money.getOrDefault(p.getUniqueId(), 0)); + case "sell" -> { + int amount = 0; + for (ItemStack stack : p.getInventory().getStorageContents()) if (is(stack, "spice")) { amount += stack.getAmount(); stack.setAmount(0); } + if(amount>0 && !politics.isAuthorizedSpice(selected.getOrDefault(p.getUniqueId(),""))) { + reportSmuggling(p,"SPICE",amount*getConfig().getInt("spice-sell-price")); + } + int gross = amount * getConfig().getInt("spice-sell-price"); int tax = politics.levy(p.getUniqueId(), gross); int earned = gross - tax; money.merge(p.getUniqueId(), earned, Integer::sum); savePlayers(); + p.sendMessage(ChatColor.GOLD + "Sold " + amount + " spice for " + earned + " Solaris ("+tax+" deposited into Spacing Trust)."); + } + case "travel" -> travelMenu(p); + case "menu", "gui" -> gui.open(p, "main"); + case "guireload" -> { if (p.hasPermission("dune.admin")) { gui.reload(); p.sendMessage("GUI configuration reloaded."); } else p.sendMessage("Admin only."); } + case "menuitem" -> { giveMenuItem(p); p.sendMessage(ChatColor.GREEN + "Dune Navigator ready."); } + 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 "givespice" -> { if (p.hasPermission("dune.admin")) p.getInventory().addItem(custom(Material.ORANGE_DYE, "Melange Spice", "spice")); } + default -> p.sendMessage("Use /dune help"); + } + return true; + } + void runGuiCommand(Player p, String command) { + String[] args = command.trim().split("\\s+"); + if (args.length == 0 || args[0].isEmpty()) return; + if (args[0].equalsIgnoreCase("travel") && args.length == 2) { + String world = args[1].toLowerCase(Locale.ROOT); + if (!Arrays.asList(planets).contains(world)) return; + int cost = (world.equals("arrakis") && politics.isSpiceSteward(selected.getOrDefault(p.getUniqueId(),""))) ? 0 : getConfig().getInt("travel-price", 100); + if (money.getOrDefault(p.getUniqueId(), 0) < cost) { p.sendMessage(ChatColor.RED+"Not enough Solaris."); return; } + money.merge(p.getUniqueId(), -cost, Integer::sum); + savePlayers(); teleport(p, world); return; + } + onCommand(p, Objects.requireNonNull(getCommand("dune")), "dune", args); + } + @EventHandler public void onGuiClick(InventoryClickEvent e) { gui.click(e); } + @EventHandler public void onGuiDrag(org.bukkit.event.inventory.InventoryDragEvent e) { gui.drag(e); } + private void showExchange(Player p) { + p.sendMessage(ChatColor.GOLD + "=== Spice Exchange (15% worker / 85% sponsor) ==="); + if (jobs.isEmpty()) { p.sendMessage("No jobs listed. Use /dune job post ."); return; } + for (Job j : jobs.values()) { + String name = Bukkit.getOfflinePlayer(j.owner()).getName(); + p.sendMessage(ChatColor.YELLOW + (name == null ? j.owner() : name) + ": " + (j.quota()-j.harvested()) + " spice remaining; /dune job accept " + (name == null ? j.owner() : name)); + } + } + private void jobCommand(Player p, String[] args) { + if (args.length < 2) { showExchange(p); return; } + UUID id = p.getUniqueId(); + switch (args[1].toLowerCase(Locale.ROOT)) { + case "post" -> { + if (args.length < 3) { p.sendMessage("/dune job post "); return; } + int quota; + try { quota = Integer.parseInt(args[2]); } catch (NumberFormatException ex) { p.sendMessage("Enter a number."); return; } + if (quota < 1 || quota > 100000) { p.sendMessage("Quota must be 1–100000."); return; } + if (jobs.containsKey(id)) { p.sendMessage("Finish or cancel your current listing first."); return; } + jobs.put(id, new Job(id, quota, 0)); savePlayers(); + p.sendMessage(ChatColor.GREEN + "Exchange listing posted for " + quota + " spice."); + } + case "cancel" -> { + if (!jobs.containsKey(id)) { p.sendMessage("No listing to cancel."); return; } + if (activeWorkers.containsValue(id)) { p.sendMessage("A worker has accepted your job."); return; } + jobs.remove(id); savePlayers(); p.sendMessage("Listing cancelled."); + } + case "accept" -> { + if (activeWorkers.containsKey(id)) { p.sendMessage("You already have a job."); return; } + if (args.length < 3) { p.sendMessage("/dune job accept "); return; } + Job job = jobs.values().stream().filter(j -> { + String name = Bukkit.getOfflinePlayer(j.owner()).getName(); + return j.owner().toString().equalsIgnoreCase(args[2]) || (name != null && name.equalsIgnoreCase(args[2])); + }).findFirst().orElse(null); + if (job == null || job.owner().equals(id)) { p.sendMessage("Invalid listing."); return; } + if (activeWorkers.containsValue(job.owner())) { p.sendMessage("That job is already taken."); return; } + activeWorkers.put(id, job.owner()); + p.sendMessage(ChatColor.GREEN + "Job accepted! Harvest spice on Arrakis. Earnings are automatically split 15/85."); + teleport(p, "arrakis"); + } + case "finish" -> { + if (activeWorkers.remove(id) == null) { p.sendMessage("No active job."); return; } + p.sendMessage("You left the spice job."); + } + default -> showExchange(p); + } + } + @EventHandler(priority=org.bukkit.event.EventPriority.LOWEST) public void loadNetworkPlayer(PlayerJoinEvent e) { + if(sharedDatabase==null)return; + try{sharedDatabase.loadPlayer(e.getPlayer(),selected,money); + if(getConfig().getString("network.local-planet","arrakis").equalsIgnoreCase("arrakis")) + Bukkit.getScheduler().runTaskLater(this,()->{if(e.getPlayer().isOnline())checkArrakisArrival(e.getPlayer());},5L); + } + catch(Exception ex){getLogger().severe("Shared player load failed: "+ex.getMessage());e.getPlayer().kickPlayer("Your network profile could not be loaded.");} + } + @EventHandler public void onNetworkQuit(org.bukkit.event.player.PlayerQuitEvent e) { + if(sharedDatabase!=null)try{sharedDatabase.savePlayer(e.getPlayer(),selected,money);} + catch(Exception ex){getLogger().severe("Shared player save failed: "+ex.getMessage());} + } + @EventHandler public void onBountyKill(org.bukkit.event.entity.PlayerDeathEvent e) { + Player victim=e.getEntity(), killer=victim.getKiller(); + if(killer==null||killer.equals(victim)||sharedDatabase==null)return; + try { + int reward=sharedDatabase.claimBounty(victim.getUniqueId(),killer.getUniqueId()); + if(reward>0){money.merge(killer.getUniqueId(),reward,Integer::sum);savePlayers(); + Bukkit.broadcastMessage(ChatColor.GOLD+killer.getName()+" claimed "+reward+" Solaris bounty on "+victim.getName()+"!");} + }catch(Exception ex){getLogger().warning("Bounty claim failed: "+ex.getMessage());} + } + @EventHandler public void onJoin(PlayerJoinEvent e) { + Player p = e.getPlayer(); + Bukkit.getScheduler().runTask(this, () -> giveMenuItem(p)); + if (!selected.containsKey(p.getUniqueId()) || selected.get(p.getUniqueId()).isEmpty()) p.sendMessage(ChatColor.GOLD + "Choose your faction with /dune choose ."); + else Bukkit.getScheduler().runTask(this, () -> { + if (p.getWorld().getName().equals("world")) teleport(p, planets[Arrays.asList(factions).indexOf(selected.get(p.getUniqueId()))]); + }); + } + @EventHandler public void onRespawn(PlayerRespawnEvent e) { + String faction = selected.get(e.getPlayer().getUniqueId()); + if (faction == null) return; + int index = Arrays.asList(factions).indexOf(faction); + if (index < 0) return; + World w = Bukkit.getWorld(planets[index]); + if (w != null) e.setRespawnLocation(new Location(w, 0.5, Math.max(66, w.getHighestBlockYAt(0,0)+2), 0.5)); + } + @EventHandler public void onNpc(PlayerInteractEntityEvent e) { + if (e.getRightClicked().getPersistentDataContainer().has(npcKey, PersistentDataType.BYTE)) { e.setCancelled(true); travelMenu(e.getPlayer()); } + } + @EventHandler public void onMenu(InventoryClickEvent e) { + if (!e.getView().getTitle().equals("Spacing Guild Travel")) return; + e.setCancelled(true); if (!(e.getWhoClicked() instanceof Player p)) return; + ItemStack clicked = e.getCurrentItem(); if (clicked == null || !clicked.hasItemMeta()) return; + String id = clicked.getItemMeta().getPersistentDataContainer().get(itemKey, PersistentDataType.STRING); + if (id == null || !id.startsWith("travel:")) return; + String planet = id.substring(7); int cost = getConfig().getInt("travel-price"); + if (money.getOrDefault(p.getUniqueId(), 0) < cost) { p.sendMessage(ChatColor.RED + "You need " + cost + " Solaris."); return; } + money.merge(p.getUniqueId(), -cost, Integer::sum); savePlayers(); p.closeInventory(); teleport(p, planet); + } + @EventHandler public void onSpice(BlockBreakEvent e) { + Block block = e.getBlock(); if (!block.getWorld().getName().equals("arrakis") || block.getType() != Material.RED_SAND) return; + Player p = e.getPlayer(); if (!is(p.getInventory().getItemInMainHand(), "shovel") || !wearingStillsuit(p)) { + e.setCancelled(true); p.sendMessage(ChatColor.RED + "Wear a full stillsuit and use a Netherite Spice Harvest Shovel to extract spice."); return; + } + e.setDropItems(false); e.setExpToDrop(0); + int amount = selected.getOrDefault(p.getUniqueId(), "").equals("Fremen") ? 2 : 1; + serverJobs.harvest(p, amount); + UUID sponsor = activeWorkers.get(p.getUniqueId()); + if (sponsor != null) { + Job job = jobs.get(sponsor); + if (job == null) activeWorkers.remove(p.getUniqueId()); + else { + int credited = Math.min(amount, job.quota() - job.harvested()); + int unitPrice = getConfig().getInt("spice-sell-price", 100); + // Pay in whole Solaris with exact 15/85 split over accumulated earnings. + int oldValue = job.harvested() * unitPrice; + int newValue = (job.harvested() + credited) * unitPrice; + int workerPay = (int)((newValue * 15L) / 100 - (oldValue * 15L) / 100); + money.merge(p.getUniqueId(), workerPay, Integer::sum); + money.merge(sponsor, credited * unitPrice - workerPay, Integer::sum); + int progress = job.harvested() + credited; + if (progress >= job.quota()) { + jobs.remove(sponsor); activeWorkers.remove(p.getUniqueId()); + p.sendMessage(ChatColor.GREEN + "Spice contract completed!"); + } else jobs.put(sponsor, new Job(sponsor, job.quota(), progress)); + savePlayers(); + p.sendMessage(ChatColor.GOLD + "Job spice: +" + workerPay + " Solaris (15% share)."); + // Contract spice is sold automatically, not dropped as a second payout. + if (credited == amount) return; + amount -= credited; + } + } + block.getWorld().dropItemNaturally(block.getLocation(), custom(Material.ORANGE_DYE, "Melange Spice", "spice").asQuantity(amount)); + Location loc = block.getLocation(); long delay = 20L * getConfig().getLong("spice-respawn-seconds", 120); + Bukkit.getScheduler().runTaskLater(this, () -> { if (loc.getChunk().isLoaded() && loc.getBlock().getType() == Material.AIR) loc.getBlock().setType(Material.RED_SAND); }, delay); + } + private boolean isWorm(Entity entity) { + return entity.getPersistentDataContainer().has(wormKey, PersistentDataType.BYTE); + } + private void spawnSandworms() { + if (!getConfig().getBoolean("sandworms.enabled", true)) return; + World world = Bukkit.getWorld("arrakis"); + if (world == null) return; + int max = Math.max(0, getConfig().getInt("sandworms.max-per-world", 12)); + int count = (int) world.getEntitiesByClass(Husk.class).stream().filter(this::isWorm).count(); + Random rng = java.util.concurrent.ThreadLocalRandom.current(); + for (Player player : world.getPlayers()) { + if (count >= max) break; + if (rng.nextDouble() > getConfig().getDouble("sandworms.spawn-chance", 0.35)) continue; + boolean nearby = world.getNearbyEntities(player.getLocation(), 48, 32, 48).stream().anyMatch(this::isWorm); + if (nearby) continue; + double angle = rng.nextDouble() * Math.PI * 2; + int distance = 22 + rng.nextInt(19); + int x = player.getLocation().getBlockX() + (int) (Math.cos(angle) * distance); + int z = player.getLocation().getBlockZ() + (int) (Math.sin(angle) * distance); + int y = world.getHighestBlockYAt(x, z); + Material surface = world.getBlockAt(x, y, z).getType(); + if (surface != Material.SAND && surface != Material.RED_SAND) continue; + Location location = new Location(world, x + 0.5, y + 1, z + 0.5); + Husk worm = world.spawn(location, Husk.class, h -> { + h.getPersistentDataContainer().set(wormKey, PersistentDataType.BYTE, (byte) 1); + h.setCustomName(ChatColor.GOLD + "Shai-Hulud | Sandworm"); + h.setCustomNameVisible(true); + h.setRemoveWhenFarAway(true); + h.setAdult(); + h.setCanPickupItems(false); + h.getAttribute(Attribute.MAX_HEALTH).setBaseValue(getConfig().getDouble("sandworms.health", 500.0)); + h.setHealth(h.getAttribute(Attribute.MAX_HEALTH).getValue()); + h.getAttribute(Attribute.ATTACK_DAMAGE).setBaseValue(getConfig().getDouble("sandworms.attack-damage", 30.0)); + h.getAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(0.33); + h.getAttribute(Attribute.SCALE).setBaseValue(3.5); + h.setTarget(player); + }); + world.spawnParticle(Particle.CLOUD, location, 45, 2, 1, 2, 0.1); + world.playSound(location, Sound.ENTITY_WARDEN_ROAR, 2f, 0.6f); + count++; + } + } + @EventHandler public void onWormTarget(EntityTargetLivingEntityEvent e) { + if (isWorm(e.getEntity()) && (!(e.getTarget() instanceof Player) || !e.getEntity().getWorld().getName().equals("arrakis"))) e.setCancelled(true); + } + @EventHandler public void onWormTeleport(EntityTeleportEvent e) { + if (isWorm(e.getEntity()) && e.getTo() != null && !e.getTo().getWorld().getName().equals("arrakis")) e.setCancelled(true); + } + @EventHandler public void onWormDeath(EntityDeathEvent e) { + if (isWorm(e.getEntity())) { + e.getDrops().clear(); e.setDroppedExp(0); + generateWormSpiceField(e.getEntity().getLocation()); + } + } + private void generateWormSpiceField(Location center) { + World w = center.getWorld(); + if (w == null || !w.getName().equals("arrakis")) return; + int price = Math.max(1, getConfig().getInt("spice-sell-price", 100)); + int target = Math.max(1, (int)Math.ceil(100000.0 / price)); + int placed = 0; + int radius = Math.max(8, (int)Math.ceil(Math.sqrt(target / Math.PI)) + 5); + Random random = java.util.concurrent.ThreadLocalRandom.current(); + for (int dx = -radius; dx <= radius && placed < target; dx++) + for (int dz = -radius; dz <= radius && placed < target; dz++) { + if (dx*dx + dz*dz > radius*radius || random.nextDouble() > 0.85) continue; + int x = center.getBlockX()+dx, z = center.getBlockZ()+dz; + int y = w.getHighestBlockYAt(x,z); + Block b = w.getBlockAt(x,y,z); + if (b.getType() == Material.SAND || b.getType() == Material.RED_SAND) { + b.setType(Material.RED_SAND); + placed++; + } + } + w.strikeLightningEffect(center); + Bukkit.broadcastMessage(ChatColor.GOLD + "Shai-Hulud has fallen! A spice bloom has appeared on Arrakis (" + placed + " deposits, up to " + (placed * price) + " Solaris at base yield)."); + } + @EventHandler public void onCombat(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Player p && selected.getOrDefault(p.getUniqueId(), "").equals("Harkonnen")) e.setDamage(e.getDamage() * 1.15); + if (e.getEntity() instanceof Player p && selected.getOrDefault(p.getUniqueId(), "").equals("Corrino")) e.setDamage(e.getDamage() * 0.85); + } + @EventHandler public void onMove(org.bukkit.event.player.PlayerMoveEvent e) { + Player p = e.getPlayer(); if (p.getTicksLived() % 100 != 0) return; + String faction = selected.getOrDefault(p.getUniqueId(), ""); + if (faction.equals("Atreides")) p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 130, 0, true, false)); + if (faction.equals("Fremen") && p.getWorld().getName().equals("arrakis")) p.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 130, 0, true, false)); + } + private static class PlanetGenerator extends ChunkGenerator { + private final String planet; + PlanetGenerator(String planet) { this.planet = planet; } + @Override public List getDefaultPopulators(World world) { + return planet.equals("arrakis") ? List.of(new ArrakisWater.SietchPopulator()) : List.of(); + } + @Override public void generateNoise(WorldInfo world, Random random, int chunkX, int chunkZ, ChunkData data) { + int sea = 63; + for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) { + int gx = chunkX * 16 + x, gz = chunkZ * 16 + z; + double n = Math.sin(gx * .018) * Math.cos(gz * .021) + Math.sin(gx * .057 + gz * .029) * .4; + int h = switch (planet) { + case "arrakis" -> 70 + (int)(n * 12); + case "giedi_prime" -> 66 + (int)(n * 9); + case "kaitain" -> 75 + (int)(n * 7); + default -> 55 + (int)(n * 17); + }; + data.setBlock(x, world.getMinHeight(), z, Material.BEDROCK); + Material core = planet.equals("giedi_prime") ? Material.DEEPSLATE : Material.STONE; + for (int y = world.getMinHeight() + 1; y < h - 4; y++) data.setBlock(x, y, z, core); + for (int y = h - 4; y <= h; y++) { + Material surface = switch (planet) { + case "arrakis" -> random.nextInt(12) == 0 ? Material.RED_SAND : Material.SAND; + case "giedi_prime" -> random.nextInt(8) == 0 ? Material.COAL_BLOCK : Material.BLACKSTONE; + case "kaitain" -> y == h ? Material.GRASS_BLOCK : Material.DIRT; + default -> y == h ? Material.GRASS_BLOCK : Material.DIRT; + }; + data.setBlock(x, y, z, surface); + } + if (planet.equals("caladan") && h < sea) for (int y = h + 1; y <= sea; y++) data.setBlock(x, y, z, Material.WATER); + } + } + @Override public BiomeProvider getDefaultBiomeProvider(WorldInfo worldInfo) { + return new BiomeProvider() { + @Override public Biome getBiome(WorldInfo info, int x, int y, int z) { + return switch (planet) { case "arrakis" -> Biome.DESERT; case "giedi_prime" -> Biome.BADLANDS; case "kaitain" -> Biome.PLAINS; default -> Biome.OCEAN; }; + } + @Override public List getBiomes(WorldInfo info) { return List.of(getBiome(info, 0, 64, 0)); } + }; + } + } +} diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/Politics.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/Politics.java new file mode 100644 index 00000000..1c49e45e --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/Politics.java @@ -0,0 +1,179 @@ +package com.example.dunerealms; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +import java.io.File; +import java.io.IOException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; + +/** + * Prototype political systems. Persistent locally; deploy a shared transactional database + * before enabling elections or treasury spending across multiple backend servers. + */ +public final class Politics { + private final JavaPlugin plugin; + private final Map factions; + private final Map wallets; + private final Runnable saveWallets; + private final File file; + private final SharedDatabase database; + private final YamlConfiguration state; + private static final String[] HOUSES={"Fremen","Harkonnen","Corrino","Atreides","Ordos"}; + + public Politics(JavaPlugin plugin, Map factions, Map wallets, Runnable saveWallets, SharedDatabase database) { + this.plugin=plugin; this.factions=factions; this.wallets=wallets; this.saveWallets=saveWallets;this.database=database; + file=new File(plugin.getDataFolder(),"politics.yml"); + state=YamlConfiguration.loadConfiguration(file); + refresh(); + } + private long week() { return Instant.now().truncatedTo(ChronoUnit.DAYS).getEpochSecond()/604800; } + private void refresh(){ + if(database==null)return; + try{ + YamlConfiguration latest=new YamlConfiguration(); + latest.loadFromString(database.loadPolitics()); + for(String key:new HashSet<>(state.getKeys(false)))state.set(key,null); + for(String key:latest.getKeys(false))state.set(key,latest.get(key)); + }catch(Exception e){plugin.getLogger().severe("Politics refresh failed: "+e.getMessage());} + } + private void save() { + try { + if(database!=null)database.savePolitics(state.saveToString()); + else state.save(file); + }catch(Exception e){plugin.getLogger().warning("Politics save failed: "+e.getMessage());} + } + private boolean house(String h) { return Arrays.stream(HOUSES).anyMatch(x->x.equalsIgnoreCase(h)); } + private String canon(String h) { return Arrays.stream(HOUSES).filter(x->x.equalsIgnoreCase(h)).findFirst().orElse(null); } + private String faction(Player p) { return factions.getOrDefault(p.getUniqueId(),""); } + private void msg(CommandSender s,String text) { s.sendMessage(ChatColor.GOLD+"[Dune Politics] "+ChatColor.WHITE+text); } + public synchronized int levy(UUID player,int gross) { + refresh(); + if (gross<=0) return 0; + int fee=(int)Math.ceil(gross*plugin.getConfig().getDouble("politics.trust-levy",0.0121)); + state.set("trust",state.getLong("trust")+fee); save(); + return fee; + } + /** The appointments expire automatically when a new election week or Emperor changes. */ + private boolean appointed(String key,String house) { + refresh(); + String emperorId=winnerId("votes.emperor."+week()); + return !emperorId.isBlank() + && state.getLong("appointments."+key+".week",-1)==week() + && emperorId.equals(state.getString("appointments."+key+".emperor","")) + && house.equalsIgnoreCase(state.getString("appointments."+key+".house","")); + } + public synchronized boolean isSpiceSteward(String house) { return appointed("steward",house); } + public synchronized boolean isHouseOfWater(String house) { return appointed("water",house); } + public synchronized boolean isAuthorizedSpice(String house) { return isSpiceSteward(house); } + public synchronized boolean isAuthorizedWater(String house) { return isHouseOfWater(house); } + public synchronized boolean freeArrakis(String house) { + refresh(); + return (isSpiceSteward(house) || isHouseOfWater(house)) + && house.equalsIgnoreCase(state.getString("edict.arrakis.house","")); + } + public synchronized boolean command(Player p,String[] args) { + refresh(); + if(args.length<2) { msg(p,"/dune politics status|deposit |vote |emperorvote |leader|invasion |defend|steward |houseofwater "); return true; } + String house=faction(p), op=args[1].toLowerCase(Locale.ROOT); + if(op.equals("status")) { + msg(p,"Spacing Trust: "+state.getLong("trust")+" Solaris | Election week: "+week()); + msg(p,"Your faction: "+house+" | Leader: "+leader(house)+" | Emperor: "+emperor()); + msg(p,"Steward of Dune: "+state.getString("appointments.steward.house","none")+" | House of Water: "+state.getString("appointments.water.house","none")); + msg(p,"Active invasion: "+state.getString("invasion.attacker","none")+" -> "+state.getString("invasion.defender","none")); + return true; + } + if(!house(house)) { msg(p,"Select a playable faction first."); return true; } + if(op.equals("deposit")) { + if(args.length<3) {msg(p,"Usage: /dune politics deposit ");return true;} + int amount; + try {amount=Integer.parseInt(args[2]);} catch(NumberFormatException e){msg(p,"Invalid amount.");return true;} + if(amount<=0 || wallets.getOrDefault(p.getUniqueId(),0)System.currentTimeMillis()){msg(p,"An invasion is already active.");return true;} + state.set("trust",state.getLong("trust")-cost); + state.set("invasion.attacker",house);state.set("invasion.defender",canon(args[2])); + state.set("invasion.until",System.currentTimeMillis()+plugin.getConfig().getLong("politics.invasion-minutes",60)*60000L); + state.set("invasion.defenses",0);save(); + plugin.getServer().broadcastMessage(ChatColor.RED+"INVASION: "+house+" attacks "+canon(args[2])+"! Defenders: /dune politics defend"); + return true; + } + if(op.equals("defend")) { + if(state.getLong("invasion.until",0)<=System.currentTimeMillis() || !house.equalsIgnoreCase(state.getString("invasion.defender",""))) {msg(p,"Your house has no active defense.");return true;} + String key="invasion.defenders."+p.getUniqueId(); + if(state.getBoolean(key)){msg(p,"You have already contributed to this defense.");return true;} + state.set(key,true);int defenses=state.getInt("invasion.defenses")+1;state.set("invasion.defenses",defenses); + if(defenses>=plugin.getConfig().getInt("politics.defenders-needed",5)) { + plugin.getServer().broadcastMessage(ChatColor.GREEN+house+" has repelled the invasion!"); + state.set("invasion.until",0); + state.set("invasion.defenders",null); + } + save();msg(p,"Defense contribution registered ("+defenses+").");return true; + } + if(op.equals("steward") || op.equals("houseofwater")) { + String emperorId=winnerId("votes.emperor."+week()); + if(emperorId.isBlank() || !p.getUniqueId().toString().equals(emperorId)) { + msg(p,"Only the elected Emperor can appoint houses.");return true; + } + if(args.length<3 || canon(args[2])==null) { + msg(p,"Choose a playable faction.");return true; + } + String key=op.equals("steward")?"steward":"water"; + String root="appointments."+key; + if(state.getLong(root+".week",-1)==week() && emperorId.equals(state.getString(root+".emperor",""))) { + msg(p,"This appointment has already been made during your term.");return true; + } + state.set(root+".house",canon(args[2])); + state.set(root+".week",week()); + state.set(root+".emperor",emperorId); + save(); + plugin.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"IMPERIAL APPOINTMENT: "+canon(args[2])+ + (key.equals("steward")?" is now Steward of Dune (legal spice rights).":" is now House of Water (legal water rights).")); + return true; + } + msg(p,"Unknown politics command.");return true; + } + private String winnerId(String prefix) { + String path=prefix+".tally"; + if(state.getConfigurationSection(path)==null)return ""; + String best="";int score=0; + for(String id:state.getConfigurationSection(path).getKeys(false)) { + int n=state.getInt(path+"."+id); + if(n>score || (n==score && id.compareTo(best)<0)){best=id;score=n;} + } + return best; + } + private String winnerName(String prefix) { + String id=winnerId(prefix); + return id.isEmpty()?"Not elected":state.getString(prefix+".names."+id,id); + } + public String leader(String house) {refresh();return winnerName("votes.house."+week()+"."+house);} + public String emperor() {refresh();return winnerName("votes.emperor."+week());} +} diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ServerJobs.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ServerJobs.java new file mode 100644 index 00000000..c71463af --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ServerJobs.java @@ -0,0 +1,161 @@ +package com.example.dunerealms; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import java.io.File; +import java.io.IOException; +import java.time.Instant; +import java.util.*; +import java.util.function.Consumer; + +/** Configurable hourly NPC-issued spice contracts; independent from player-sponsored jobs. */ +final class ServerJobs { + private record Template(String id, String title, int spiceRequired, int pay, long limitSeconds) {} + private record Active(String id, long acceptedAt, int harvested) {} + private final JavaPlugin plugin; + private final Map balances; + private final Runnable saveBalances; + private final Map templates = new LinkedHashMap<>(); + private final Map active = new HashMap<>(); + private final File stateFile; + private final File jobsFile; + private long rotationStart; + private List offers = new ArrayList<>(); + + ServerJobs(JavaPlugin plugin, Map balances, Runnable saveBalances) { + this.plugin=plugin; this.balances=balances; this.saveBalances=saveBalances; + stateFile=new File(plugin.getDataFolder(),"server-jobs-state.yml"); + jobsFile=new File(plugin.getDataFolder(),"server-jobs.yml"); + } + void load() { + if (!jobsFile.exists()) plugin.saveResource("server-jobs.yml",false); + reloadTemplates(); + YamlConfiguration y=YamlConfiguration.loadConfiguration(stateFile); + rotationStart=y.getLong("rotation-start",0); + offers=new ArrayList<>(y.getStringList("offers")); + ConfigurationSection section=y.getConfigurationSection("active"); + if(section!=null) for(String id:section.getKeys(false)) try { + UUID uuid=UUID.fromString(id); + active.put(uuid,new Active(y.getString("active."+id+".id",""),y.getLong("active."+id+".accepted-at"),y.getInt("active."+id+".harvested"))); + } catch(IllegalArgumentException ignored) {} + tick(); + Bukkit.getScheduler().runTaskTimer(plugin,this::tick,20L,20L*10); + } + private void reloadTemplates() { + templates.clear(); + YamlConfiguration y=YamlConfiguration.loadConfiguration(jobsFile); + ConfigurationSection section=y.getConfigurationSection("jobs"); + if(section==null) return; + for(String id:section.getKeys(false)) { + String key="jobs."+id+"."; + int required=y.getInt(key+"spice-required"); + int pay=y.getInt(key+"pay"); + long duration=y.getLong(key+"time-limit-minutes")*60L; + if(required<=0 || pay<=0 || duration<=0) { + plugin.getLogger().warning("Invalid server job: "+id); continue; + } + templates.put(id,new Template(id,y.getString(key+"title",id),required,pay,duration)); + } + } + private void tick() { + long now=Instant.now().getEpochSecond(); + long interval=3600; + long window=now/interval*interval; + if(rotationStart!=window) { + rotationStart=window; + reloadTemplates(); + List all=new ArrayList<>(templates.keySet()); + Collections.shuffle(all); + int count=Math.max(1,YamlConfiguration.loadConfiguration(jobsFile).getInt("offers-per-hour",3)); + offers=new ArrayList<>(all.subList(0,Math.min(count,all.size()))); + Bukkit.broadcastMessage(ChatColor.GOLD+"[CHOAM] New server spice contracts are available! /dune serverjobs"); + } + for(var entry:new ArrayList<>(active.entrySet())) { + Active job=entry.getValue(); + Template t=templates.get(job.id()); + if(t==null || now-job.acceptedAt()>=t.limitSeconds()) { + fail(entry.getKey(),job,t); + } + } + save(); + } + private void fail(UUID player,Active job,Template t) { + active.remove(player); + if(t==null) return; + int fine=(int)Math.ceil(t.pay()*0.05); + balances.merge(player,-fine,Integer::sum); // Negative balances represent debt. + saveBalances.run(); + Player online=Bukkit.getPlayer(player); + if(online!=null) online.sendMessage(ChatColor.RED+"CHOAM contract failed: "+t.title()+". Fine: "+fine+" Solaris (5% of pay)."); + } + void harvest(Player p,int amount) { + Active a=active.get(p.getUniqueId()); + if(a==null) return; + Template t=templates.get(a.id()); + if(t==null) return; + long now=Instant.now().getEpochSecond(); + if(now-a.acceptedAt()>=t.limitSeconds()) { fail(p.getUniqueId(),a,t); save(); return; } + int progress=Math.min(t.spiceRequired(),a.harvested()+amount); + if(progress>=t.spiceRequired()) { + active.remove(p.getUniqueId()); + balances.merge(p.getUniqueId(),t.pay(),Integer::sum); + saveBalances.run(); + p.sendMessage(ChatColor.GREEN+"CHOAM contract complete: "+t.title()+"! Paid "+t.pay()+" Solaris."); + } else active.put(p.getUniqueId(),new Active(a.id(),a.acceptedAt(),progress)); + save(); + } + List offerIds() { return List.copyOf(offers); } + String describe(String id) { + Template t=templates.get(id); + return t==null ? "Unavailable" : t.title()+" | "+t.spiceRequired()+" spice | "+t.pay()+" Solaris | "+(t.limitSeconds()/60)+" min | 5% failure fine"; + } + String activeDescription(Player p) { + Active a=active.get(p.getUniqueId()); + if(a==null) return "No active contract"; + Template t=templates.get(a.id()); + if(t==null) return "Contract no longer available"; + return t.title()+" | "+a.harvested()+"/"+t.spiceRequired()+" spice | "+Math.max(0,(a.acceptedAt()+t.limitSeconds()-Instant.now().getEpochSecond())/60)+" min left"; + } + void list(Player p) { + p.sendMessage(ChatColor.GOLD+"=== CHOAM Hourly Contracts ==="); + for(String id:offers) { + Template t=templates.get(id); if(t==null) continue; + p.sendMessage(ChatColor.YELLOW+id+" | "+t.title()+" | "+t.spiceRequired()+" spice | "+t.pay()+" Solaris | "+(t.limitSeconds()/60)+" min | failure fine "+(int)Math.ceil(t.pay()*0.05)+" Solaris"); + } + Active a=active.get(p.getUniqueId()); + if(a!=null) { + Template t=templates.get(a.id()); + if(t!=null) p.sendMessage(ChatColor.AQUA+"Active: "+t.title()+" "+a.harvested()+"/"+t.spiceRequired()+" spice, "+Math.max(0,(a.acceptedAt()+t.limitSeconds()-Instant.now().getEpochSecond())/60)+" min left"); + } + } + void command(Player p,String[] args) { + if(args.length<2) { list(p); return; } + if(args[1].equalsIgnoreCase("reload")) { + if(!p.hasPermission("dune.admin")) { p.sendMessage("Admin only."); return; } + reloadTemplates(); offers.removeIf(id->!templates.containsKey(id)); + p.sendMessage("Server job definitions reloaded; next rotation occurs at the next hour."); return; + } + if(!args[1].equalsIgnoreCase("accept") || args.length<3) { list(p); return; } + if(active.containsKey(p.getUniqueId())) { p.sendMessage("Finish your existing CHOAM contract first."); return; } + Template t=templates.get(args[2]); + if(t==null || !offers.contains(t.id())) { p.sendMessage("Job not available in the current rotation."); return; } + active.put(p.getUniqueId(),new Active(t.id(),Instant.now().getEpochSecond(),0)); + save(); + p.sendMessage(ChatColor.GREEN+"Accepted "+t.title()+". Complete within "+(t.limitSeconds()/60)+" minutes or pay a 5% fine."); + } + void save() { + YamlConfiguration y=new YamlConfiguration(); + y.set("rotation-start",rotationStart); y.set("offers",offers); + for(var e:active.entrySet()) { + String path="active."+e.getKey()+"."; + y.set(path+"id",e.getValue().id()); + y.set(path+"accepted-at",e.getValue().acceptedAt()); + y.set(path+"harvested",e.getValue().harvested()); + } + try { y.save(stateFile); } catch(IOException ex) { plugin.getLogger().warning("Cannot save CHOAM jobs: "+ex.getMessage()); } + } +} diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java new file mode 100644 index 00000000..1490e53d --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java @@ -0,0 +1,107 @@ +package com.example.dunerealms; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.bukkit.plugin.java.JavaPlugin; +import java.io.*; +import java.sql.*; +import java.util.*; +import java.util.Base64; + +/** PostgreSQL-backed network player state and shared politics state. */ +public final class SharedDatabase { + private final JavaPlugin plugin; + private final String url,user,password; + public SharedDatabase(JavaPlugin plugin) throws SQLException { + this.plugin=plugin; + url=plugin.getConfig().getString("database.jdbc-url",""); + user=plugin.getConfig().getString("database.username",""); + password=plugin.getConfig().getString("database.password",""); + if(url.isBlank())throw new SQLException("database.jdbc-url is required"); + try(Connection c=connect();Statement s=c.createStatement()){ + s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_players (uuid UUID PRIMARY KEY, faction TEXT NOT NULL DEFAULT '', solaris INTEGER NOT NULL DEFAULT 0, inventory TEXT)"); + s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_politics (id INTEGER PRIMARY KEY, yaml TEXT NOT NULL)"); + s.executeUpdate("INSERT INTO dune_politics (id,yaml) VALUES (1,'') ON CONFLICT (id) DO NOTHING"); + s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_arrakis_permits (player UUID PRIMARY KEY, expires_at BIGINT NOT NULL)"); + s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_bounties (target UUID PRIMARY KEY, world TEXT NOT NULL, reward INTEGER NOT NULL, claimed BOOLEAN NOT NULL DEFAULT FALSE, hunter UUID)"); + } + } + public Connection connect() throws SQLException {return DriverManager.getConnection(url,user,password);} + public void loadPlayer(Player p,Map factions,Map money) throws Exception { + try(Connection c=connect()){ + try(PreparedStatement ins=c.prepareStatement("INSERT INTO dune_players(uuid) VALUES (?) ON CONFLICT DO NOTHING")){ + ins.setObject(1,p.getUniqueId());ins.executeUpdate(); + } + try(PreparedStatement q=c.prepareStatement("SELECT faction,solaris,inventory FROM dune_players WHERE uuid=?")){ + q.setObject(1,p.getUniqueId()); + try(ResultSet r=q.executeQuery())if(r.next()){ + factions.put(p.getUniqueId(),r.getString(1));money.put(p.getUniqueId(),r.getInt(2)); + String blob=r.getString(3); + if(blob!=null && !blob.isBlank()){ + ItemStack[] contents=decode(blob); + p.getInventory().setContents(contents); + } + } + } + } + } + public void savePlayer(Player p,Map factions,Map money) throws Exception { + try(Connection c=connect();PreparedStatement q=c.prepareStatement( + "INSERT INTO dune_players(uuid,faction,solaris,inventory) VALUES(?,?,?,?) ON CONFLICT(uuid) DO UPDATE SET faction=EXCLUDED.faction,solaris=EXCLUDED.solaris,inventory=EXCLUDED.inventory")){ + q.setObject(1,p.getUniqueId());q.setString(2,factions.getOrDefault(p.getUniqueId(),"")); + q.setInt(3,money.getOrDefault(p.getUniqueId(),0));q.setString(4,encode(p.getInventory().getContents()));q.executeUpdate(); + } + } + public String loadPolitics() throws SQLException { + try(Connection c=connect();PreparedStatement q=c.prepareStatement("SELECT yaml FROM dune_politics WHERE id=1");ResultSet r=q.executeQuery()){ + return r.next()?r.getString(1):""; + } + } + public void savePolitics(String yaml) throws SQLException { + try(Connection c=connect();PreparedStatement q=c.prepareStatement("UPDATE dune_politics SET yaml=? WHERE id=1")){ + q.setString(1,yaml);q.executeUpdate(); + } + } + /** Short-lived, single-use authorization for an Emperor-approved arrival. */ + public void issueArrakisPermit(UUID player,long expiresAt) throws SQLException { + try(Connection c=connect();PreparedStatement q=c.prepareStatement( + "INSERT INTO dune_arrakis_permits(player,expires_at) VALUES (?,?) ON CONFLICT(player) DO UPDATE SET expires_at=EXCLUDED.expires_at")){ + q.setObject(1,player);q.setLong(2,expiresAt);q.executeUpdate(); + } + } + public boolean consumeArrakisPermit(UUID player) throws SQLException { + try(Connection c=connect();PreparedStatement q=c.prepareStatement( + "DELETE FROM dune_arrakis_permits WHERE player=? AND expires_at>? RETURNING player")){ + q.setObject(1,player);q.setLong(2,System.currentTimeMillis()); + try(ResultSet r=q.executeQuery()){return r.next();} + } + } + public void issueBounty(UUID target,String world,int reward) throws SQLException { + try(Connection c=connect();PreparedStatement q=c.prepareStatement( + "INSERT INTO dune_bounties(target,world,reward,claimed,hunter) VALUES(?,?,?,FALSE,NULL) ON CONFLICT(target) DO UPDATE SET world=EXCLUDED.world,reward=EXCLUDED.reward,claimed=FALSE,hunter=NULL")){ + q.setObject(1,target);q.setString(2,world);q.setInt(3,reward);q.executeUpdate(); + } + } + public int claimBounty(UUID target,UUID hunter) throws SQLException { + try(Connection c=connect();PreparedStatement q=c.prepareStatement( + "UPDATE dune_bounties SET claimed=TRUE,hunter=? WHERE target=? AND claimed=FALSE RETURNING reward")){ + q.setObject(1,hunter);q.setObject(2,target); + try(ResultSet r=q.executeQuery()){return r.next()?r.getInt(1):0;} + } + } + private String encode(ItemStack[] items) throws Exception { + ByteArrayOutputStream bytes=new ByteArrayOutputStream(); + try(BukkitObjectOutputStream out=new BukkitObjectOutputStream(bytes)){out.writeInt(items.length);for(ItemStack i:items)out.writeObject(i);} + return Base64.getEncoder().encodeToString(bytes.toByteArray()); + } + private ItemStack[] decode(String str) throws Exception { + try(BukkitObjectInputStream in=new BukkitObjectInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(str)))){ + int n=in.readInt();if(n<0||n>54)throw new IOException("Invalid inventory length"); + ItemStack[] items=new ItemStack[n];for(int i=0;i, dune:, close, none. +# Dynamic lists: server_jobs, factions, planets. +menus: + main: + title: "&6Dune | Main Menu" + size: 54 + items: + guild: + slot: 10 + icon: COMPASS + name: "&eSpacing Guild" + lore: ["&7Travel to another planet", "&7Fare: %travel_cost% Solaris"] + action: "open:travel" + choam: + slot: 12 + icon: EMERALD + name: "&eCHOAM Contracts" + lore: ["&7Hourly server jobs", "&7Failure fine: 5%"] + action: "open:serverjobs" + exchange: + slot: 14 + icon: WRITABLE_BOOK + name: "&ePlayer Spice Exchange" + lore: ["&7Worker receives 15%", "&7Sponsor receives 85%"] + action: "open:exchange" + wallet: + slot: 16 + icon: GOLD_INGOT + name: "&6Wallet: %balance% Solaris" + lore: ["&7Click to view balance"] + action: "dune:balance" + sell: + slot: 28 + icon: ORANGE_DYE + name: "&eSell Spice" + lore: ["&7Sell harvested spice"] + action: "dune:sell" + kit: + slot: 30 + icon: LEATHER_CHESTPLATE + name: "&eStillsuit Kit" + lore: ["&7Get a netherite spice shovel and armor"] + action: "dune:kit" + winged_stillsuit: + slot: 34 + icon: ELYTRA + name: "&dWinged Stillsuit Upgrade" + lore: + - "&7Merge worn chestplate with an Elytra" + - "&6Cost: 1,000,000 Solaris" + - "&7Wear stillsuit chestplate and carry Elytra" + action: "dune:elytra" + faction: + slot: 32 + icon: NETHER_STAR + name: "&eChoose Faction" + lore: ["&7Select your homeworld"] + action: "open:factions" + serverjobs: + title: "&6Dune | CHOAM Jobs" + size: 54 + items: + active: + slot: 49 + icon: CLOCK + name: "&eCurrent Contract" + lore: ["&7%active_job%"] + action: none + back: + slot: 53 + icon: ARROW + name: "&eBack" + action: "open:main" + dynamic: + type: server_jobs + start-slot: 10 + step: 1 + max-items: 27 + icon: PAPER + name: "&e%id%" + lore: ["&7%description%", "&aClick to accept"] + action: "dune:serverjobs accept %id%" + exchange: + title: "&6Dune | Player Exchange" + size: 54 + items: + server: + slot: 4 + icon: EMERALD + name: "&eServer Jobs" + action: "open:serverjobs" + post100: + slot: 45 + icon: PAPER + name: "&ePost 100 Spice" + action: "dune:job post 100" + post500: + slot: 46 + icon: PAPER + name: "&ePost 500 Spice" + action: "dune:job post 500" + post1000: + slot: 47 + icon: PAPER + name: "&ePost 1000 Spice" + action: "dune:job post 1000" + cancel: + slot: 48 + icon: BARRIER + name: "&cCancel Listing" + action: "dune:job cancel" + leave: + slot: 50 + icon: OAK_DOOR + name: "&eLeave Job" + action: "dune:job finish" + back: + slot: 53 + icon: ARROW + name: "&eBack" + action: "open:main" + travel: + title: "&6Dune | Guild Travel" + size: 54 + items: + back: + slot: 53 + icon: ARROW + name: "&eBack" + action: "open:main" + dynamic: + type: planets + start-slot: 10 + step: 2 + max-items: 4 + icon: ENDER_PEARL + name: "&eTravel to %id%" + lore: ["&7Fare: %travel_cost% Solaris"] + action: "dune:travel %id%" + factions: + title: "&6Dune | Factions" + size: 54 + items: + back: + slot: 53 + icon: ARROW + name: "&eBack" + action: "open:main" + dynamic: + type: factions + start-slot: 10 + step: 2 + max-items: 5 + icon: SHIELD + name: "&e%id%" + lore: ["&7Click to join %id%"] + action: "dune:choose %id%" diff --git a/DuneRealms-minecraft-only/src/main/resources/plugin.yml b/DuneRealms-minecraft-only/src/main/resources/plugin.yml new file mode 100644 index 00000000..194c8327 --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/resources/plugin.yml @@ -0,0 +1,12 @@ +name: DuneRealms +version: 1.0.0 +main: com.example.dunerealms.DuneRealms +api-version: '1.21' +description: Dune-inspired factions, spice, planets and Guild travel +commands: + dune: + description: Dune realms commands + usage: /dune help +permissions: + dune.admin: + default: op diff --git a/DuneRealms-minecraft-only/src/main/resources/server-jobs.yml b/DuneRealms-minecraft-only/src/main/resources/server-jobs.yml new file mode 100644 index 00000000..0538c6a0 --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/resources/server-jobs.yml @@ -0,0 +1,23 @@ +# CHOAM contracts rotate on the hour (server clock, UTC epoch boundaries). +offers-per-hour: 3 +jobs: + small-spice-run: + title: "Arrakis Spice Collection" + spice-required: 100 + pay: 3000 + time-limit-minutes: 30 + guild-supply: + title: "Spacing Guild Supply Order" + spice-required: 250 + pay: 8500 + time-limit-minutes: 45 + imperial-contract: + title: "Imperial Spice Shipment" + spice-required: 500 + pay: 20000 + time-limit-minutes: 60 + dangerous-harvest: + title: "Deep Desert Extraction" + spice-required: 800 + pay: 35000 + time-limit-minutes: 90