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<>();