// Map to store active Radiation Zones by their name
private final Map<String, RadiationZone> zones = new HashMap<>();
// Map to store radiation levels per player
private final Map<UUID, Integer> radiationLevels = new HashMap<>();
private final Random random = new Random();
private FileConfiguration config;
@Override
public void onEnable() {
// Save default configuration if not present
saveDefaultConfig();
config = getConfig();
// Register commands
getCommand("radiationzone").setExecutor(this);
getCommand("radiationzone").setTabCompleter(this);
getCommand("radiationcheck").setExecutor(this);
// Register event listeners
getServer().getPluginManager().registerEvents(this, this);
// Start the random radiation zone spawner
startRandomRadiationZoneSpawner();
// Register crafting recipes
registerRecipes();
getLogger().info("RadiationPlugin включен!");
}
@Override
public void onDisable() {
// Force end all radiation zones
for (RadiationZone zone : zones.values()) {
zone.forceEndZone();
}
zones.clear();
getLogger().info("RadiationPlugin выключен!");
}
/**
* Register custom crafting recipes for radiation equipment and items.
*/
private void registerRecipes() {
// Create the Filter item
ItemStack filter = createCustomItem(Material.PAPER, ChatColor.AQUA + "Фильтр", null);
NamespacedKey filterKey = new NamespacedKey(this, "filter");
ShapedRecipe filterRecipe = new ShapedRecipe(filterKey, filter);
filterRecipe.shape(" C ", "WPW", " C ");
filterRecipe.setIngredient('C', Material.CHARCOAL);
filterRecipe.setIngredient('W', Material.WHITE_WOOL);
filterRecipe.setIngredient('P', Material.PAPER);
Bukkit.addRecipe(filterRecipe);
// Create the Antidote
ItemStack antidote = createCustomItem(Material.POTION, ChatColor.GOLD + "Антидот", null);
PotionMeta antidoteMeta = (PotionMeta) antidote.getItemMeta();
if (antidoteMeta != null) {
antidoteMeta.setColor(Color.LIME);
antidoteMeta.addCustomEffect(new PotionEffect(PotionEffectType.HEAL, 1, 1), true);
antidote.setItemMeta(antidoteMeta);
}
NamespacedKey antidoteKey = new NamespacedKey(this, "antidote");
ShapelessRecipe antidoteRecipe = new ShapelessRecipe(antidoteKey, antidote);
antidoteRecipe.addIngredient(Material.HONEY_BOTTLE);
antidoteRecipe.addIngredient(Material.SPIDER_EYE);
antidoteRecipe.addIngredient(new RecipeChoice.ExactChoice(filter)); // Add Filter to recipe
Bukkit.addRecipe(antidoteRecipe);
// Create Radiation Boots
ItemStack radBoots = createCustomItem(Material.LEATHER_BOOTS, ChatColor.GREEN + "Радиационные ботинки", null);
NamespacedKey radBootsKey = new NamespacedKey(this, "radiation_boots");
ShapedRecipe radBootsRecipe = new ShapedRecipe(radBootsKey, radBoots);
radBootsRecipe.shape("F F", "F F", " "); // Three rows, third is empty
radBootsRecipe.setIngredient('F', new RecipeChoice.ExactChoice(filter));
Bukkit.addRecipe(radBootsRecipe);
// Create Radiation Leggings
ItemStack radLeggings = createCustomItem(Material.LEATHER_LEGGINGS, ChatColor.GREEN + "Радиационные штаны", null);
NamespacedKey radLeggingsKey = new NamespacedKey(this, "radiation_leggings");
ShapedRecipe radLeggingsRecipe = new ShapedRecipe(radLeggingsKey, radLeggings);
radLeggingsRecipe.shape("FFF", "F F", " "); // Three rows, third is empty
radLeggingsRecipe.setIngredient('F', new RecipeChoice.ExactChoice(filter));
Bukkit.addRecipe(radLeggingsRecipe);
// Create Protective Gloves
ItemStack gloves = createCustomItem(Material.LEATHER_GLOVES, ChatColor.GREEN + "Защитные перчатки", null);
NamespacedKey glovesKey = new NamespacedKey(this, "protective_gloves");
ShapedRecipe glovesRecipe = new ShapedRecipe(glovesKey, gloves);
glovesRecipe.shape("F F", " I ", " "); // Three rows, third is empty
glovesRecipe.setIngredient('F', new RecipeChoice.ExactChoice(filter));
glovesRecipe.setIngredient('I', Material.IRON_INGOT);
Bukkit.addRecipe(glovesRecipe);
// Create Strong Antidote
ItemStack strongAntidote = createCustomItem(Material.POTION, ChatColor.DARK_PURPLE + "Усиленный антидот", null);
PotionMeta strongAntidoteMeta = (PotionMeta) strongAntidote.getItemMeta();
if (strongAntidoteMeta != null) {
strongAntidoteMeta.setColor(Color.PURPLE);
strongAntidoteMeta.addCustomEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 1), true);
strongAntidote.setItemMeta(strongAntidoteMeta);
}
NamespacedKey strongAntidoteKey = new NamespacedKey(this, "strong_antidote");
ShapelessRecipe strongAntidoteRecipe = new ShapelessRecipe(strongAntidoteKey, strongAntidote);
strongAntidoteRecipe.addIngredient(new RecipeChoice.ExactChoice(antidote));
strongAntidoteRecipe.addIngredient(Material.GHAST_TEAR);
Bukkit.addRecipe(strongAntidoteRecipe);
// Note: Mutaционные предметы и соответствующие рецепты удалены.
}
/**
* Helper method to create a custom item with name and lore.
*
* @param material Material of the item
* @param name Display name of the item
* @param lore Lore of the item (can be null)
* @return Custom ItemStack
*/
private ItemStack createCustomItem(Material material, String name, List<String> lore) {
ItemStack item = new ItemStack(material);
if (name != null || lore != null) {
ItemMeta meta = item.getItemMeta();
if (meta != null) {
if (name != null) {
meta.setDisplayName(name);
}
if (lore != null) {
meta.setLore(lore);
}
meta.setUnbreakable(false); // Items should be breakable
item.setItemMeta(meta);
}
}
return item;
}
/**
* Handle commands.
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Handle /radiationcheck
if (command.getName().equalsIgnoreCase("radiationcheck")) {
if (!sender.hasPermission("radiationplugin.radiationcheck")) {
sender.sendMessage(ChatColor.RED + "У вас нет прав для выполнения этой команды.");
return true;
}
if (!(sender instanceof Player)) {
sender.sendMessage("Эта команда может использоваться только игроками.");
return true;
}
Player player = (Player) sender;
int radiationLevel = radiationLevels.getOrDefault(player.getUniqueId(), 0);
player.sendMessage(ChatColor.YELLOW + "Ваш текущий уровень радиации: " + radiationLevel);
return true;
}
// Handle /radiationzone
if (command.getName().equalsIgnoreCase("radiationzone")) {
if (!sender.hasPermission("radiationplugin.radiationzone")) {
sender.sendMessage(ChatColor.RED + "У вас нет прав для выполнения этой команды.");
return true;
}
if (!(sender instanceof Player)) {
sender.sendMessage("Эта команда может использоваться только игроками.");
return true;
}
Player player = (Player) sender;
if (args.length == 0) {
player.sendMessage(ChatColor.RED + "Использование: /radiationzone <create|delete|list|info> [args]");
return true;
}
switch (args[0].toLowerCase()) {
case "create":
return handleCreateZone(player, args);
case "delete":
return handleDeleteZone(player, args);
case "list":
return handleListZones(player);
case "info":
return handleInfoZone(player, args);
default:
player.sendMessage(ChatColor.RED + "Неверная подкоманда. Используйте: create, delete, list, info");
return true;
}
}
// Unhandled command
return false;
}
/**
* Handle the creation of a radiation zone.
*
* @param player Player executing the command
* @param args Command arguments
* @return true
*/
private boolean handleCreateZone(Player player, String[] args) {
if (args.length != 10) { // radiationzone, create, 8 params
player.sendMessage(ChatColor.RED + "Использование: /radiationzone create <min.x> <min.y> <min.z> <max.x> <max.y> <max.z> <level> <name> <decrease_interval (ticks)>");
return true;
}
try {
double minX = Double.parseDouble(args[1]);
double minY = Double.parseDouble(args[2]);
double minZ = Double.parseDouble(args[3]);
double maxX = Double.parseDouble(args[4]);
double maxY = Double.parseDouble(args[5]);
double maxZ = Double.parseDouble(args[6]);
int level = Integer.parseInt(args[7]);
String name = args[8];
int decreaseInterval = Integer.parseInt(args[9]);
// Validate level
int minLevel = config.getInt("rad_zone.min_level", 1);
int maxLevel = config.getInt("rad_zone.max_level", 5);
if (level < minLevel || level > maxLevel) {
player.sendMessage(ChatColor.RED + "Уровень радиации должен быть между " + minLevel + " и " + maxLevel + ".");
return true;
}
// Check if zone with same name exists
if (zones.containsKey(name)) {
player.sendMessage(ChatColor.RED + "Радиационная зона с таким названием уже существует.");
return true;
}
// Create and store the zone
RadiationZone zone = new RadiationZone(minX, minY, minZ, maxX, maxY, maxZ, level, name, decreaseInterval);
zones.put(name, zone);
zone.startRadiation();
player.sendMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' успешно создана.");
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.RED + "Ошибка: убедитесь, что координаты, уровень и интервал указаны числом.");
return true;
} catch (Exception e) {
player.sendMessage(ChatColor.RED + "Произошла непредвиденная ошибка при создании зоны.");
e.printStackTrace();
return true;
}
return true;
}
/**
* Handle deletion of a radiation zone.
*
* @param player Player executing the command
* @param args Command arguments
* @return true
*/
private boolean handleDeleteZone(Player player, String[] args) {
if (args.length != 2) { // radiationzone, delete, name
player.sendMessage(ChatColor.RED + "Использование: /radiationzone delete <name>");
return true;
}
String name = args[1];
RadiationZone zone = zones.get(name);
if (zone == null) {
player.sendMessage(ChatColor.RED + "Радиационная зона с названием '" + name + "' не найдена.");
return true;
}
zone.forceEndZone();
zones.remove(name);
player.sendMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' успешно удалена.");
return true;
}
/**
* Handle listing all active radiation zones.
*
* @param player Player executing the command
* @return true
*/
private boolean handleListZones(Player player) {
if (zones.isEmpty()) {
player.sendMessage(ChatColor.YELLOW + "Нет активных радиационных зон.");
return true;
}
player.sendMessage(ChatColor.GOLD + "Список активных радиационных зон:");
for (String name : zones.keySet()) {
player.sendMessage(ChatColor.GRAY + "- " + name);
}
return true;
}
/**
* Handle displaying info about a specific radiation zone.
*
* @param player Player executing the command
* @param args Command arguments
* @return true
*/
private boolean handleInfoZone(Player player, String[] args) {
if (args.length != 2) { // radiationzone, info, name
player.sendMessage(ChatColor.RED + "Использование: /radiationzone info <name>");
return true;
}
String name = args[1];
RadiationZone zone = zones.get(name);
if (zone == null) {
player.sendMessage(ChatColor.RED + "Радиационная зона с названием '" + name + "' не найдена.");
return true;
}
player.sendMessage(ChatColor.GOLD + "Информация о радиационной зоне '" + name + "':");
player.sendMessage(ChatColor.WHITE + "Координаты: [" + zone.minX + ", " + zone.minY + ", " + zone.minZ + "] до [" + zone.maxX + ", " + zone.maxY + ", " + zone.maxZ + "]");
player.sendMessage(ChatColor.WHITE + "Текущий уровень радиации: " + zone.getLevel());
return true;
}
/**
* Helper method to check if a player is wearing full radiation protection.
*
* @param player Player to check
* @return true if player is wearing full protection, false otherwise
*/
private boolean isWearingFullProtection(Player player) {
PlayerInventory inv = player.getInventory();
ItemStack helmet = inv.getHelmet();
ItemStack chestplate = inv.getChestplate();
ItemStack leggings = inv.getLeggings();
ItemStack boots = inv.getBoots();
ItemStack gloves = inv.getItemInOffHand(); // Assuming gloves are in off-hand; adjust as needed
return isProtectiveItem(helmet, ChatColor.WHITE + "Противогаз") &&
isProtectiveItem(chestplate, ChatColor.WHITE + "Химический костюм") &&
isProtectiveItem(leggings, ChatColor.GREEN + "Радиационные штаны") &&
isProtectiveItem(boots, ChatColor.GREEN + "Радиационные ботинки") &&
isProtectiveItem(gloves, ChatColor.GREEN + "Защитные перчатки");
}
/**
* Helper method to verify if an item is part of the radiation protection set.
*
* @param item ItemStack item
* @param name Expected name of the protective item
* @return true if item matches the name, false otherwise
*/
private boolean isProtectiveItem(ItemStack item, String name) {
if (item == null || !item.hasItemMeta() || !item.getItemMeta().hasDisplayName()) return false;
String itemName = ChatColor.stripColor(item.getItemMeta().getDisplayName());
String expectedName = ChatColor.stripColor(name);
return itemName.equalsIgnoreCase(expectedName);
}
/**
* Start spawning random radiation zones based on config settings.
*/
private void startRandomRadiationZoneSpawner() {
long interval = config.getLong("rad_zone.random_spawn_interval", 7200);
Bukkit.getScheduler().runTaskTimer(this, () -> {
double minX = random.nextDouble() * 16000 - 8000;
double minY = 0;
double minZ = random.nextDouble() * 16000 - 8000;
double maxX = minX + random.nextInt(50) + 50;
double maxY = 256;
double maxZ = minZ + random.nextInt(50) + 50;
int initialLevel = random.nextInt(config.getInt("rad_zone.max_level", 5) - config.getInt("rad_zone.min_level", 1) + 1) + config.getInt("rad_zone.min_level", 1);
String zoneName = "РадЗона-" + System.currentTimeMillis();
int decreaseInterval = random.nextInt(config.getInt("rad_zone.max_decrease_interval", 4800) - config.getInt("rad_zone.min_decrease_interval", 1200) + 1) + config.getInt("rad_zone.min_decrease_interval", 1200);
// Validate coordinates if necessary (optional)
// Create the radiation zone
RadiationZone zone = new RadiationZone(minX, minY, minZ, maxX, maxY, maxZ, initialLevel, zoneName, decreaseInterval);
zones.put(zoneName, zone);
zone.startRadiation();
Bukkit.broadcastMessage(ChatColor.GOLD + "Появилась новая радиационная зона: " + zoneName);
}, interval, interval); // Initial delay: interval ticks, Repeat: interval ticks
}
/**
* RadiationZone class handling radiation effects within a defined area.
*/
private class RadiationZone {
private final double minX, minY, minZ, maxX, maxY, maxZ;
private int level;
private final String name;
private final int decreaseInterval;
private BukkitTask task;
public RadiationZone(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, int initialLevel, String name, int decreaseInterval) {
this.minX = Math.min(minX, maxX);
this.minY = Math.min(minY, maxY);
this.minZ = Math.min(minZ, maxZ);
this.maxX = Math.max(minX, maxX);
this.maxY = Math.max(minY, maxY);
this.maxZ = Math.max(minZ, maxZ);
this.level = initialLevel;
this.name = name;
this.decreaseInterval = decreaseInterval;
}
/**
* Get current radiation level of the zone.
*
* @return Current level
*/
public int getLevel() {
return level;
}
/**
* Start applying radiation effects to players in the zone and decrease level over time.
*/
public void startRadiation() {
task = new BukkitRunnable() {
@Override
public void run() {
if (level <= 0) {
endZone();
return;
}
// Apply radiation effects to players in zone
for (Player player : Bukkit.getOnlinePlayers()) {
if (isInZone(player.getLocation())) {
// If player is spectator or creative, switch to survival
if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) {
player.setGameMode(GameMode.SURVIVAL);
player.sendMessage(ChatColor.RED + "Вы были переключены в режим выживания из-за радиационной зоны.");
}
applyRadiationEffects(player);
}
}
// Show particles in zone
showParticles();
// Decrease level
level--;
if (level > 0) {
Bukkit.broadcastMessage(ChatColor.YELLOW + "Уровень радиации в зоне '" + name + "' снизился до " + level);
}
if (level <= 0) {
Bukkit.broadcastMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' больше не активна.");
endZone();
}
}
}.runTaskTimer(RadiationPlugin.this, 0L, decreaseInterval); // Initial delay: 0 ticks, Repeat: decreaseInterval ticks
}
/**
* Force end the radiation zone.
*/
public void forceEndZone() {
if (task != null) {
task.cancel();
}
endZone();
}
/**
* End the radiation zone by removing from zones map and cancelling tasks.
*/
private void endZone() {
zones.remove(name);
if (task != null) {
task.cancel();
}
}
/**
* Check if a location is inside this radiation zone.
*/
private boolean isInZone(Location loc) {
return loc.getX() >= minX && loc.getX() <= maxX &&
loc.getY() >= minY && loc.getY() <= maxY &&
loc.getZ() >= minZ && loc.getZ() <= maxZ;
}
/**
* Show particles within the zone (for visualization).
*/
private void showParticles() {
World world = Bukkit.getWorlds().get(0); // Use the first world; adjust if multiple worlds
if (world == null) return;
// Display particles at regular intervals for visualization (optional)
double particleDensity = 50; // Average distance between particles
for (double x = minX; x <= maxX; x += particleDensity) {
for (double z = minZ; z <= maxZ; z += particleDensity) {
double y = world.getHighestBlockYAt((int) x, (int) z) + 1;
Location loc = new Location(world, x, y, z);
world.spawnParticle(Particle.REDSTONE, loc, 10, 0.5, 0.5, 0.5, 0.05, new Particle.DustOptions(Color.GRAY, 1f));
}
}
}
/**
* Apply radiation effects to a player based on current level.
*/
private void applyRadiationEffects(Player player) {
UUID playerId = player.getUniqueId();
int currentRadiation = radiationLevels.getOrDefault(playerId, 0);
if (isWearingFullProtection(player)) {
// Player has full protection, skip effects
return;
}
if (level > 0) {
List<String> effectsList = config.getStringList("radiation.levels." + level + ".effects");
int duration = config.getInt("radiation.levels." + level + ".duration", 200); // duration in ticks
int amplifier = config.getInt("radiation.levels." + level + ".amplifier", 0); // amplifier
for (String effectName : effectsList) {
PotionEffectType effectType = PotionEffectType.getByName(effectName);
if (effectType != null) {
PotionEffect effect = new PotionEffect(effectType, duration, amplifier);
player.addPotionEffect(effect, true); // true: override existing
} else {
getLogger().warning("PotionEffectType '" + effectName + "' не найден.");
}
}
// Increase player's radiation level
radiationLevels.put(playerId, currentRadiation + level);
}
}
}
/**
* Degrade player's equipment within the radiation zone.
*
* @param player Player whose equipment is to be degraded
*/
private void degradePlayerEquipment(Player player) {
PlayerInventory inventory = player.getInventory();
ItemStack[] equipment = {
inventory.getHelmet(),
inventory.getChestplate(),
inventory.getLeggings(),
inventory.getBoots(),
inventory.getItemInMainHand(),
inventory.getItemInOffHand()
};
// Iterate over each piece of equipment
for (ItemStack item : equipment) {
if (item != null) {
ItemMeta meta = item.getItemMeta();
if (meta instanceof Damageable) {
Damageable damageable = (Damageable) meta;
int currentDamage = damageable.getDamage();
int degradationAmount = config.getInt("radiation.levels." + ((RadiationZone) zones.get(name)).getLevel() + ".degrade_factor", 1);
int newDamage = currentDamage + degradationAmount;
damageable.setDamage(newDamage);
item.setItemMeta(damageable); // Set the updated meta back to the item
// Check if item should break
if (newDamage >= item.getType().getMaxDurability()) {
String itemName = item.hasItemMeta() && item.getItemMeta().hasDisplayName()
? item.getItemMeta().getDisplayName()
: item.getType().toString();
// Remove the item from inventory
if (item.equals(inventory.getItemInMainHand())) {
inventory.setItemInMainHand(null);
} else if (item.equals(inventory.getItemInOffHand())) {
inventory.setItemInOffHand(null);
} else {
// Iterate through inventory slots to remove the specific item
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack invItem = inventory.getItem(i);
if (invItem != null && invItem.equals(item)) {
inventory.setItem(i, null);
break;
}
}
}
player.sendMessage(ChatColor.RED + "Ваш предмет '" + itemName + "' разрушился из-за радиации!");
}
}
}
}
}
Понятно, вы хотите упростить плагин, оставив только противогаз, сделать радиационные зоны постоянными и постоянно проверять игроков на нахождение в зонах радиации, применяя соответствующие эффекты. Ниже представлен полный обновленный код плагина RadiationPlugin, который соответствует вашим требованиям:
- Удалены все предметы, кроме противогаза
- Радиоактивные зоны постоянные
- Каждые 2 секунды проверяется нахождение игроков в зонах радиации
- Применяются эффекты радиации на основе суммарного уровня радиации
- Противогаз позволяет избежать эффектов радиации
Обновлённый Файл Конфигурации (config.yml)
radiation_zones:
# Пример радиационной зоны
Zone1:
min_x: 100
min_y: 64
min_z: 100
max_x: 200
max_y: 80
max_z: 200
radiation: 150
effect_mappings:
# Порог уровня радиации и соответствующие эффекты
100:
duration: 40 # Длительность эффекта в тиках (2 секунды)
amplifier: 1
effects:
- POISON
200:
duration: 40
amplifier: 2
effects:
- POISON
- CONFUSION
300:
duration: 40
amplifier: 3
effects:
- POISON
- CONFUSION
- BLINDNESS
name: RadiationPlugin
version: 1.0
main: com.yourpackage.RadiationPlugin
api-version: 1.20
commands:
radiationzone:
description: Управление радиационными зонами
usage: /radiationzone <create|delete|list|info> [args]
permission: radiationplugin.radiationzone
radiationcheck:
description: Проверить уровень радиации
usage: /radiationcheck
permission: radiationplugin.radiationcheck
permissions:
radiationplugin.radiationzone:
description: Позволяет управлять радиационными зонами
default: op
radiationplugin.radiationcheck:
description: Позволяет проверять уровень радиации
default: true
Обновлённый Java Код Плагина (RadiationPlugin.java)
package com.yourpackage;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import java.util.*;
public class RadiationPlugin extends JavaPlugin implements CommandExecutor, TabCompleter {
// Map to store active Radiation Zones by their name
private final Map<String, RadiationZone> zones = new HashMap<>();
// Map to store radiation thresholds and their corresponding effects
private final TreeMap<Integer, EffectMapping> effectMappings = new TreeMap<>(Collections.reverseOrder());
private FileConfiguration config;
@Override
public void onEnable() {
// Save and load configuration
saveDefaultConfig();
config = getConfig();
// Load effect mappings
loadEffectMappings();
// Load radiation zones
loadRadiationZones();
// Register commands
getCommand("radiationzone").setExecutor(this);
getCommand("radiationzone").setTabCompleter(this);
getCommand("radiationcheck").setExecutor(this);
// Register crafting recipes
registerRecipes();
// Start the radiation checker task
startRadiationCheckerTask();
getLogger().info("RadiationPlugin включен!");
}
@Override
public void onDisable() {
// Save radiation zones to config
saveRadiationZones();
getLogger().info("RadiationPlugin выключен!");
}
/**
* Load effect mappings from config.
*/
private void loadEffectMappings() {
ConfigurationSection section = config.getConfigurationSection("effect_mappings");
if (section != null) {
for (String key : section.getKeys(false)) {
try {
int threshold = Integer.parseInt(key);
ConfigurationSection mappingSection = section.getConfigurationSection(key);
int duration = mappingSection.getInt("duration", 40);
int amplifier = mappingSection.getInt("amplifier", 1);
List<String> effects = mappingSection.getStringList("effects");
effectMappings.put(threshold, new EffectMapping(duration, amplifier, effects));
} catch (NumberFormatException e) {
getLogger().warning("Неверный порог уровня радиации: " + key);
}
}
} else {
getLogger().warning("Отсутствует секция effect_mappings в config.yml!");
}
}
/**
* Load radiation zones from config.
*/
private void loadRadiationZones() {
ConfigurationSection zonesSection = config.getConfigurationSection("radiation_zones");
if (zonesSection != null) {
for (String zoneName : zonesSection.getKeys(false)) {
ConfigurationSection zoneConfig = zonesSection.getConfigurationSection(zoneName);
if (zoneConfig != null) {
double minX = zoneConfig.getDouble("min_x");
double minY = zoneConfig.getDouble("min_y");
double minZ = zoneConfig.getDouble("min_z");
double maxX = zoneConfig.getDouble("max_x");
double maxY = zoneConfig.getDouble("max_y");
double maxZ = zoneConfig.getDouble("max_z");
int radiation = zoneConfig.getInt("radiation", 100);
RadiationZone zone = new RadiationZone(zoneName, minX, minY, minZ, maxX, maxY, maxZ, radiation);
zones.put(zoneName, zone);
}
}
}
}
/**
* Save radiation zones to config.
*/
private void saveRadiationZones() {
ConfigurationSection zonesSection = config.getConfigurationSection("radiation_zones");
if (zonesSection != null) {
zonesSection.getKeys(false).forEach(zonesSection::set); // Clear existing zones
}
for (RadiationZone zone : zones.values()) {
ConfigurationSection zoneConfig = config.createSection("radiation_zones." + zone.getName());
zoneConfig.set("min_x", zone.minX);
zoneConfig.set("min_y", zone.minY);
zoneConfig.set("min_z", zone.minZ);
zoneConfig.set("max_x", zone.maxX);
zoneConfig.set("max_y", zone.maxY);
zoneConfig.set("max_z", zone.maxZ);
zoneConfig.set("radiation", zone.radiation);
}
saveConfig();
}
/**
* Register custom crafting recipes for radiation equipment and items.
* Оставлен только рецепт для противогаза.
*/
private void registerRecipes() {
// Создание Предмета: Противогаз
ItemStack gasMask = createCustomItem(Material.LEATHER_HELMET, ChatColor.AQUA + "Противогаз", null);
NamespacedKey gasMaskKey = new NamespacedKey(this, "gas_mask");
ShapedRecipe gasMaskRecipe = new ShapedRecipe(gasMaskKey, gasMask);
gasMaskRecipe.shape(" I ", "IRI", " R ");
gasMaskRecipe.setIngredient('I', Material.IRON_INGOT);
gasMaskRecipe.setIngredient('R', Material.REDSTONE);
Bukkit.addRecipe(gasMaskRecipe);
}
/**
* Helper method to create a custom item with name and lore.
*
* @param material Material of the item
* @param name Display name of the item
* @param lore Lore of the item (can be null)
* @return Custom ItemStack
*/
private ItemStack createCustomItem(Material material, String name, List<String> lore) {
ItemStack item = new ItemStack(material);
if (name != null || lore != null) {
ItemMeta meta = item.getItemMeta();
if (meta != null) {
if (name != null) {
meta.setDisplayName(name);
}
if (lore != null) {
meta.setLore(lore);
}
meta.setUnbreakable(true); // Сделаем противогаз неразрушимым
item.setItemMeta(meta);
}
}
return item;
}
/**
* Handle commands.
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Handle /radiationcheck
if (command.getName().equalsIgnoreCase("radiationcheck")) {
if (!sender.hasPermission("radiationplugin.radiationcheck")) {
sender.sendMessage(ChatColor.RED + "У вас нет прав для выполнения этой команды.");
return true;
}
if (!(sender instanceof Player)) {
sender.sendMessage("Эта команда может использоваться только игроками.");
return true;
}
Player player = (Player) sender;
int totalRadiation = getPlayerTotalRadiation(player);
player.sendMessage(ChatColor.YELLOW + "Ваш суммарный уровень радиации: " + totalRadiation);
return true;
}
// Handle /radiationzone
if (command.getName().equalsIgnoreCase("radiationzone")) {
if (!sender.hasPermission("radiationplugin.radiationzone")) {
sender.sendMessage(ChatColor.RED + "У вас нет прав для выполнения этой команды.");
return true;
}
if (!(sender instanceof Player)) {
sender.sendMessage("Эта команда может использоваться только игроками.");
return true;
}
Player player = (Player) sender;
if (args.length == 0) {
player.sendMessage(ChatColor.RED + "Использование: /radiationzone <create|delete|list|info> [args]");
return true;
}
switch (args[0].toLowerCase()) {
case "create":
return handleCreateZone(player, args);
case "delete":
return handleDeleteZone(player, args);
case "list":
return handleListZones(player);
case "info":
return handleInfoZone(player, args);
default:
player.sendMessage(ChatColor.RED + "Неверная подкоманда. Используйте: create, delete, list, info");
return true;
}
}
// Unhandled command
return false;
}
/**
* Handle the creation of a radiation zone.
*
* @param player Player executing the command
* @param args Command arguments
* @return true
*/
private boolean handleCreateZone(Player player, String[] args) {
if (args.length != 7) { // /radiationzone create <level> <radius> <name>
player.sendMessage(ChatColor.RED + "Использование: /radiationzone create <название> <min.x> <min.y> <min.z> <max.x> <max.y> <max.z> <radiation>");
return true;
}
try {
String name = args[1];
double minX = Double.parseDouble(args[2]);
double minY = Double.parseDouble(args[3]);
double minZ = Double.parseDouble(args[4]);
double maxX = Double.parseDouble(args[5]);
double maxY = Double.parseDouble(args[6]);
double maxZ = Double.parseDouble(args[7]);
int radiation = Integer.parseInt(args[8]);
// Validate radiation
if (radiation <= 0) {
player.sendMessage(ChatColor.RED + "Уровень радиации должен быть положительным числом.");
return true;
}
// Check if zone with same name exists
if (zones.containsKey(name)) {
player.sendMessage(ChatColor.RED + "Радиационная зона с таким названием уже существует.");
return true;
}
// Create and store the zone
RadiationZone zone = new RadiationZone(name, minX, minY, minZ, maxX, maxY, maxZ, radiation);
zones.put(name, zone);
saveRadiationZones();
player.sendMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' успешно создана.");
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.RED + "Ошибка: убедитесь, что координаты и уровень радиации указаны числами.");
return true;
} catch (ArrayIndexOutOfBoundsException e) {
player.sendMessage(ChatColor.RED + "Недостаточно аргументов. Используйте: /radiationzone create <название> <min.x> <min.y> <min.z> <max.x> <max.y> <max.z> <radiation>");
return true;
} catch (Exception e) {
player.sendMessage(ChatColor.RED + "Произошла непредвиденная ошибка при создании зоны.");
e.printStackTrace();
return true;
}
return true;
}
/**
* Handle deletion of a radiation zone.
*
* @param player Player executing the command
* @param args Command arguments
* @return true
*/
private boolean handleDeleteZone(Player player, String[] args) {
if (args.length != 2) { // /radiationzone delete <name>
player.sendMessage(ChatColor.RED + "Использование: /radiationzone delete <имя>");
return true;
}
String name = args[1];
RadiationZone zone = zones.get(name);
if (zone == null) {
player.sendMessage(ChatColor.RED + "Радиационная зона с названием '" + name + "' не найдена.");
return true;
}
zones.remove(name);
saveRadiationZones();
player.sendMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' успешно удалена.");
return true;
}
/**
* Handle listing all active radiation zones.
*
* @param player Player executing the command
* @return true
*/
private boolean handleListZones(Player player) {
if (zones.isEmpty()) {
player.sendMessage(ChatColor.YELLOW + "Нет активных радиационных зон.");
return true;
}
player.sendMessage(ChatColor.GOLD + "Список активных радиационных зон:");
for (RadiationZone zone : zones.values()) {
player.sendMessage(ChatColor.GRAY + "- " + zone.getName() + " (Радиация: " + zone.radiation + ")");
}
return true;
}
/**
* Handle displaying info about a specific radiation zone.
*
* @param player Player executing the command
* @param args Command arguments
* @return true
*/
private boolean handleInfoZone(Player player, String[] args) {
if (args.length != 2) { // /radiationzone info <name>
player.sendMessage(ChatColor.RED + "Использование: /radiationzone info <имя>");
return true;
}
String name = args[1];
RadiationZone zone = zones.get(name);
if (zone == null) {
player.sendMessage(ChatColor.RED + "Радиационная зона с названием '" + name + "' не найдена.");
return true;
}
player.sendMessage(ChatColor.GOLD + "Информация о радиационной зоне '" + name + "':");
player.sendMessage(ChatColor.WHITE + "Координаты: [" + zone.minX + ", " + zone.minY + ", " + zone.minZ + "] до [" + zone.maxX + ", " + zone.maxY + ", " + zone.maxZ + "]");
player.sendMessage(ChatColor.WHITE + "Уровень радиации: " + zone.radiation);
return true;
}
/**
* Start a repeating task that checks every 2 секунды for players in radiation zones.
*/
private void startRadiationCheckerTask() {
BukkitTask task = new BukkitRunnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
int totalRadiation = getPlayerTotalRadiation(player);
if (totalRadiation <= 0) {
continue; // Нет радиации для применения эффектов
}
if (isWearingGasMask(player)) {
continue; // Игрок носит противогаз, эффекты не применяются
}
applyRadiationEffects(player, totalRadiation);
}
}
}.runTaskTimer(this, 0L, 40L); // Каждые 40 тиков (2 секунды)
}
/**
* Calculate the total radiation a player is exposed to based on current zones.
*
* @param player Player to check
* @return Total radiation value
*/
private int getPlayerTotalRadiation(Player player) {
int total = 0;
Location loc = player.getLocation();
for (RadiationZone zone : zones.values()) {
if (zone.isInZone(loc)) {
total += zone.radiation;
}
}
return total;
}
/**
* Check if a player is wearing the Gas Mask.
*
* @param player Player to check
* @return true if wearing Gas Mask, false otherwise
*/
private boolean isWearingGasMask(Player player) {
ItemStack helmet = player.getInventory().getHelmet();
if (helmet == null) return false;
if (helmet.getType() != Material.LEATHER_HELMET) return false;
if (!helmet.hasItemMeta()) return false;
if (!helmet.getItemMeta().hasDisplayName()) return false;
String name = ChatColor.stripColor(helmet.getItemMeta().getDisplayName());
return name.equalsIgnoreCase("Противогаз");
}
/**
* Apply radiation effects to a player based on the total radiation value.
*
* @param player Player to apply effects to
* @param totalRadiation Total radiation value
*/
private void applyRadiationEffects(Player player, int totalRadiation) {
for (Map.Entry<Integer, EffectMapping> entry : effectMappings.entrySet()) {
if (totalRadiation >= entry.getKey()) {
EffectMapping mapping = entry.getValue();
for (String effectName : mapping.effects) {
PotionEffectType effectType = PotionEffectType.getByName(effectName);
if (effectType != null) {
PotionEffect effect = new PotionEffect(effectType, mapping.duration, mapping.amplifier - 1);
player.addPotionEffect(effect, true);
} else {
getLogger().warning("PotionEffectType '" + effectName + "' не найден.");
}
}
break; // Применяем только самое высокое соответствие
}
}
}
/**
* RadiationZone class representing a persistent radiation zone.
*/
private static class RadiationZone {
private final String name;
private final double minX, minY, minZ, maxX, maxY, maxZ;
private final int radiation;
public RadiationZone(String name, double minX, double minY, double minZ, double maxX, double maxY, double maxZ, int radiation) {
this.name = name;
this.minX = Math.min(minX, maxX);
this.minY = Math.min(minY, maxY);
this.minZ = Math.min(minZ, maxZ);
this.maxX = Math.max(minX, maxX);
this.maxY = Math.max(minY, maxY);
this.maxZ = Math.max(minZ, maxZ);
this.radiation = radiation;
}
public String getName() {
return name;
}
/**
* Check if a location is inside this radiation zone.
*
* @param loc Location to check
* @return true if inside, false otherwise
*/
public boolean isInZone(Location loc) {
return loc.getX() >= minX && loc.getX() <= maxX &&
loc.getY() >= minY && loc.getY() <= maxY &&
loc.getZ() >= minZ && loc.getZ() <= maxZ;
}
}
/**
* EffectMapping class representing the mapping from radiation threshold to effects.
*/
private static class EffectMapping {
private final int duration;
private final int amplifier;
private final List<String> effects;
public EffectMapping(int duration, int amplifier, List<String> effects) {
this.duration = duration;
this.amplifier = amplifier;
this.effects = effects;
}
}
/**
* Provide tab completion for the /radiationzone command.
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (command.getName().equalsIgnoreCase("radiationzone")) {
if (args.length == 1) {
return Arrays.asList("create", "delete", "list", "info");
} else if (args.length >= 2) {
String subCommand = args[0].toLowerCase();
if (subCommand.equals("delete") || subCommand.equals("info")) {
return new ArrayList<>(zones.keySet());
}
}
}
return Collections.emptyList();
}
}
Объяснение Основных Изменений и Функциональности
-
Удаление Ненужных Предметов:
- В методе
registerRecipes() остался только рецепт для создания противогаза. Все остальные рецепты были удалены согласно вашим требованиям.
-
Постоянные Радиоактивные Зоны:
- Зоны загружаются из конфигурационного файла
config.yml при инициализации плагина и сохраняются при его отключении.
- Радиоактивные зоны не деградируют и остаются активными постоянно, пока не будут удалены вручную через команду.
-
Проверка Игроков на Нахождение в Зоне Радиации:
- Создана задача, которая выполняется каждые 2 секунды (
40L тиков), проверяющая, находятся ли игроки в радиационных зонах.
- Если игрок находится в одной или нескольких зонах радиации, суммируется общий уровень радиации и применяются соответствующие эффекты.
- Если игрок носит противогаз, эффекты радиации не применяются.
-
Противогаз:
- Противогаз реализован как настраиваемый предмет (
Leather Helmet) с уникальным именем "Противогаз".
- Если игрок носит противогаз, он защищён от эффектов радиации.
-
Эффекты Радиоактивности:
- В конфигурации
config.yml определены пороги уровня радиации и соответствующие им эффекты. Например, при радиации 100 накладывается эффект POISON I, при 200 – POISON II и CONFUSION, и т.д.
- Плагин применяет только самый высокий соответствующий эффект на основе текущего уровня радиации.
-
Команды Управления Радиируемыми Зонами:
/radiationzone create <название> <min.x> <min.y> <min.z> <max.x> <max.y> <max.z> <radiation> – создание новой радиационной зоны.
/radiationzone delete <имя> – удаление существующей радиационной зоны.
/radiationzone list – отображение списка всех активных радиационных зон.
/radiationzone info <имя> – отображение информации об определённой радиационной зоне.
/radiationcheck – проверка текущего суммарного уровня радиации игрока.
-
Tab-Completion для Команд:
- Поддержка автодополнения для команды
/radiationzone, предлагая подкоманды и имена зон.
-
Сохранение и Загрузка Конфигурации:
Дополнительные Рекомендации
Заключение
Данный обновлённый плагин RadiationPlugin соответствует вашим требованиям, обеспечивая постоянные радиационные зоны, защиту через противогаз и динамическое применение эффектов радиации. Вы можете дополнительно настроить его поведение через конфигурационный файл config.yml в зависимости от специфических нужд вашего сервера Minecraft.