Piksel

Redact this project and compile it into a .jar plugin that generates Minecraft ores from deepslate and stone blocks, incorporating configurable success and failure rates based on Y-coordinates. Ensure the plugin maintains its core mechanics and placeholder integration while improving code quality and structure

Kodari AI
KodariOct 10 at 10:20 pm 2
  1. Trace the existing ore-generation mechanics and placeholder integration.

  2. Refactor the relevant code and add configurable Y-based success/failure rates.

  3. Keep existing behavior intact and leave the project ready to compile.

Refactored the OreFinder project, fixed its source/resource layout and PlaceholderAPI build dependency, and added optional inclusive Y-ranges for success/failure rates. When a range matches, its rates are normalized to 100%; existing ore chances still determine which ore is selected. With y-ranges empty, the existing odds remain unchanged, and PlaceholderAPI placeholders use the same updated chance calculation.

To create and download the .jar, click Compile in the desktop top bar (or ⋮ → Compile Project on phone), click Compile, then click Download when it succeeds.

Piksel

Add code to store the coordinates of all stone/deepslate blocks where no ore was found into a list, and implement a check before ore generation to see if a block matches an entry in this list (i would prefer separate .json file). The goal is to ensure that all stone/deepslate blocks containing no ore would be synchronized across all players. Also i need a code for checking if the block was placed by player. If true - do not start ore generation and send fail message into hotbar. We have CoreProtect on server, so you may use it's functionality to implement this mechanic. The last request for this plugin is to add villager sounds and green sparkle particles for a successful ore generation and a sound of unhappy villager and smoke for failed ore generation.

Kodari AI
KodariOct 25 at 7:02 pm 4
  1. Add persistent, shared JSON tracking for locations where ore generation failed, and skip previously recorded locations.

  2. Detect player-placed blocks and send the requested hotbar failure message.

  3. Add success/failure villager sounds and particles.

  1. Persistent shared failure-location tracking goes in a separate JSON file; later attempts will be blocked before generation, including attempts already in progress when another player records a failure.

  1. Added a CoreProtect history check for previously player-placed blocks, with a placement-event fallback and a configurable hotbar failure message.

  1. Replaced the generation feedback with villager sounds, HAPPY_VILLAGER sparkles on success, and smoke on failure.

Added the requested mechanics:

  • Failed stone/deepslate coordinates are saved to failed-locations.json in the plugin’s data folder and checked before generation, so players share the same results.

  • CoreProtect history blocks generation on player-placed blocks. A BlockPlaceEvent fallback tracks placements during the session; players receive the configurable messages.player-placed hotbar message.

  • Successful generation plays a happy villager sound with green sparkles; failed generation plays an unhappy villager sound with smoke.

To build and download the updated .jar, click Compile in the desktop top bar (or ⋮ → Compile Project on phone), then click Compile and Download when the build succeeds.

Piksel

Move the message output for succesfull ore generation from chat to hotbar title, and if it's possible, make the ore names translated into russian language

Kodari AI
KodariOct 25 at 7:27 pm 1
  1. Change the successful-generation message to a hotbar action-bar message.

  2. Add Russian ore-name translations while preserving the existing generation and placeholder behavior.

  3. Keep the translation configurable and compile-ready.

Successful ore-generation messages now appear in the hotbar action bar instead of chat. Ore names are translated into Russian using the configurable ore-names section in src/main/resources/config.yml; if a translation is missing, the plugin falls back to the ore ID.

Piksel

can you add item id for every single tier of orefinder and prepare nbts of it to be compatable with executable items and itemsadder recognition and reading? You may use API if needed

Kodari AI
KodariOct 25 at 7:47 pm 2

Added stable IDs and metadata for all five tiers:

  • Each generated tool stores its tier ID in PDC/NBT as orefinder:item_id, with values such as orefinder:tier1 through orefinder:tier5.

  • Added optional itemsadder-id and executableitems-id settings per tier. OreFinder checks those IDs through the respective APIs and recognizes matching custom items as that tier.

  • Added the plugins as soft dependencies; OreFinder does not require either plugin to run.

The NBT tag does not register a vanilla pickaxe as an ItemsAdder or ExecutableItems custom item by itself. To have those plugins recognize an item as their own, define it in their configuration and enter its registered ID in the corresponding setting.

Kodari can make mistakes. Review important code before using.
Files
src
IMPORTANT.txt
pom.xml
Code
7 1,041
src/main/java/com/tapochekprod/orefinder/OreFinderPlugin.java
package com.tapochekprod.orefinder;

import com.cryptomorin.xseries.XSound;
import com.cryptomorin.xseries.particles.XParticle;
import net.kyori.adventure.text.Component;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OreFinderPlugin extends JavaPlugin implements Listener {

    private static final long HOLD_TICKS = 20L;
    private static final int REACH_CHECK = 5;
    private static final Pattern FAILED_LOCATION_PATTERN = Pattern.compile(
            "\\{\"world\":\"([A-Za-z0-9_-]+)\",\"x\":(-?\\d+),\"y\":(-?\\d+),\"z\":(-?\\d+)\\}");

    private NamespacedKey toolKey;   // маркер: предмет наш
    private NamespacedKey tierKey;   // строка: "tier1" / "tier2" / ...
    private NamespacedKey itemIdKey;

    private final Random random = new Random();
    private final List<OreRule> ores = new ArrayList<>();
    private final List<ChanceRange> chanceRanges = new ArrayList<>();
    private final Map<String, ToolTier> tools = new LinkedHashMap<>();

    private final Map<UUID, Set<BlockPos>> investigated = new HashMap<>();
    private final Set<BlockPos> failedLocations = new HashSet<>();
    private final Set<BlockPos> playerPlacedLocations = new HashSet<>();
    private File failedLocationsFile;
    private Object coreProtectAPI;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        loadFailedLocations();
        toolKey = new NamespacedKey(this, "ore_finder_tool");
        tierKey = new NamespacedKey(this, "ore_finder_tier");
        itemIdKey = new NamespacedKey(this, "item_id");
        initializeCoreProtect();
        loadOres();
        loadChanceRanges();
        loadTools();
        getServer().getPluginManager().registerEvents(this, this);

        if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
            new OreFinderExpansion(this).register();
        }
    }

    // ============================================================
    //  Загрузка
    // ============================================================
    private void loadOres() {
        ores.clear();
        ConfigurationSection sec = getConfig().getConfigurationSection("ores");
        if (sec == null) { getLogger().warning("В конфиге нет секции 'ores'"); return; }
        for (String key : sec.getKeys(false)) {
            ConfigurationSection s = sec.getConfigurationSection(key);
            if (s == null) continue;
            try {
                Material stoneMat = Material.valueOf(s.getString("stone", key + "_ore").toUpperCase(Locale.ROOT));
                Material deepMat  = Material.valueOf(s.getString("deepslate", "deepslate_" + key + "_ore").toUpperCase(Locale.ROOT));
                ores.add(new OreRule(key.toLowerCase(Locale.ROOT), stoneMat, deepMat,
                        s.getBoolean("rising", false),
                        s.getDouble("peak-chance", 5.0),
                        s.getInt("y-peak"),
                        s.getInt("y-zero")));
            } catch (IllegalArgumentException ex) {
                getLogger().warning("Пропущена руда '" + key + "': " + ex.getMessage());
            }
        }
    }

    private void loadChanceRanges() {
        chanceRanges.clear();
        ConfigurationSection section = getConfig().getConfigurationSection("generation.y-ranges");
        if (section == null) return;

        for (String key : section.getKeys(false)) {
            ConfigurationSection range = section.getConfigurationSection(key);
            if (range == null) continue;

            int minY = range.getInt("min-y");
            int maxY = range.getInt("max-y");
            double successRate = range.getDouble("success-rate", 0.0);
            double failureRate = range.getDouble("failure-rate", 0.0);
            double rateTotal = successRate + failureRate;
            if (minY > maxY || successRate < 0.0 || failureRate < 0.0
                    || !Double.isFinite(successRate) || !Double.isFinite(failureRate)
                    || !Double.isFinite(rateTotal)) {
                getLogger().warning("Пропущен диапазон шансов '" + key + "': проверьте Y и success-rate/failure-rate");
                continue;
            }
            chanceRanges.add(new ChanceRange(minY, maxY, successRate, failureRate));
        }
    }

    @Override
    public void onDisable() {
        saveFailedLocations();
    }

    private void loadFailedLocations() {
        failedLocations.clear();
        failedLocationsFile = new File(getDataFolder(), "failed-locations.json");
        if (!failedLocationsFile.isFile()) return;

        try {
            Matcher matcher = FAILED_LOCATION_PATTERN.matcher(Files.readString(failedLocationsFile.toPath()));
            while (matcher.find()) {
                try {
                    String world = new String(Base64.getUrlDecoder().decode(matcher.group(1)), StandardCharsets.UTF_8);
                    failedLocations.add(new BlockPos(world,
                            Integer.parseInt(matcher.group(2)),
                            Integer.parseInt(matcher.group(3)),
                            Integer.parseInt(matcher.group(4))));
                } catch (IllegalArgumentException ex) {
                    getLogger().warning("Пропущена некорректная запись в failed-locations.json");
                }
            }
        } catch (IOException ex) {
            getLogger().warning("Не удалось загрузить failed-locations.json: " + ex.getMessage());
        }
    }

    private void saveFailedLocations() {
        if (failedLocationsFile == null) return;

        StringBuilder json = new StringBuilder("[\n");
        Iterator<BlockPos> iterator = failedLocations.iterator();
        while (iterator.hasNext()) {
            BlockPos pos = iterator.next();
            String world = Base64.getUrlEncoder().withoutPadding()
                    .encodeToString(pos.world.getBytes(StandardCharsets.UTF_8));
            json.append("  {\"world\":\"").append(world)
                    .append("\",\"x\":").append(pos.x)
                    .append(",\"y\":").append(pos.y)
                    .append(",\"z\":").append(pos.z).append('}');
            if (iterator.hasNext()) json.append(',');
            json.append('\n');
        }
        json.append("]\n");

        try {
            Files.createDirectories(failedLocationsFile.toPath().getParent());
            Files.writeString(failedLocationsFile.toPath(), json.toString());
        } catch (IOException ex) {
            getLogger().warning("Не удалось сохранить failed-locations.json: " + ex.getMessage());
        }
    }

    private void initializeCoreProtect() {
        Plugin plugin = getServer().getPluginManager().getPlugin("CoreProtect");
        if (plugin == null || !plugin.isEnabled()) return;

        try {
            coreProtectAPI = plugin.getClass().getMethod("getAPI").invoke(plugin);
        } catch (ReflectiveOperationException ex) {
            getLogger().warning("CoreProtect API is unavailable; player placement checks use live placement events only.");
        }
    }

    private void loadTools() {
        tools.clear();
        ConfigurationSection sec = getConfig().getConfigurationSection("tools");
        if (sec == null) { getLogger().warning("В конфиге нет секции 'tools'"); return; }
        for (String key : sec.getKeys(false)) {
            ConfigurationSection s = sec.getConfigurationSection(key);
            if (s == null) continue;
            try {
                Material mat = Material.valueOf(s.getString("material", "WOODEN_PICKAXE").toUpperCase(Locale.ROOT));
                String name = s.getString("name", "&7Искатель руды");
                String itemId = s.getString("item-id", "orefinder:" + key.toLowerCase(Locale.ROOT));
                String itemsAdderId = s.getString("itemsadder-id", "").trim();
                String executableItemsId = s.getString("executableitems-id", "").trim();
                Set<String> allowed = new HashSet<>();