thomas patrick pearl
📎 1 file 7,881 chars
đź“„
pasted-code-1792437955293.txt
txt 67 lines
â–¶
Create a COMPLETE server-side Fabric mod for Minecraft 26.3 (Java 25, Fabric Loader >=0.19.5, Fabric API), from scratch. Mod id: empireclaims, name: "Empire Claims & Wars", package it.kodari.empireclaims. Only the server needs it (no client mod). ALL player-facing text must be in clear, simple ITALIAN, with colors (green = success, red = error, yellow = info) and a prefix like "[Impero]". Include /empire help listing every command, and tab-completion for every command and argument (empire names, online players, members).

=== EMPIRES ===
- /empire create  (3-24 chars, letters/numbers/_/-), invite , accept, deny, leave, kick , officer , demote , transfer  (give leadership), disband (leader only, with confirmation), rename , description  (leader only).
- Invitations expire after 2 minutes. Max members per empire: default 20 (config).
- Every member of the empire has full access to its claims (no trust system).
- /empire info [empire]: name, leader, officers, members (online green, offline gray), claims used / available, time left to the next extra claim, war or cooldown state, wins and losses. Without argument, show the player's own empire.
- /empire list (all empires with members and claims count), /empire top (ranking by claims and by war wins).
- Empire chat: /empire chat  and /empire chat toggle, visible only to members.
- Per-empire flags toggled by the leader: allow mob griefing, allow fire spread.

=== CLAIMS ===
- Claims are per chunk: /empire claim and /empire unclaim (leader and officers) on the chunk the player is standing in.
- New claims must touch an existing chunk of the same empire (except the first one). Configurable.
- Prevent claiming within a configurable radius of world spawn.
- How claims are earned: each empire starts with a base number of claims (default 5). Every hour of total playtime of its members adds claim capacity (default +1 per hour), up to a maximum (default 100). All in config. Track playtime per player.
- Protection in foreign claims: outsiders cannot break, attack, use blocks or containers, and cannot hurt animals/villagers, use item frames, paintings, armor stands, boats, minecarts. The message tells whose claim it is.
- Border protection: block pistons, water/lava, hoppers, dispensers and fire spread from crossing into a claim of a different empire. Configurable.
- Explosions are blocked in claims normally, but during an ACTIVE war they CAN destroy blocks inside the chunks involved in that war (configurable).
- Enter/leave messages on the action bar: "Territorio dell'impero X" / "Terra libera".
- Intruder alert: when a player of another empire enters a claim, online members of the owner get an action bar message "X è entrato nel tuo territorio".

=== BORDERS ===
- NO real blocks. Borders are GLOWING particles (END_ROD, ELECTRIC_SPARK or large colored DUST), sent only to the single player, visible from far away and at night.
- Adjacent chunks of the same empire are ONE territory: draw particles only on the OUTER perimeter, never on edges shared between two chunks of the same empire.
- Lines of particles at the player's height range (a few blocks above/below), only for chunks within ~3 chunks, refreshed every ~10 ticks.
- Shown only to players who enabled /empire borders (toggle), and automatically for 10 seconds after a claim/unclaim.
- Colors: green = own empire, red = enemy at war, yellow = other empires.
- /empire map: small chat map of the chunks around the player (own = green, other empires = red, free = gray, player position marked).

=== WARS ===
- /empire declare   (1-10080), only leader or officers. Fails if: it targets own empire, target has no claims, one of the empires is already in a war or preparation, cooldown is active, or the target has fewer than N members online (default 1, config).
- 24-hour preparation (config), then the war begins. The preparation timer pauses if the attacker has fewer than N members online.
- PvP is allowed only between the two empires at war, only inside the war chunks.
- Warn leader/officers when their empire is declared war on, and broadcast to the whole server at war start and end.
- /empire war status: current war, time left, cores alive and their health.
- When the war ends, show clear messages (conquests or not). Cooldown after the war: default 3 days for both empires (config), with a message that says which case happened.
- Boss bar at the top for members of the involved empires: "Preparazione guerra contro X: 05:12:30", "Guerra contro X: 00:45:10", "Cooldown guerre: 2g 4h". It disappears when nothing is active.

=== CLAIM CORES ===
- Every claimed chunk has exactly one core, ACTIVE ONLY DURING THE ACTIVE WAR (not in preparation, not in peace). When the war starts, each core appears as a real visible block (e.g. center of the chunk, on the surface, with a beacon-like particle effect). When the war ends, all cores disappear. Outside the war they do not exist.
- Only the ATTACKING empire can damage a core. Normal breaking is cancelled and a custom health system is used.
- Damage works ONLY with a PICKAXE (otherwise show "Serve un piccone"). Damage per hit depends on the pickaxe tier and Efficiency.
- Health scales with territory size: health = baseHealth + healthPerChunk * connectedChunks (adjacent chunks of the same empire). A single isolated chunk core must take about as long as mining 4 obsidian blocks in a row with a diamond pickaxe (~40 seconds); configurable (coreBaseSeconds, coreExtraSecondsPerChunk, maxCoreSeconds).
- Show core health to nearby attackers on a boss bar/action bar ("Cuore: 63%"), with damage particles and sound on each hit. Optional slow regeneration after 30 seconds without attacks (default off).
- When health reaches 0: the chunk becomes owned by the attacker, the core disappears, both empires get a message. If the attacker conquers all cores, the war ends early.
- Cores of chunks not conquered return to the defender unchanged when the war ends.

=== ADMIN COMMANDS (permission level 2, every action written in the admin log) ===
- /empire admin unclaim (chunk where the admin stands), unclaimall  (with confirmation), forceclaim  (ignores capacity and adjacency), delete  (with confirmation).
- /empire admin setclaims  , resetclaims .
- /empire admin startwar    [skipPreparation]: force a war immediately, ignoring cooldown, online and claims requirements.
- /empire admin endwar  [keepCooldown].
- /empire admin cooldown clear , cooldown set  .
- /empire admin setleader  , addmember  , removemember  .
- /empire admin info  (claims coordinates, war, cores, cooldown).
- /empire admin bypass (toggle build/break/open containers in any claim, shown on the action bar).
- /empire admin reload (reload config).

=== CONFIG, DATA, LOGS ===
- config/empireclaims.json with: base claims, claims per hour, max claims, war min/max duration, preparation hours, cooldown days, core health values, particle settings, spawn protection radius, max members, min online members for war.
- Save data in the world folder automatically every 5 minutes and after every important change, using a temp file + atomic replace so a crash never corrupts data.
- Log file logs/empireclaims.log with claims, unclaims, wars and conquests (date, player, empire, chunk).

DO NOT add: home/teleport commands, trust/untrust, surrender, alliances.

OUTPUT: a complete, compilable Gradle project (build.gradle, gradle.properties, fabric.mod.json, mixins json, all source files, all with clean commented code) with no compile errors. Explain how to build it with ./gradlew build.
Kodari AI
KodariOct 19 at 8:31 pm 9
EmpireClaimsPlugin
Comprehensive server-side Fabric mod enabling empire creation, territory claiming via chunks, and PvP warfare. Features include empire management with invitations, per-chunk claims with adjacency rules, glowing particle borders, claim cores with pickaxe-based damage, war preparation and cooldown timers, boss bars, and admin commands with permission levels. All player-facing text in Italian with color-coded messages.

Piano:

  1. Recupero dal sorgente 26.3 le firme Fabric e Minecraft necessarie per comandi, eventi, protezioni e feedback.

  2. Creo configurazione, persistenza atomica e modello dati per imperi, inviti, claim, guerre e cooldown.

  3. Implemento comandi italiani con permessi, completamento, protezioni territoriali, notifiche e registrazione.

  4. Aggiungo tick, confini particellari, gestione delle guerre e file Gradle/Fabric del progetto.

Ho creato il progetto Fabric server-side empireclaims per Minecraft 26.3, con configurazione, salvataggio atomico dei dati, comandi in italiano, gestione di imperi e claim, protezioni, confini particellari, guerre, cuori-beacon e mixin per le esplosioni.

La specifica non è ancora interamente coperta: le opzioni mob-griefing e fire-spread vengono salvate ma non applicate al mondo; pistoni, tramogge, erogatori e propagazione del fuoco non sono protetti ai confini; la protezione dalle esplosioni controlla il chunk d’origine, non tutti i blocchi raggiunti dall’esplosione. Non posso quindi presentarlo come implementazione completa, né attestare la compilazione senza una build.

Per compilare il progetto su Kodari: clicca Compile nella barra in alto, poi Compile nella finestra; se riesce, usa Download per ottenere il jar.

thomas patrick pearl
📎 1 file 5,193 chars
đź“„
pasted-code-1792499709027.txt
txt 50 lines
â–¶
Update the existing Empire Claims & Wars mod with ALL the changes below. Keep everything else exactly as it is. All player-facing text stays in clear Italian. At the end make sure the project compiles with no errors and give me the list of changed files.

=== 1. REMOVE completely (code, /empire help, tab-completion, config entries) ===
- /empire flag and the per-empire flags system. From now on mob griefing and fire spread inside claims are always blocked for everyone, except in chunks involved in an active war, where explosions and fire are allowed as already configured.
- /empire disband
- /empire map
- /empire transfer
- The old /empire declare command.

=== 2. WAR COMMANDS ===
- Group all war commands under /empire war:
  - /empire war declare  :  is in minutes and can ONLY be 30, 45 or 60. Any other value is refused with: "La durata deve essere 30, 45 o 60 minuti." Tab-completion suggests exactly 30, 45 and 60. If omitted, use warDefaultMinutes from config (default 30). Allowed values are in config as warAllowedMinutes.
  - /empire war status
- Remove the old 1-10080 minute range everywhere (help, tab-completion, usage messages, boss bar, broadcasts). Messages must show the chosen duration (e.g. "Guerra dichiarata: durata 45 minuti").
- The 24-hour preparation, cooldown and online-member rules stay as they are. Update every message that mentions the old command.

=== 3. ADMIN COMMANDS HIDDEN FROM PLAYERS ===
- Register /empire admin ... with a permission requirement (operator, permission level 2) on the "admin" literal itself, so normal players do not see it in tab-completion or suggestions and get no usage hints.
- /empire help shows admin commands only to operators.

=== 4. ADMIN WAR COMMANDS (operators only) ===
- /empire admin startwar   [duration]: start the war RIGHT NOW, no preparation, cores active immediately, with the normal boss bar and server broadcast. Duration can only be 30, 45 or 60 (default 30). Ignore cooldown, minimum online members and minimum claims; if one of the two empires is in preparation, cancel it and start the war. It fails only if an empire does not exist, they are the same empire, the defender has no claims, or one of them is already in an ACTIVE war (clear Italian message).
- /empire admin skipprep : if that empire has a war in preparation, end the preparation and start the war immediately, with the duration chosen at declaration.
- /empire admin endwar , /empire admin cooldown clear , /empire admin cooldown set   stay as they are.
- Write every admin action in the admin log. Tab-completion for empire names and durations.

=== 5. CLAIM CAPACITY (replaces all previous rules) ===
- Every empire starts with 6 claims (config: baseClaims = 6).
- War reward: when an empire wins a war as attacker by destroying at least one core, it gets +10 claim capacity (config: warWinBonusClaims = 10), once per war, given when the war ends, permanent. If no core is destroyed, no bonus. Message: "Il tuo impero ha ottenuto +10 claim per la vittoria in guerra".
- Playtime reward: +1 claim for every hour of playtime counted as the TOTAL of all members together (config: claimsPerHour = 1). Example: 3 members playing 1 hour each = +3 claims.
- Capacity = baseClaims + total playtime claims + (war wins * warWinBonusClaims) + manual admin bonus.
- Maximum capacity: config maxClaims (default 150).
- Chunks conquered in war count as used claims of the winner. Conquering is allowed even if the winner is over capacity (chunks are kept, but the empire cannot make new claims until it is back under capacity).
- If a member leaves or is kicked, the hours already played stay in the empire total.

=== 6. DAILY LIMIT ON PLAYTIME CLAIMS ===
- Claims earned from playtime are limited to a maximum of 10 per day per empire (config: maxPlaytimeClaimsPerDay = 10), using a rolling 24-hour window. When the limit is reached, stop giving playtime claims until the oldest ones leave the window. Playtime hours played while the limit is reached are NOT lost: keep counting them and give the claims as soon as the limit allows it.
- Save the playtime claims and their timestamps in the data file so the limit survives restarts.
- Message: "Hai raggiunto il limite di 10 claim al giorno dal tempo di gioco. Prossimo claim tra 05:12:30".
- The war win bonus is NOT affected by this limit, and the limit never removes claims already obtained.

=== 7. /empire info ===
- Show: "Claim: usati/disponibili", the breakdown (base, ore di gioco, vittorie in guerra), playtime claims received in the last 24 hours (e.g. "7/10"), and the time left until the next playtime claim.

=== 8. ADMIN CLAIM COMMANDS ===
- /empire admin setclaims   sets a manual bonus on top of the capacity; /empire admin resetclaims  removes it.
- /empire admin resetbonus  resets the daily playtime limit.

=== 9. CONFIG (config/empireclaims.json) ===
baseClaims, claimsPerHour, warWinBonusClaims, maxClaims, maxPlaytimeClaimsPerDay, warDefaultMinutes, warAllowedMinutes. Keep all other existing values.
Kodari AI
KodariOct 20 at 1:35 pm 9
  1. Rimuovo comandi e flag esclusi, aggiornando help e suggerimenti.

  2. Riordino dichiarazione e stato guerra e rendo i comandi admin invisibili ai non operatori.

  3. Aggiorno bonus/capacitĂ  claim, limite mobile giornaliero, info e comandi amministrativi.

  4. Allineo la configurazione mantenendo le altre opzioni e controllo le modifiche per gli errori di compilazione.

  1. Comandi rimossi e flag persistenti eliminati; le guerre passano sotto /empire war. Aggiungo ora bonus di capacitĂ , limite mobile giornaliero e relativo riepilogo/comandi admin.

Ho aggiornato i comandi guerra, nascosto /empire admin ai non operatori e rimosso flag, /empire disband, /empire map e /empire transfer. Ho aggiunto le durate configurabili 30/45/60, l’avvio e il salto della preparazione per gli admin, la nuova capacità claim con bonus di guerra e playtime, il limite mobile di 24 ore e /empire admin resetbonus. Mob griefing e propagazione del fuoco sono protetti nei claim fuori dalla guerra attiva.

File modificati

  • src/main/java/it/kodari/empireclaims/EmpireCommands.java

  • src/main/java/it/kodari/empireclaims/EmpireConfig.java

  • src/main/java/it/kodari/empireclaims/EmpireData.java

  • src/main/java/it/kodari/empireclaims/EmpireClaims.java

  • src/main/java/it/kodari/empireclaims/mixin/EntityTickMixin.java — nuovo

  • src/main/java/it/kodari/empireclaims/mixin/GameRulesMixin.java — nuovo

  • src/main/java/it/kodari/empireclaims/mixin/FireBlockMixin.java — nuovo

  • src/main/resources/empireclaims.mixins.json

Non ho un esito di compilazione da riportare. Per verificarla su Kodari, clicca Compile nella barra in alto (su telefono: ⋮ → Compile Project), poi Compile nella finestra. Se la build riesce, puoi scaricare il jar da lì.

thomas patrick pearl
📎 1 file 1,998 chars
đź“„
pasted-code-1792505366974.txt
txt 15 lines
â–¶
Update the Empire Claims & Wars mod with these two fixes. Keep everything else exactly as it is. Italian messages. Make sure the project compiles and give me the list of changed files.

- Right now PvP does not work outside the claims. The mod must only change PvP INSIDE claims.
- Outside any claim (unclaimed land): the mod does NOT interfere at all, PvP follows the normal server setting (pvp=true in server.properties means players can fight).
- Inside a claim (any empire), when there is NO active war involving that chunk: PvP is disabled (players cannot damage each other).
- Inside a claim, during an ACTIVE war, in the chunks involved in that war: PvP is allowed between the two empires at war only (as it already works).
- Fix the mixin/check that currently cancels the damage everywhere: it must cancel damage only when the attacker or the victim is inside a claimed chunk and the war condition is not satisfied. In unclaimed chunks it must always let the normal behavior pass.
- Check also arrows, tridents, potions and other indirect damage with the same rule.

=== 2. CLAIM CORE CHANGES ===
- The core can be damaged ONLY with a SWORD (any sword: wooden, stone, iron, golden, diamond, netherite). With a pickaxe, other tools or bare hands it does nothing and shows "Serve una spada". Remove the pickaxe rule and the Efficiency logic.
- Damage per hit = the attack damage of the sword (including Sharpness if present). Respect the normal attack cooldown, so spamming clicks with a weak swing does less damage.
- Every core has exactly 1000 health points, the same for every chunk (config: coreHealth = 1000). Remove the old formula based on territory size, baseHealth, healthPerChunk, coreBaseSeconds, coreExtraSecondsPerChunk and maxCoreSeconds.
- Keep: only the attacking empire can damage a core, boss bar/action bar with the core health, damage particles and sound, conquest at 0 health, cores only active during an active war.
- Update the texts and help that mention the pickaxe.
Kodari AI
KodariOct 20 at 2:09 pm 1
  1. PvP: trace claim/war checks for direct and indirect damage; allow vanilla PvP outside claims.

  2. Core: switch damage to sword attack damage with cooldown, fixed 1000 HP, and update Italian help/messages.

[Generation stopped]

thomas patrick pearl
📎 1 file 3,415 chars
đź“„
pasted-code-1792505577483.txt
txt 27 lines
â–¶
Update the Empire Claims & Wars mod with ALL the changes below. Keep everything else exactly as it is. All player-facing text stays in clear Italian. At the end make sure the project compiles with no errors and give me the list of changed files.

=== 1. PVP FIX ===
- Right now PvP does not work outside the claims. The mod must only change PvP INSIDE claims.
- Outside any claim (unclaimed land): the mod does NOT interfere at all. PvP follows the normal server setting (pvp=true in server.properties means players can fight).
- Inside a claim (any empire), when there is NO active war involving that chunk: PvP is disabled (players cannot damage each other).
- Inside a claim, during an ACTIVE war, in the chunks involved in that war: PvP is allowed between the two empires at war only (as it already works).
- Fix the mixin/check that currently cancels damage everywhere: it must cancel damage only when the attacker or the victim is inside a claimed chunk and the war condition is not satisfied. In unclaimed chunks it must always let the normal behavior pass.
- Apply the same rule to arrows, tridents, potions and other indirect damage.

=== 2. CLAIM CORES: SWORD AND HEALTH ===
- The core can be damaged ONLY with a SWORD (wooden, stone, iron, golden, diamond, netherite). With a pickaxe, other tools or bare hands it does nothing and shows "Serve una spada". Remove the pickaxe rule and the Efficiency logic.
- Damage per hit = the attack damage of the sword (including Sharpness if present). Respect the normal attack cooldown, so spamming clicks with weak swings does less damage.
- Chunks of the same empire that touch each other (sharing an edge, not diagonal) form ONE connected territory.
- The health of EVERY core in that territory = 1000 * number of chunks in the connected territory. Examples: 1 isolated chunk = 1000, 2 connected chunks = 2000 (each of the two cores has 2000), 3 connected = 3000.
- Each chunk still has its own core, and destroying a core conquers ONLY that chunk.
- Calculate the health when the war starts (cores spawn with the value of that moment). During the war the value does not change, even if chunks are conquered.
- Config: coreHealthPerChunk = 1000 and maxCoreHealth = 10000 (cap). Remove the old formula and the config entries baseHealth, healthPerChunk, coreBaseSeconds, coreExtraSecondsPerChunk, maxCoreSeconds and coreHealth.
- Show the real value on the boss bar/action bar (example: "Cuore: 1200/2000").
- Keep: only the attacking empire can damage a core, damage particles and sound, conquest at 0 health, cores active only during an active war.
- Update every text and /empire help entry that mentions the pickaxe.

=== 3. PROTECTION DURING WARS ===
- During an active war, the claims of the attacked empire stay FULLY PROTECTED: attackers and everyone who is not a member cannot break, place or use blocks and containers inside those claims. The only things allowed in war are: PvP between the two empires in the war chunks, and attacking the cores with a sword.
- Explosions (TNT, creepers, end crystals, beds, etc.) can NEVER destroy blocks inside any claim, not even during a war. Remove the old rule that allowed explosions in war chunks, and remove its config option.
- Fire spread, pistons, fluids and all other protections stay active during wars too.
- Members of the empire keep full access to their own claims, as always.
Kodari AI
KodariOct 20 at 2:45 pm 6
  1. Fix PvP checks for claimed versus unclaimed chunks, including indirect damage.

  2. Update core weapons, cooldown-aware damage, connected-territory health, and Italian help/config.

  3. Keep claims protected during wars, remove explosion exceptions, then report changed files.

Implemented the PvP, core, and wartime protection changes.

  • Unclaimed land now follows the server’s normal PvP setting. Claimed-territory PvP still requires an active war and the appropriate war chunk; attributed arrow, trident, and potion damage uses the same check.

  • Cores now require a sword. Damage uses sword attack damage, Sharpness, and attack cooldown. Core maximum health is based on connected claims at war start, capped by the new config values; health displays numerically, and help text is updated.

  • Removed the wartime explosion exception. Explosions are blocked in claimed chunks and their affected-block lists exclude claimed blocks even when the explosion starts outside a claim. Fire protection remains active during wars; block placement and piston movement are also protected at claim boundaries, while same-empire piston movement remains allowed.

Changed files

  • src/main/java/it/kodari/empireclaims/EmpireClaims.java

  • src/main/java/it/kodari/empireclaims/EmpireConfig.java

  • src/main/java/it/kodari/empireclaims/EmpireCommands.java

  • src/main/java/it/kodari/empireclaims/mixin/ServerExplosionMixin.java

  • src/main/java/it/kodari/empireclaims/mixin/ClaimedBlockItemMixin.java (new)

  • src/main/java/it/kodari/empireclaims/mixin/DoubleHighBlockItemMixin.java (new)

  • src/main/java/it/kodari/empireclaims/mixin/PistonBaseBlockMixin.java (new)

  • src/main/resources/empireclaims.mixins.json

The project’s automatic compile verification will check the changes; no compile error has been reported here.

thomas patrick pearl

Update the Empire Claims & Wars mod with ALL the changes below. Keep everything else exactly as it is. All player-facing text stays in clear Italian. At the end make sure the project compiles with no errors and give me the list of changed files.

=== 1. FLUIDS FIX ===

  • Water and lava inside claims currently stop flowing and stay frozen in one block. Fix it.
  • The fluid protection must block a fluid ONLY when it tries to flow from one place into a block of a DIFFERENT owner. Cancel the flow only if the source block and the destination block belong to different territories (different empires, or unclaimed land flowing into a claim, or a claim flowing into another empire's claim).
  • Fluids must flow NORMALLY inside the same claim, between two chunks of the same empire, and in unclaimed land. Do not block, tick-cancel or freeze fluids in any of these cases.
  • Check also that buckets, dispensers, pistons and fluid spreading from sources placed by members work normally inside their own claims.
  • Keep blocking pistons, hoppers, dispensers and fire spread only when they cross into a different empire's claim.

=== 2. CLAIMS CAN BE FAR FROM EACH OTHER ===

  • Remove the rule that a new claim must touch an existing chunk of the same empire. Empires can claim any free chunk, even far away from their other claims, as long as they have available claims.
  • Remove the related config option and the related error message.
  • Everything else about claiming stays: capacity, spawn radius, no claiming chunks owned by other empires.
  • Chunks that touch each other still form one connected territory for borders and for core health. Separate groups of chunks are separate territories, each with its own outer border and its own core health.

=== 3. CORE HEALTH: 750 PER CHUNK ===

  • Config: coreHealthPerChunk = 750 (replaces 1000).
  • Chunks of the same empire that touch each other (sharing an edge, not diagonal) form ONE connected group. The health of EVERY core in that group = 750 * number of chunks in the group. Examples: 1 isolated chunk = 750, 2 connected = 1500, 3 connected = 2250.
  • Separate groups of chunks (far from each other) are calculated separately, based only on their own chunks.
  • Each chunk still has its own core, and destroying a core conquers ONLY that chunk.
  • Calculate the health when the war starts. During the war the value does not change, even if chunks are conquered.
  • Set maxCoreHealth = 7500 (config cap). Show the real value on the boss bar/action bar (example: "Cuore: 900/1500").
  • Update every text and default config value that mentions 1000.
Kodari AI
KodariOct 21 at 7:06 am 4
  1. Correct fluid flow checks so only cross-territory transfers are blocked.

  2. Remove adjacency requirements while keeping connected territories separate for borders and core health.

  3. Set core health to 750 per connected chunk, cap 7500, and update defaults/text.

Fluid boundary checks now compare source and destination owners, and ordinary flow within the same ownership region remains untouched.

  1. Remove the claim-adjacency rule and its config/error text while preserving connected-group handling; then update core health values.

The claim command no longer requires adjacency, and the adjacency config option and error text are removed. Separate connected claim groups remain independent.

  1. Update the default core health per chunk and cap to 750 and 7500.

Implemented the fluid, boundary-protection, claim, and core-health changes. Fluid flow is blocked only when source and destination owners differ; fire, pistons, hoppers, and dispensers are likewise checked at territory boundaries. Claim adjacency is no longer required, and existing connected-group logic remains in place. Core-health defaults are now 750 per chunk with a 7500 cap, and old default config values are migrated.

Changed files

  • src/main/java/it/kodari/empireclaims/EmpireClaims.java

  • src/main/java/it/kodari/empireclaims/EmpireProtection.java

  • src/main/java/it/kodari/empireclaims/EmpireConfig.java

  • src/main/java/it/kodari/empireclaims/EmpireCommands.java

  • src/main/java/it/kodari/empireclaims/mixin/FireBlockMixin.java

  • src/main/java/it/kodari/empireclaims/mixin/FlowingFluidMixin.java (new)

  • src/main/java/it/kodari/empireclaims/mixin/LavaFluidMixin.java (new)

  • src/main/java/it/kodari/empireclaims/mixin/HopperBlockEntityMixin.java (new)

  • src/main/java/it/kodari/empireclaims/mixin/DispenserBlockMixin.java (new)

  • src/main/resources/empireclaims.mixins.json

I can’t confirm a successful compile: no compile result was available in this session.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
gradle.properties
settings.gradle
Code
21 2,279
src/main/java/it/kodari/empireclaims/EmpireClaims.java
package it.kodari.empireclaims;

import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.event.player.AttackBlockCallback;
import net.fabricmc.fabric.api.event.player.AttackEntityCallback;
import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents;
import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.fabricmc.fabric.api.event.player.UseEntityCallback;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.DustParticleOptions;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerBossEvent;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.BossEvent;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Blocks;
	import net.minecraft.world.level.block.piston.PistonStructureResolver;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.phys.Vec3;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;

public final class EmpireClaims implements ModInitializer {
	private static final long PLAYTIME_CLAIM_WINDOW_MILLIS = 86_400_000L;
	private static final ThreadLocal<Deque<Entity>> ENTITY_TICK_CONTEXT = ThreadLocal.withInitial(ArrayDeque::new);
	private static final Map<UUID, String> lastTerritory = new HashMap<>();
	private static final Set<UUID> borderToggles = new HashSet<>();
	private static final Map<UUID, Long> temporaryBorders = new HashMap<>();
	private static final Set<UUID> chatToggles = new HashSet<>();
	private static final Set<UUID> bypassPlayers = new HashSet<>();
	private static final Map<String, ServerBossEvent> bossBars = new HashMap<>();
	private static final Map<UUID, String> shownBossBars = new HashMap<>();
	private static long tickCount;

	@Override
	public void onInitialize() {
		EmpireConfig.load();
		CommandRegistrationCallback.EVENT.register((dispatcher, buildContext, selection) -> EmpireCommands.register(dispatcher));
		ServerTickEvents.END_SERVER_TICK.register(EmpireClaims::tick);
		ServerPlayConnectionEvents.JOIN.register((listener, sender, server) -> EmpireData.ensureLoaded(server));
		ServerPlayConnectionEvents.DISCONNECT.register((listener, server) -> {
			UUID id = listener.getPlayer().getUUID();
			lastTerritory.remove(id);
			borderToggles.remove(id);
			temporaryBorders.remove(id);
			chatToggles.remove(id);
			bypassPlayers.remove(id);
			shownBossBars.remove(id);
			for (ServerBossEvent bar : bossBars.values()) bar.removePlayer(listener.getPlayer());
		});
		PlayerBlockBreakEvents.BEFORE.register(EmpireProtection::beforeBreak);
		AttackBlockCallback.EVENT.register(EmpireProtection::attackBlock);
		UseBlockCallback.EVENT.register(EmpireProtection::useBlock);
		UseEntityCallback.EVENT.register(EmpireProtection::useEntity);
		AttackEntityCallback.EVENT.register(EmpireProtection::attackEntity);
		ServerLivingEntityEvents.ALLOW_DAMAGE.register(EmpireProtection::allowDamage);
	}

	private static void tick(MinecraftServer server) {
		EmpireData.ensureLoaded(server);
		tickCount++;
		for (ServerPlayer player : server.getPlayerList().getPlayers()) updateTerritory(player);
		if (tickCount % 10 == 0) {
			for (ServerPlayer player : server.getPlayerList().getPlayers()) {
				if (bordersEnabled(player)) drawBorders(player);
			}
		}
		if (tickCount % 20 == 0) {
			for (ServerPlayer player : server.getPlayerList().getPlayers()) {
				String id = player.getUUID().toString();
				EmpireData.store.playtimeSeconds.merge(id, 1L, Long::sum);
				String empireKey = EmpireData.memberEmpire(player.getUUID());
				if (empireKey != null) EmpireData.store.empirePlaytimeSeconds.merge(empireKey, 1L, Long::sum);
			}
			boolean playtimeClaimsChanged = false;
			long now = System.currentTimeMillis();
			for (String empireKey : EmpireData.store.empires.keySet()) playtimeClaimsChanged |= refreshPlaytimeClaims(empireKey, now);
			if (playtimeClaimsChanged) EmpireData.save();
			advanceWars(server);
			updateBossBars(server);
			EmpireData.store.invitations.entrySet().removeIf(entry -> entry.getValue().expiresAt <= System.currentTimeMillis());
		}
		if (tickCount % 6000 == 0) EmpireData.save();
	}

	private static void updateTerritory(ServerPlayer player) {
		String key = EmpireData.chunkKey(dimension(player.level()), player.chunkPosition().x(), player.chunkPosition().z());
		String owner = EmpireData.store.claims.get(key);
		UUID id = player.getUUID();
		if (!lastTerritory.containsKey(id)) {
			lastTerritory.put(id, owner);
			return;
		}
		String previous = lastTerritory.put(id, owner);
		if (Objects.equals(previous, owner)) return;
		if (owner == null) {
			player.sendOverlayMessage(colored("Terra libera", ChatFormatting.YELLOW));
			return;
		}
		EmpireData.Empire empire = EmpireData.store.empires.get(owner);
		if (empire == null) return;
		player.sendOverlayMessage(colored("Territorio dell'impero " + empire.name, ChatFormatting.GREEN));
		String visitorEmpire = EmpireData.memberEmpire(id);
		if (Objects.equals(visitorEmpire, owner)) return;
		for (ServerPlayer member : onlineMembers(player.level().getServer(), owner)) {
			member.sendOverlayMessage(colored(player.getPlainTextName() + " è entrato nel tuo territorio", ChatFormatting.RED));
		}
	}

	private static void drawBorders(ServerPlayer player) {
		int radius = EmpireConfig.borderViewChunks;
		int centerX = player.chunkPosition().x();
		int centerZ = player.chunkPosition().z();
		int y = player.blockPosition().getY();
		String dimension = dimension(player.level());
		String ownEmpire = EmpireData.memberEmpire(player.getUUID());
		for (int chunkX = centerX - radius; chunkX <= centerX + radius; chunkX++) {
			for (int chunkZ = centerZ - radius; chunkZ <= centerZ + radius; chunkZ++) {
				String chunkKey = EmpireData.chunkKey(dimension, chunkX, chunkZ);
				String owner = EmpireData.store.claims.get(chunkKey);
				if (owner == null) continue;
				int color = Objects.equals(owner, ownEmpire) ? 0x35E66B : isAtWar(ownEmpire, owner) ? 0xF33A3A : 0xF4D03F;
				DustParticleOptions dust = new DustParticleOptions(color, 1.2F);
				int minX = chunkX * 16;
				int minZ = chunkZ * 16;
				if (!Objects.equals(EmpireData.store.claims.get(EmpireData.chunkKey(dimension, chunkX, chunkZ - 1)), owner))
					drawEdge(player, dust, minX, minZ, minX + 16, minZ, y);
				if (!Objects.equals(EmpireData.store.claims.get(EmpireData.chunkKey(dimension, chunkX, chunkZ + 1)), owner))
					drawEdge(player, dust, minX, minZ + 16, minX + 16, minZ + 16, y);
				if (!Objects.equals(EmpireData.store.claims.get(EmpireData.chunkKey(dimension, chunkX - 1, chunkZ)), owner))
					drawEdge(player, dust, minX, minZ, minX, minZ + 16, y);
				if (!Objects.equals(EmpireData.store.claims.get(EmpireData.chunkKey(dimension, chunkX + 1, chunkZ)), owner))
					drawEdge(player, dust, minX + 16, minZ, minX + 16, minZ + 16, y);
			}
		}
	}

	private static void drawEdge(ServerPlayer player, DustParticleOptions dust, int x1, int z1, int x2, int z2, int baseY) {
		for (int offset = -2; offset <= 2; offset += 2) {
			for (int step = 0; step <= 16; step += 2) {
				double x = x1 + (x2 - x1) * step / 16.0;
				double z = z1 + (z2 - z1) * step / 16.0;
				player.level().sendParticles(player, dust, true, true, x, baseY + offset + 0.5, z, 1, 0, 0, 0, 0);
			}
		}
	}

	static boolean bordersEnabled(ServerPlayer player) {
		Long until = temporaryBorders.get(player.getUUID());
		if (until != null && until <= tickCount) temporaryBorders.remove(player.getUUID());
		return borderToggles.contains(player.getUUID()) || temporaryBorders.getOrDefault(player.getUUID(), 0L) > tickCount;
	}

	static void revealBorders(ServerPlayer player) {
		temporaryBorders.put(player.getUUID(), tickCount + 200);
	}

	private static void advanceWars(MinecraftServer server) {
		Iterator<Map.Entry<String, EmpireData.War>> iterator = EmpireData.store.wars.entrySet().iterator();
		List<EmpireData.War> ended = new ArrayList<>();
		for (EmpireData.War war : EmpireData.store.wars.values()) {
			if (war.active) {