Jzpm
๐Ÿ“Ž 1 file 5,247 chars
๐Ÿ“„
pasted-code-1790324748297.txt
txt 188 lines
โ–ถ
Create a complete **Minecraft Java Edition plugin for PaperMC 1.21.11**.

The plugin should add a custom **Golden Apple trade** to Farmer villagers.

## CUSTOM TRADE

Every Farmer villager should have this additional trade:

**Normal Farmer:**
**3 Emeralds โ†’ 1 Golden Apple**

Keep all of the Farmer's normal vanilla trades. The Golden Apple trade should be added alongside them.

The item must be a normal **Golden Apple (`GOLDEN_APPLE`)**, NOT an Enchanted Golden Apple.

## SPECIAL PRICING

The Golden Apple trade should automatically change price depending on the Farmer's status.

### Normal Farmer
**3 Emeralds โ†’ 1 Golden Apple**

### Hero of the Village
**2 Emeralds โ†’ 1 Golden Apple**

### Cured Farmer
**1 Emerald โ†’ 1 Golden Apple**

### Cured + Hero of the Village
**1 Emerald โ†’ 1 Golden Apple**

Curing takes priority over Hero of the Village.

Do NOT stack the discounts.

For example:
- Normal = 3 emeralds
- Hero of the Village = 2 emeralds
- Cured = 1 emerald
- Cured + Hero of the Village = 1 emerald

The plugin must detect these conditions automatically.

## CONFIGURATION

Create a `config.yml` so I can customize the prices and Golden Apple amount.

Use:

```yaml
trade:
  normal-emerald-cost: 3
  hero-emerald-cost: 2
  cured-emerald-cost: 1
  golden-apple-amount: 1

settings:
  keep-vanilla-trades: true
  infinite-restocks: true
```

For example, if I change:

```yaml
normal-emerald-cost: 5
hero-emerald-cost: 3
cured-emerald-cost: 1
golden-apple-amount: 2
```

then the trades should become:

Normal:
**5 Emeralds โ†’ 2 Golden Apples**

Hero of the Village:
**3 Emeralds โ†’ 2 Golden Apples**

Cured:
**1 Emerald โ†’ 2 Golden Apples**

## INFINITE USES / RESTOCKS

The custom Golden Apple trade must have **infinite uses**.

It should NEVER permanently lock after being used.

Players should be able to trade the custom Golden Apple trade continuously.

The infinite-use behavior should apply ONLY to the custom Golden Apple trade.

Do NOT make the Farmer's normal vanilla trades infinite.

Do not create hundreds of duplicate trades. There should only ever be **one custom Golden Apple trade per Farmer villager**.

## CURING

Detect when a Farmer villager has been cured from a Zombie Villager.

After being cured, the custom trade should use the configured:

```yaml
cured-emerald-cost: 1
```

The cured status must persist when:
- The villager unloads
- The chunk unloads
- The server restarts
- The villager is saved and loaded again

Do not repeatedly apply the discount every time the villager loads.

## HERO OF THE VILLAGE

Detect when the player trading with the Farmer has **Hero of the Village**.

If the Farmer is not cured and the player has Hero of the Village:

**2 Emeralds โ†’ 1 Golden Apple**

The Hero of the Village discount should apply based on the **player currently trading**, not permanently change the villager's base price.

If the player does not have Hero of the Village, use the normal price unless the villager is cured.

If the villager is cured, always use the cured price of **1 emerald**, regardless of Hero of the Village.

## RELOAD COMMAND

Add:

`/farmerreload`

This command should reload the `config.yml` without restarting the server.

Permission:

`farmergoldenapple.reload`

Only operators or players with this permission can use the command.

When successfully reloaded, send:

`Farmer Golden Apple config reloaded!`

The new prices should take effect after the reload.

## VILLAGER REQUIREMENTS

- Only affect **Farmer** villagers.
- Keep all normal vanilla Farmer trades.
- Add the Golden Apple trade alongside the vanilla trades.
- Do not affect Librarians, Armors, Toolsmiths, etc.
- Existing Farmer villagers should receive the custom trade.
- Newly spawned Farmer villagers should receive the custom trade.
- The trade must work through the normal villager trading GUI.
- Do not add duplicate Golden Apple trades.
- Correctly handle villagers leveling up.
- Correctly handle villagers being loaded from chunks.
- Correctly handle server restarts.

## TECHNICAL REQUIREMENTS

- Minecraft Java Edition
- **PaperMC 1.21.11**
- Java
- Use the modern Paper/Bukkit API compatible with 1.21.11.
- No Vault.
- No ProtocolLib.
- No external plugins required.
- Include complete Java source code.
- Include `plugin.yml`.
- Include `config.yml`.
- Include the complete project structure.
- Make sure the plugin does not produce duplicate trades.
- Make sure the plugin does not cause errors when villagers are loaded, cured, leveled up, or restocked.

## IMPORTANT โ€” I DON'T KNOW HOW TO COMPILE PLUGINS

I don't know how to use Maven, Gradle, or compile Java plugins.

**If your environment allows it, compile the finished plugin and give me the actual `.jar` file that I can immediately put into my Paper server's `plugins` folder.**

If you cannot provide a compiled `.jar`, provide a complete project with a **one-click `build.bat`** that automatically compiles the plugin.

Do not give me pseudocode, incomplete code, or just an explanation.

I want a **complete, working PaperMC 1.21.11 plugin**.
Kodari AI
KodariSep 25 at 8:28 am 1
FarmerGoldenAppleTrade
A PaperMC 1.21.11 plugin that adds a custom Golden Apple trade to Farmer villagers with dynamic pricing based on villager status. Farmers trade 3 emeralds for 1 golden apple normally, 2 emeralds when the trading player has Hero of the Village, and 1 emerald when cured from a zombie villager. Cured status persists across server restarts via persistent data. The trade has infinite uses without locking, never duplicates, and coexists with vanilla trades. Fully configurable via config.yml with a /farmerreload command for hot-reloading prices without server restart.
  1. Create the Paper 1.21.11 Gradle project, plugin descriptor, and default config.

  2. Implement Farmer trade management, persistent cure tracking, per-trader Hero pricing, and /farmerreload.

  3. Add a one-click Windows build script.

Created the complete Paper 1.21.11 project with the Farmer Golden Apple trade, saved cure status, Hero of the Village pricing, and /farmerreload.

Run build.bat on Windows with a Java 21 JDK and internet access. The plugin JAR will be at build\libs\FarmerGoldenApple-1.0.0.jar. I couldnโ€™t provide a precompiled JAR here.

Kodari can make mistakes. Review important code before using.
Files
src
build.bat
build.gradle
settings.gradle
Code
6 257
src/main/java/com/kodari/farmergoldenapple/FarmerGoldenApplePlugin.java
package com.kodari.farmergoldenapple;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityTransformEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;

import java.util.ArrayList;
import java.util.List;

public final class FarmerGoldenApplePlugin extends JavaPlugin implements Listener {
    private NamespacedKey curedKey;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        curedKey = new NamespacedKey(this, "cured-farmer");
        getServer().getPluginManager().registerEvents(this, this);

        for (var world : Bukkit.getWorlds()) {
            for (Entity entity : world.getEntities()) {
                if (entity instanceof Villager villager) {
                    scheduleTradeUpdate(villager);
                }
            }
        }
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!command.getName().equalsIgnoreCase("farmerreload")) {
            return false;
        }
        if (!sender.hasPermission("farmergoldenapple.reload")) {
            sender.sendMessage("You do not have permission to use this command.");
            return true;
        }

        reloadConfig();
        for (var world : Bukkit.getWorlds()) {
            for (Entity entity : world.getEntities()) {
                if (entity instanceof Villager villager && isFarmer(villager)) {
                    updateTrade(villager, false);
                }
            }
        }
        sender.sendMessage("Farmer Golden Apple config reloaded!");
        return true;
    }

    @EventHandler
    public void onVillagerSpawn(CreatureSpawnEvent event) {
        if (event.getEntity() instanceof Villager villager) {
            scheduleTradeUpdate(villager);
        }
    }

    @EventHandler
    public void onChunkLoad(ChunkLoadEvent event) {
        for (Entity entity : event.getChunk().getEntities()) {
            if (entity instanceof Villager villager) {
                scheduleTradeUpdate(villager);
            }
        }
    }

    @EventHandler
    public void onVillagerCured(EntityTransformEvent event) {
        if (event.getTransformReason() != EntityTransformEvent.TransformReason.CURED) {
            return;
        }
        for (Entity entity : event.getTransformedEntities()) {
            if (entity instanceof Villager villager) {
                Bukkit.getScheduler().runTask(this, () -> {
                    if (!villager.isValid() || !isFarmer(villager)) {
                        return;
                    }
                    villager.getPersistentDataContainer().set(curedKey, PersistentDataType.BYTE, (byte) 1);
                    updateTrade(villager, false);
                });
            }
        }
    }

    @EventHandler
    public void onVillagerAcquireTrade(org.bukkit.event.entity.VillagerAcquireTradeEvent event) {
        if (event.getEntity() instanceof Villager villager) {
            scheduleTradeUpdate(villager);
        }
    }

    @EventHandler
    public void onFarmerInteract(PlayerInteractEntityEvent event) {
        if (event.isCancelled() || !(event.getRightClicked() instanceof Villager villager) || !isFarmer(villager)) {
            return;
        }
        updateTrade(villager, hasHeroOfTheVillage(event.getPlayer()));
    }

    private void scheduleTradeUpdate(Villager villager) {
        Bukkit.getScheduler().runTask(this, () -> {
            if (villager.isValid() && isFarmer(villager)) {
                updateTrade(villager, false);
            }
        });
    }

    private void updateTrade(Villager villager, boolean heroOfTheVillage) {
        Material apple = Material.matchMaterial("GOLDEN_APPLE");
        Material emerald = Material.matchMaterial("EMERALD");
        if (apple == null || emerald == null) {
            return;
        }

        List<MerchantRecipe> recipes = new ArrayList<>();
        if (getConfig().getBoolean("settings.keep-vanilla-trades", true)) {
            for (MerchantRecipe recipe : villager.getRecipes()) {
                if (recipe.getResult().getType() != apple) {
                    recipes.add(recipe);
                }
            }
        }

        boolean cured = villager.getPersistentDataContainer().has(curedKey, PersistentDataType.BYTE);
        int emeraldCost = cured
                ? getConfig().getInt("trade.cured-emerald-cost", 1)
                : heroOfTheVillage
                    ? getConfig().getInt("trade.hero-emerald-cost", 2)
                    : getConfig().getInt("trade.normal-emerald-cost", 3);
        int appleAmount = getConfig().getInt("trade.golden-apple-amount", 1);

        MerchantRecipe goldenAppleTrade = new MerchantRecipe(
                new ItemStack(apple, Math.max(1, appleAmount)), Integer.MAX_VALUE);
        goldenAppleTrade.setIngredients(List.of(new ItemStack(emerald, Math.max(1, emeraldCost))));
        goldenAppleTrade.setUses(0);
        goldenAppleTrade.setMaxUses(Integer.MAX_VALUE);
        goldenAppleTrade.setPriceMultiplier(0.0f);
        goldenAppleTrade.setDemand(0);
        goldenAppleTrade.setSpecialPrice(0);
        recipes.add(goldenAppleTrade);
        villager.setRecipes(recipes);
    }

    private boolean isFarmer(Villager villager) {
        return villager.getProfession() == Villager.Profession.FARMER;
    }

    private boolean hasHeroOfTheVillage(Player player) {
        for (PotionEffect effect : player.getActivePotionEffects()) {
            if (effect.getType().getKey().getKey().equals("hero_of_the_village")) {
                return true;
            }
        }
        return false;
    }
}