public class Rocket {
protected final Player launcher;
protected final RocketType type;
protected final Location target;
protected final RocketPlugin plugin;
protected Location currentLocation;
protected double speed = 1.0;
code
Assistant
public Rocket(Player launcher, RocketType type, Location target, RocketPlugin plugin) {
this.launcher = launcher;
this.type = type;
this.target = target;
this.plugin = plugin;
this.currentLocation = launcher.getLocation().clone();
}
public void launch() {
final World world = this.launcher.getWorld();
if (world == null) {
this.launcher.sendMessage("§cОшибка: Мир не найден.");
} else {
world.spawnParticle(this.type.getLaunchParticle(), this.currentLocation, 20, 0.5, 0.5, 0.5, 0.05);
world.playSound(this.currentLocation, this.type.getLaunchSound(), 1.0F, 1.0F);
(new BukkitRunnable() {
public void run() {
Vector direction = Rocket.this.target.clone().subtract(Rocket.this.currentLocation).toVector();
double distance = direction.length();
if (distance < (double)Rocket.this.type.getRange()) {
Rocket.this.explode();
this.cancel();
} else {
direction = direction.normalize().multiply(Rocket.this.speed);
Rocket.this.currentLocation.add(direction);
world.spawnParticle(Rocket.this.type.getLaunchParticle(), Rocket.this.currentLocation, 5, 0.1, 0.1, 0.1, 0.02);
}
}
}).runTaskTimer(this.plugin, 0L, 1L);
}
}
protected void explode() {
World world = this.target.getWorld();
if (world == null) {
this.launcher.sendMessage("§cОшибка: Целевая локация не найдена.");
} else {
if (this.type.isOptimized()) {
this.optimizedExplode(world);
} else {
this.standardExplode(world);
}
}
}
protected void standardExplode(final World world) {
world.createExplosion(this.target, (float)this.type.getPower(), false, true);
world.spawnParticle(this.type.getExplosionParticle(), this.target, 100, 1.0, 1.0, 1.0, 0.1);
world.playSound(this.target, this.type.getExplosionSound(), 1.0F, 1.0F);
if (this.type.getName().equalsIgnoreCase("SUPER_NUCLEAR") || this.type.getName().equalsIgnoreCase("MEGA_NUCLEAR") || this.type.getName().equalsIgnoreCase("EXTREME_NUCLEAR") || this.type.getName().equalsIgnoreCase("ULTRA_NUCLEAR") || this.type.getName().equalsIgnoreCase("USSR")) {
double effectRadius = 20.0;
Collection<Entity> entities = world.getNearbyEntities(this.target, effectRadius, effectRadius, effectRadius);
Iterator var5 = entities.iterator();
while(var5.hasNext()) {
Entity entity = (Entity)var5.next();
if (entity instanceof Player) {
Player player = (Player)entity;
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 200, 1));
player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 200, 1));
}
}
(new BukkitRunnable() {
private int ticks = 0;
private final int maxTicks = 100;
public void run() {
if (this.ticks >= 100) {
this.cancel();
} else {
world.spawnParticle(Particle.EXPLOSION_HUGE, Rocket.this.target, 50, 2.0, 2.0, 2.0, 0.05);
world.spawnParticle(Particle.LAVA, Rocket.this.target, 100, 3.0, 3.0, 3.0, 0.02);
world.spawnParticle(Particle.FIREWORKS_SPARK, Rocket.this.target, 100, 4.0, 4.0, 4.0, 0.1);
world.spawnParticle(Particle.END_ROD, Rocket.this.target, 50, 2.0, 2.0, 2.0, 0.05);
world.playSound(Rocket.this.target, Sound.ENTITY_GENERIC_EXPLODE, 1.0F, 1.0F);
++this.ticks;
}
}
}).runTaskTimer(this.plugin, 0L, 1L);
}
}
protected void optimizedExplode(final World world) {
world.createExplosion(this.target, (float)this.type.getPower(), false, true);
world.spawnParticle(this.type.getExplosionParticle(), this.target, 50, 0.5, 0.5, 0.5, 0.02);
world.playSound(this.target, this.type.getExplosionSound(), 1.0F, 1.0F);
double effectRadius = (double)(this.type.getRange() / 2);
Collection<Entity> entities = world.getNearbyEntities(this.target, effectRadius, effectRadius, effectRadius);
Iterator var5 = entities.iterator();
while(var5.hasNext()) {
Entity entity = (Entity)var5.next();
if (entity instanceof Player player) {
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 100, 1));
}
}
(new BukkitRunnable() {
private int ticks = 0;
private final int maxTicks = 50;
public void run() {
if (this.ticks >= 50) {
this.cancel();
} else {
world.spawnParticle(Particle.SMOKE_NORMAL, Rocket.this.target, 30, 1.0, 1.0, 1.0, 0.01);
world.spawnParticle(Particle.FLAME, Rocket.this.target, 50, 1.0, 1.0, 1.0, 0.02);
world.playSound(Rocket.this.target, Sound.ENTITY_GENERIC_EXPLODE, 1.0F, 1.0F);
++this.ticks;
}
}
}).runTaskTimer(this.plugin, 0L, 1L);
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
public class RocketCommand implements CommandExecutor {
private final RocketManager rocketManager;
private final StatsManager statsManager;
private final RocketPlugin plugin;
code
public RocketCommand(RocketManager rocketManager, StatsManager statsManager, RocketPlugin plugin) {
this.rocketManager = rocketManager;
this.statsManager = statsManager;
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("rocketplugin.use")) {
sender.sendMessage(ChatColor.RED + "§cУ вас нет разрешения использовать эту команду.");
return true;
} else if (args.length == 0) {
sender.sendMessage(ChatColor.RED + "§cИспользование: /rocket <launch|give|stats|reload> [параметры]");
return true;
} else {
switch (args[0].toLowerCase()) {
case "launch" -> this.handleLaunch(sender, args);
case "give" -> this.handleGive(sender, args);
case "stats" -> this.handleStats(sender, args);
case "reload" -> this.handleReload(sender, args);
default -> sender.sendMessage(ChatColor.RED + "§cНеизвестная подкоманда. Использование: /rocket <launch|give|stats|reload> [параметры]");
}
return true;
}
}
private void handleLaunch(CommandSender sender, String[] args) {
if (sender instanceof Player player) {
if (args.length < 5) {
player.sendMessage(ChatColor.RED + "§cИспользование: /rocket launch <type> <x> <y> <z> [delay]");
player.sendMessage(ChatColor.YELLOW + "§eПримечание: delay - опциональный параметр (1-30 секунд)");
} else {
String typeName = args[1].toUpperCase();
RocketType type = this.rocketManager.getRocketType(typeName);
if (type == null) {
player.sendMessage(ChatColor.RED + "§cНеверный тип ракеты. Используйте /rocket для просмотра доступных типов.");
} else {
double x;
double y;
double z;
try {
x = Double.parseDouble(args[2]);
y = Double.parseDouble(args[3]);
z = Double.parseDouble(args[4]);
} catch (NumberFormatException var15) {
player.sendMessage(ChatColor.RED + "§cКоординаты должны быть действительными числами.");
return;
}
Location target = new Location(player.getWorld(), x, y, z);
int delay = 0;
if (args.length >= 6) {
try {
delay = Integer.parseInt(args[5]);
if (delay < 1 || delay > 30) {
player.sendMessage(ChatColor.RED + "§cЗадержка должна быть между 1 и 30 секундами.");
return;
}
} catch (NumberFormatException var16) {
player.sendMessage(ChatColor.RED + "§cЗадержка должна быть целым числом.");
return;
}
}
this.rocketManager.launchRocket(player, type, target, delay);
}
}
} else {
sender.sendMessage(ChatColor.RED + "§cТолько игроки могут запускать ракеты.");
}
}
private void handleGive(CommandSender sender, String[] args) {
if (!sender.hasPermission("rocketplugin.give")) {
sender.sendMessage(ChatColor.RED + "§cУ вас нет разрешения выдавать ракеты.");
} else if (args.length < 4) {
sender.sendMessage(ChatColor.RED + "§cИспользование: /rocket give <player> <type> <amount>");
} else {
String targetName = args[1];
Player targetPlayer = Bukkit.getPlayerExact(targetName);
if (targetPlayer == null) {
sender.sendMessage(ChatColor.RED + "§cИгрок не найден или не онлайн.");
} else {
String typeName = args[2].toUpperCase();
RocketType type = this.rocketManager.getRocketType(typeName);
if (type == null) {
sender.sendMessage(ChatColor.RED + "§cНеверный тип ракеты. Используйте /rocket для просмотра доступных типов.");
} else {
int amount;
try {
amount = Integer.parseInt(args[3]);
if (amount <= 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException var9) {
sender.sendMessage(ChatColor.RED + "§cКоличество должно быть положительным целым числом.");
return;
}
this.statsManager.addRockets(targetPlayer, type, amount);
ChatColor var10001 = ChatColor.GREEN;
sender.sendMessage("" + var10001 + "§aВыдали " + amount + " ракет типа " + type.getName() + " игроку " + targetPlayer.getName() + ".");
var10001 = ChatColor.GREEN;
targetPlayer.sendMessage("" + var10001 + "§aВам выдали " + amount + " ракет типа " + type.getName() + " от " + sender.getName() + ".");
}
}
}
}
private void handleStats(CommandSender sender, String[] args) {
if (args.length < 2) {
if (sender instanceof Player) {
Player player = (Player)sender;
sender.sendMessage(this.statsManager.getStats(player));
} else {
sender.sendMessage(ChatColor.RED + "§cКонсоль не имеет статистики.");
}
} else {
String targetName = args[1];
Player targetPlayer = Bukkit.getPlayerExact(targetName);
if (targetPlayer == null) {
sender.sendMessage(ChatColor.RED + "§cИгрок не найден или не онлайн.");
} else {
sender.sendMessage(this.statsManager.getStats(targetPlayer));
}
}
}
private void handleReload(CommandSender sender, String[] args) {
if (!sender.hasPermission("rocketplugin.reload")) {
sender.sendMessage(ChatColor.RED + "§cУ вас нет разрешения перезагружать конфигурацию.");
} else {
this.plugin.reloadConfig();
this.rocketManager.loadRocketTypes();
sender.sendMessage(ChatColor.GREEN + "§aКонфигурация плагина успешно перезагружена.");
}
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
public class RocketManager {
private final RocketPlugin plugin;
private StatsManager statsManager;
private PVOManager pvoManager;
private final Random random;
private final Map<String, RocketType> rocketTypes;
code
public RocketManager(RocketPlugin plugin) {
this.plugin = plugin;
this.random = new Random();
this.rocketTypes = new HashMap();
this.loadRocketTypes();
this.pvoManager = new PVOManager(plugin);
}
public void setStatsManager(StatsManager statsManager) {
this.statsManager = statsManager;
this.pvoManager.setStatsManager(statsManager);
}
public PVOManager getPvoManager() {
return this.pvoManager;
}
public void loadRocketTypes() {
FileConfiguration config = this.plugin.getConfig();
ConfigurationSection rocketsSection = config.getConfigurationSection("rockets");
if (rocketsSection == null) {
this.plugin.getLogger().severe("§cРаздел 'rockets' не найден в config.yml! Плагин отключен.");
this.plugin.getServer().getPluginManager().disablePlugin(this.plugin);
} else {
Iterator var3 = rocketsSection.getKeys(false).iterator();
while(var3.hasNext()) {
String key = (String)var3.next();
ConfigurationSection rocketSection = rocketsSection.getConfigurationSection(key);
if (rocketSection != null) {
double power = rocketSection.getDouble("power");
int range = rocketSection.getInt("range");
String launchParticleStr = rocketSection.getString("launchParticle", "FLAME");
String launchSoundStr = rocketSection.getString("launchSound", "ENTITY_FIREWORK_ROCKET_LAUNCH");
String explosionSoundStr = rocketSection.getString("explosionSound", "ENTITY_FIREWORK_ROCKET_LAUNCH");
String explosionParticleStr = rocketSection.getString("explosionParticle", "SMOKE_NORMAL");
int successChance = rocketSection.getInt("successChance", 50);
boolean optimized = rocketSection.getBoolean("optimized", false);
Particle launchParticle;
try {
launchParticle = Particle.valueOf(launchParticleStr);
} catch (IllegalArgumentException var23) {
this.plugin.getLogger().warning("§cНеизвестный тип частицы запуска '" + launchParticleStr + "' для ракеты '" + key + "'. Используется FLAME.");
launchParticle = Particle.FLAME;
}
Sound launchSound;
try {
launchSound = Sound.valueOf(launchSoundStr);
} catch (IllegalArgumentException var22) {
this.plugin.getLogger().warning("§cНеизвестный звук запуска '" + launchSoundStr + "' для ракеты '" + key + "'. Используется ENTITY_FIREWORK_ROCKET_LAUNCH.");
launchSound = Sound.ENTITY_FIREWORK_ROCKET_LAUNCH;
}
Sound explosionSound;
try {
explosionSound = Sound.valueOf(explosionSoundStr);
} catch (IllegalArgumentException var21) {
this.plugin.getLogger().warning("§cНеизвестный звук взрыва '" + explosionSoundStr + "' для ракеты '" + key + "'. Используется ENTITY_FIREWORK_ROCKET_LAUNCH.");
explosionSound = Sound.ENTITY_FIREWORK_ROCKET_LAUNCH;
}
Particle explosionParticle;
try {
explosionParticle = Particle.valueOf(explosionParticleStr);
} catch (IllegalArgumentException var20) {
this.plugin.getLogger().warning("§cНеизвестный тип частицы взрыва '" + explosionParticleStr + "' для ракеты '" + key + "'. Используется SMOKE_NORMAL.");
explosionParticle = Particle.SMOKE_NORMAL;
}
RocketType rocketType = new RocketType(key, power, range, launchParticle, launchSound, explosionSound, explosionParticle, successChance, optimized);
this.rocketTypes.put(key.toUpperCase(), rocketType);
}
}
this.plugin.getLogger().info("§aЗагружено " + this.rocketTypes.size() + " типов ракет.");
}
}
public RocketType getRocketType(String name) {
return (RocketType)this.rocketTypes.get(name.toUpperCase());
}
public Map<String, RocketType> getAllRocketTypes() {
return this.rocketTypes;
}
public void launchRocket(final Player player, final RocketType type, final Location target, final int delay) {
if (!target.getWorld().getName().equalsIgnoreCase("P_Drilla")) {
player.sendMessage("§cРакеты могут взрываться только в мире P_Drilla.");
} else if (!this.statsManager.hasRockets(player, type)) {
player.sendMessage("§cУ вас нет ракет типа " + type.getName() + "!");
} else {
this.statsManager.useRocket(player, type);
if (delay > 0) {
player.sendMessage("§eЗапуск ракеты через " + delay + " секунд(ы).");
(new BukkitRunnable() {
private int secondsLeft = delay;
public void run() {
if (this.secondsLeft <= 0) {
this.cancel();
boolean success = RocketManager.this.checkLaunchSuccess(type);
if (success) {
Rocket rocket = type.isOptimized() ? new OptimizedRocket(player, type, target, RocketManager.this.plugin) : new Rocket(player, type, target, RocketManager.this.plugin);
((Rocket)rocket).launch();
player.sendMessage("§aРакета успешно запущена!");
} else {
player.sendMessage("§cРакета не смогла достичь цели и не взорвалась.");
}
} else {
player.sendMessage("§eЗапуск ракеты через " + this.secondsLeft + " секунд(ы).");
--this.secondsLeft;
}
}
}).runTaskTimer(this.plugin, 0L, 20L);
} else {
boolean success = this.checkLaunchSuccess(type);
if (success) {
Rocket rocket = type.isOptimized() ? new OptimizedRocket(player, type, target, this.plugin) : new Rocket(player, type, target, this.plugin);
((Rocket)rocket).launch();
player.sendMessage("§aРакета успешно запущена!");
} else {
player.sendMessage("§cРакета не смогла достичь цели и не взорвалась.");
}
}
}
}
private boolean checkLaunchSuccess(RocketType type) {
int chance = type.getSuccessChance();
int roll = this.random.nextInt(100) + 1;
return roll <= chance;
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
public class RocketType {
private final String name;
private final double power;
private final int range;
private final Particle launchParticle;
private final Sound launchSound;
private final Sound explosionSound;
private final Particle explosionParticle;
private final int successChance;
private final boolean optimized;
code
public RocketType(String name, double power, int range, Particle launchParticle, Sound launchSound, Sound explosionSound, Particle explosionParticle, int successChance, boolean optimized) {
this.name = name;
this.power = power;
this.range = range;
this.launchParticle = launchParticle;
this.launchSound = launchSound;
this.explosionSound = explosionSound;
this.explosionParticle = explosionParticle;
this.successChance = successChance;
this.optimized = optimized;
}
public String getName() {
return this.name;
}
public double getPower() {
return this.power;
}
public int getRange() {
return this.range;
}
public Particle getLaunchParticle() {
return this.launchParticle;
}
public Sound getLaunchSound() {
return this.launchSound;
}
public Sound getExplosionSound() {
return this.explosionSound;
}
public Particle getExplosionParticle() {
return this.explosionParticle;
}
public int getSuccessChance() {
return this.successChance;
}
public boolean isOptimized() {
return this.optimized;
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
public class StatsManager {
private final RocketPlugin plugin;
private final File statsFile;
private FileConfiguration statsConfig;
private final RocketManager rocketManager;
code
public StatsManager(RocketPlugin plugin, RocketManager rocketManager) {
this.plugin = plugin;
this.rocketManager = rocketManager;
this.statsFile = new File(plugin.getDataFolder(), "stats.yml");
if (!this.statsFile.exists()) {
try {
if (plugin.getResource("stats.yml") != null) {
plugin.saveResource("stats.yml", false);
} else {
this.statsConfig = new YamlConfiguration();
this.statsConfig.save(this.statsFile);
}
} catch (IOException var4) {
IOException e = var4;
plugin.getLogger().severe("§cНе удалось создать stats.yml:");
e.printStackTrace();
}
}
this.statsConfig = YamlConfiguration.loadConfiguration(this.statsFile);
}
public void load() {
try {
this.statsConfig.load(this.statsFile);
} catch (Exception var2) {
Exception e = var2;
this.plugin.getLogger().severe("§cНе удалось загрузить stats.yml:");
e.printStackTrace();
}
}
public void save() {
try {
this.statsConfig.save(this.statsFile);
} catch (IOException var2) {
IOException e = var2;
this.plugin.getLogger().severe("§cНе удалось сохранить stats.yml:");
e.printStackTrace();
}
}
public int getRockets(Player player, RocketType type) {
String var10000 = player.getUniqueId().toString();
String path = var10000 + ".rockets." + type.getName();
return this.statsConfig.getInt(path, 0);
}
public void addRockets(Player player, RocketType type, int amount) {
String var10000 = player.getUniqueId().toString();
String path = var10000 + ".rockets." + type.getName();
int current = this.getRockets(player, type);
this.statsConfig.set(path, current + amount);
this.save();
}
public boolean hasRockets(Player player, RocketType type) {
return this.getRockets(player, type) > 0;
}
public void useRocket(Player player, RocketType type) {
String var10000 = player.getUniqueId().toString();
String path = var10000 + ".rockets." + type.getName();
int current = this.getRockets(player, type);
if (current > 0) {
this.statsConfig.set(path, current - 1);
this.save();
}
}
public String getStats(Player player) {
StringBuilder sb = new StringBuilder("§a§lСтатистика Ракет для " + player.getName() + ":\n");
Map<String, RocketType> allTypes = this.rocketManager.getAllRocketTypes();
Iterator var4 = allTypes.values().iterator();
while(var4.hasNext()) {
RocketType type = (RocketType)var4.next();
sb.append("§e").append(type.getName()).append(": §b").append(this.getRockets(player, type)).append("\n");
}
return sb.toString();
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
commands:
rocket:
description: Управление ракетами.
usage: /rocket <launch|give|trade|remove|stats|reload|craft>
aliases: [rk]
permissions:
rocketplugin.use:
description: Разрешение на использование команд RocketPlugin.
default: true
rocketplugin.give:
description: Разрешение на выдачу ракет другим игрокам.
default: op
rocketplugin.trade:
description: Разрешение на торговлю ракетами между игроками.
default: op
rocketplugin.remove:
description: Разрешение на удаление ракет у игроков.
default: op
rocketplugin.reload:
description: Разрешение на перезагрузку конфигурации плагина.
default: op
rocketplugin.craft:
description: Разрешение на крафт ракет.
default: false
Реализуй все функции для всех команд, убери то, что не нужно (пво, крафт ракет и тд).
Реализуй новый метод взрыва ракет, с помощью другой обработки, например с помощью worldedit
Сделай ограничение на кол-во ракет. Изначально 0, чтобы появилось, игроку нужно поставить особый блок (для него команду получения), он его ставит и он добавляет 1 ракету (то есть всего 1 из всех типов). Если этот блок разрушается (он не выпадает ввиде блока, а также его нельзя никак скопировать), то отнимается кол-во ракет возможных (если таких 0, то запуск не возможен)
To achieve your desired functionality for the RocketPlugin, we'll address each of your three requirements step-by-step:
Implement All Functions for Necessary Commands and Remove Unnecessary Features (e.g., PVO, Crafting).
Implement a New Explosion Method Using WorldEdit.
Restrict the Number of Rockets Per Player via a Special Block Mechanism.
Below, I'll guide you through each step, providing updated code snippets and explanations to help you implement these features effectively.
1. Implement All Functions for Necessary Commands and Remove Unnecessary Features
a. Update plugin.yml
First, refine your plugin.yml to remove unused commands (trade, craft, remove) and adjust permissions accordingly.
yaml
name: RocketPlugin
version: 1.0
main: com.yourname.rocketplugin.RocketPlugin
api-version: 1.16
commands:
rocket:
description: Управление ракетами.
usage: /rocket <launch|give|stats|reload>
aliases: [rk]
permissions:
rocketplugin.use:
description: Разрешение на использование команд RocketPlugin.
default: true
rocketplugin.give:
description: Разрешение на выдачу ракет другим игрокам.
default: op
rocketplugin.reload:
description: Разрешение на перезагрузку конфигурации плагина.
default: op
b. Remove PVO-Related Code
Since you want to eliminate the PVO (Point Defense System) features, remove all classes and references associated with PVO, including:
RocketListener (specifically PVO event handlers)
PVOManager
PVOBlock
Related commands (pvo)
Updated RocketPlugin Class:
Here's the updated RocketPlugin class without PVO integration:
java
package com.yourname.rocketplugin;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class RocketPlugin extends JavaPlugin {
private static RocketPlugin instance;
private RocketManager rocketManager;
private StatsManager statsManager;
public RocketPlugin() {
}
public static RocketPlugin getInstance() {
return instance;
}
public RocketManager getRocketManager() {
return this.rocketManager;
}
public StatsManager getStatsManager() {
return this.statsManager;
}
@Override
public void onEnable() {
instance = this;
this.saveDefaultConfig();
// Initialize Managers
this.rocketManager = new RocketManager(this);
this.statsManager = new StatsManager(this, this.rocketManager);
this.rocketManager.setStatsManager(this.statsManager);
// Load Stats
this.statsManager.load();
// Register Commands and Tab Completer
PluginCommand rocketCommand = this.getCommand("rocket");
if (rocketCommand != null) {
rocketCommand.setExecutor(new RocketCommand(this.rocketManager, this.statsManager, this));
rocketCommand.setTabCompleter(new RocketTabCompleter(this));
} else {
this.getLogger().severe("§cНе удалось зарегистрировать команду 'rocket'. Проверьте plugin.yml.");
this.setEnabled(false);
return;
}
// Register Event Listeners
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvents(new RocketListener(this.rocketManager, this), this);
this.getLogger().info("§aRocketPlugin был включен!");
}
@Override
public void onDisable() {
if (this.statsManager != null) {
this.statsManager.save();
}
this.getLogger().info("§cRocketPlugin был отключен!");
}
}
Updated RocketListener Class:
Remove PVO-related event handling but retain relevant explosion event handling.
java
package com.yourname.rocketplugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.util.Collection;
public class RocketListener implements Listener {
private final RocketManager rocketManager;
private final RocketPlugin plugin;
public RocketListener(RocketManager rocketManager, RocketPlugin plugin) {
this.rocketManager = rocketManager;
this.plugin = plugin;
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event) {
World world = event.getEntity().getWorld();
if (!world.getName().equalsIgnoreCase("P_Drilla")) {
event.setCancelled(true);
} else {
// Handle explosion logic if needed
// Currently handled within the Rocket class
}
}
// Remove other PVO-related event handlers
}
Note: Ensure that all references to PVO in other classes (e.g., RocketManager, StatsManager) are also removed or updated accordingly.
c. Update RocketCommand Class
Ensure that the RocketCommand only handles available subcommands: launch, give, stats, reload.
java
With these changes, your plugin now focuses solely on rocket-related functionalities, removing all PVO, trading, crafting, and removal features.
2. Implement a New Explosion Method Using WorldEdit
To leverage WorldEdit for handling rocket explosions, you'll need to integrate the WorldEdit API into your plugin. This approach allows for more advanced and customizable explosion effects, such as generating schematics or using WorldEdit brushes.
a. Add WorldEdit as a Dependency
First, add WorldEdit as a dependency in your project. If you're using Maven, add the following to your pom.xml:
xml
<dependencies>
<!-- Other dependencies -->
<!-- WorldEdit API -->
<dependency>
<groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-bukkit</artifactId>
<version>7.2.0</version> <!-- Use the version compatible with your server -->
<scope>provided</scope>
</dependency>
</dependencies>
Note: Adjust the version number based on your server's WorldEdit version. Ensure that WorldEdit is installed on your server.
If you're not using Maven, download the WorldEdit JAR and include it in your project's build path, marking it as "provided" to avoid bundling it within your plugin's JAR.
b. Update RocketType Explosion Handling
Modify the Rocket class to utilize WorldEdit for explosions. Here's how you can update the explode() method:
Updated Rocket Class:
java
Explanation:
WorldEdit Integration:
The explode() method now utilizes WorldEdit to manipulate the world blocks more intricately during explosions.
Safety Check: Ensures WorldEdit is installed; otherwise, it notifies the player and aborts the explosion.
Explosion Mechanics:
Spherical Explosion: Replaces blocks within a spherical radius with air, simulating an explosion.
Optimized Explosion: You can customize the optimizedExplode method to create more intricate patterns or effects as needed.
Error Handling:
Robust error handling ensures that any issues during the explosion process are caught and reported without crashing the plugin.
c. Permissions for WorldEdit Commands (Optional)
If your explosion method involves executing WorldEdit commands, you might need to handle permissions to prevent misuse. However, in the above implementation, direct WorldEdit commands are not executed, so this step is optional.
3. Restrict the Number of Rockets Per Player via a Special Block Mechanism
To implement a system where players have a limited number of rockets controlled via placing a special block, follow these steps:
a. Define the Special Block
Choose a unique block type that players will place to gain a rocket slot. For example, you can use a beacon block named "Rocket Controller."
b. Create a New Command to Obtain the Special Block
Add a new subcommand getblock to allow players to obtain the special block. Update plugin.yml accordingly.
Update plugin.yml:
yaml
commands:
rocket:
description: Управление ракетами.
usage: /rocket <launch|give|stats|reload|getblock>
aliases: [rk]
permissions:
rocketplugin.use:
description: Разрешение на использование команд RocketPlugin.
default: true
rocketplugin.give:
description: Разрешение на выдачу ракет другим игрокам.
default: op
rocketplugin.reload:
description: Разрешение на перезагрузку конфигурации плагина.
default: op
rocketplugin.getblock:
description: Разрешение на получение блока Rocket Controller.
default: op
Update RocketCommand Class:
Add handling for getblock.
java
private void handleGetBlock(CommandSender sender, String[] args) {
if (!(sender instanceof Player player)) {
sender.sendMessage(ChatColor.RED + "§cТолько игроки могут получать блок Rocket Controller.");
return;
}
if (!sender.hasPermission("rocketplugin.getblock")) {
sender.sendMessage(ChatColor.RED + "§cУ вас нет разрешения получать блок Rocket Controller.");
return;
}
// Give the player a special block with a custom name
org.bukkit.inventory.ItemStack blockItem = new org.bukkit.inventory.ItemStack(org.bukkit.Material.BEACON, 1);
org.bukkit.inventory.meta.ItemMeta meta = blockItem.getItemMeta();
if (meta != null) {
meta.setDisplayName(ChatColor.GOLD + "Rocket Controller");
blockItem.setItemMeta(meta);
}
player.getInventory().addItem(blockItem);
player.sendMessage(ChatColor.GREEN + "§aВы получили блок Rocket Controller.");
}
Update the onCommand Method in RocketCommand:
Add the new subcommand getblock.
java
switch (args[0].toLowerCase()) {
case "launch" -> this.handleLaunch(sender, args);
case "give" -> this.handleGive(sender, args);
case "stats" -> this.handleStats(sender, args);
case "reload" -> this.handleReload(sender, args);
case "getblock" -> this.handleGetBlock(sender, args);
default -> sender.sendMessage(ChatColor.RED + "§cНеизвестная подкоманда. Использование: /rocket <launch|give|stats|reload|getblock>");
}
c. Track Rocket Slots Per Player
Modify StatsManager to track the number of allowed rocket slots per player.
Updated StatsManager Class:
java
d. Handle Block Placement and Destruction
Listen for block placement and destruction events to manage rocket slots.
Add Event Listeners in RocketListener:
java
import org.bukkit.Material;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.ChatColor;
public class RocketListener implements Listener {
private final RocketManager rocketManager;
private final RocketPlugin plugin;
public RocketListener(RocketManager rocketManager, RocketPlugin plugin) {
this.rocketManager = rocketManager;
this.plugin = plugin;
}
// Existing explosion handler...
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
ItemStack placedBlock = event.getItemInHand();
if (placedBlock.getType() == Material.BEACON) {
ItemMeta meta = placedBlock.getItemMeta();
if (meta != null && meta.hasDisplayName() && meta.getDisplayName().equals(ChatColor.GOLD + "Rocket Controller")) {
// Add a rocket slot
this.rocketManager.getStatsManager().addRocketSlot(player);
player.sendMessage(ChatColor.GREEN + "§aВы установили Rocket Controller. У вас теперь " + this.rocketManager.getStatsManager().getRocketSlots(player) + " слот(ов) ракет.");
}
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Material brokenType = event.getBlock().getType();
if (brokenType == Material.BEACON) {
// Check if the broken beacon was a Rocket Controller
// Assuming only Rocket Controllers are beacons in this context
this.rocketManager.getStatsManager().removeRocketSlot(player);
player.sendMessage(ChatColor.RED + "§cВы разрушили Rocket Controller. У вас осталось " + this.rocketManager.getStatsManager().getRocketSlots(player) + " слот(ов) ракет.");
}
}
}
Note: This simplistic approach assumes that any placed beacon with the display name "Rocket Controller" is a special block. For more robust identification (e.g., multiple Rocket Controllers placed by the same player), consider storing the location of each Rocket Controller or using Persistent Data Containers.
e. Enforce Rocket Slot Limits in RocketManager
Ensure that players cannot launch rockets unless they have available slots.
Updated RocketManager Class:
java
Explanation:
Rocket Slots Check:
Before launching a rocket, the plugin checks if the player has at least one available rocket slot.
If not, it notifies the player to place a Rocket Controller block.
Rocket Slot Consumption:
Launching a rocket consumes one rocket slot (optional). If you prefer that rocket slots represent the number of rocket types a player can have, adjust accordingly.
Note: Decide whether rocket slots are permanent or consumed upon launching rockets. The above example assumes slots represent the number of rockets a player can have at any given time, not consumed per launch.
e. Prevent Copying of Rocket Controller Blocks
To ensure that Rocket Controller blocks cannot be copied or duplicated, you can implement the following:
Unique Identification:
Use Persistent Data Containers to tag Rocket Controller blocks uniquely.
This ensures that even if players duplicate beacons with names, the server recognizes them.
Add Unique Identifier to Rocket Controller Blocks:
Update onBlockPlace in RocketListener:
java
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.NamespacedKey;
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
ItemStack placedBlock = event.getItemInHand();
if (placedBlock.getType() == Material.BEACON) {
ItemMeta meta = placedBlock.getItemMeta();
if (meta != null && meta.hasDisplayName() && meta.getDisplayName().equals(ChatColor.GOLD + "Rocket Controller")) {
// Tag the block to prevent duplication
PersistentDataContainer container = event.getBlock().getBlockData().getAsString().contains("beacon") ?
event.getBlock().getState().getPersistentDataContainer() : null;
if (container != null) {
NamespacedKey key = new NamespacedKey(plugin, "rocket_controller");
container.set(key, PersistentDataType.STRING, "true");
event.getBlock().getState().update(true, false);
}
// Add a rocket slot
this.rocketManager.getStatsManager().addRocketSlot(player);
player.sendMessage(ChatColor.GREEN + "§aВы установили Rocket Controller. У вас теперь " + this.rocketManager.getStatsManager().getRocketSlots(player) + " слот(ов) ракет.");
}
}
}
Update onBlockBreak in RocketListener:
java
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Material brokenType = event.getBlock().getType();
if (brokenType == Material.BEACON) {
// Verify if the broken beacon is a Rocket Controller
PersistentDataContainer container = event.getBlock().getState().getPersistentDataContainer();
NamespacedKey key = new NamespacedKey(plugin, "rocket_controller");
if (container.has(key, PersistentDataType.STRING) && container.get(key, PersistentDataType.STRING).equals("true")) {
this.rocketManager.getStatsManager().removeRocketSlot(player);
player.sendMessage(ChatColor.RED + "§cВы разрушили Rocket Controller. У вас осталось " + this.rocketManager.getStatsManager().getRocketSlots(player) + " слот(ов) ракет.");
}
}
}
Explanation:
Persistent Data Container:
Tags the Rocket Controller block with a unique key rocket_controller to identify it.
Prevents players from duplicating the block since only blocks with this tag are considered Rocket Controllers.
Verification on Block Break:
Checks the tag before removing a rocket slot, ensuring only genuine Rocket Controllers affect the slot count.
Note: The above method works for Bukkit versions that support Persistent Data Containers (1.14+). Ensure your server and WorldEdit version are compatible.
Conclusion
By following the steps outlined above, you've:
Streamlined Commands and Removed Unnecessary Features: Focused solely on rocket-related commands (launch, give, stats, reload, getblock) and eliminated PVO, trading, and crafting functionalities.
Integrated WorldEdit for Explosion Handling: Leveraged WorldEdit's API to create more sophisticated and customizable explosion effects, enhancing the realism and impact of rocket launches.
Implemented Rocket Slot Restrictions via Special Blocks: Established a system where players must place a unique Rocket Controller block to gain rocket slots, preventing rocket launches without proper authorization and ensuring players can't duplicate controllers to gain unlimited rockets.
Final Notes:
Testing: Ensure thorough testing of all features in a controlled environment before deploying them to a live server.
WorldEdit Compatibility: Verify that the WorldEdit version matches the server's version to prevent compatibility issues.
Enhancements: Consider adding visual indicators or additional feedback to players when interacting with Rocket Controllers for a better user experience.
Feel free to reach out if you encounter any issues or need further assistance with your plugin development!