Certainly! To optimize, restructure, and improve your plugin for siege weapons, we can implement several best practices, including:
- Refactoring Repetitive Code: Abstract common functionalities into base classes or utilities to avoid duplication.
- Modular Project Structure: Organize the project into clear packages based on functionality.
- Enhanced Command Handling: Utilize a command manager to handle commands more efficiently.
- Dependency Injection: Manage dependencies more cleanly, making the code more maintainable.
- Consistent Naming Conventions: Update all spell-related names to reflect siege weapons.
Below is a step-by-step guide to refactoring your plugin with the improved structure and code.
1. Project Structure
Organize your project into the following packages for better modularity:
com.unistable.siegeweaponplugin
├── commands
├── listeners
├── models
├── spells
├── utils
└── SiegeWeaponPlugin.java
- commands: Contains all command-related classes.
- listeners: Contains all event listener classes.
- models: Contains classes that represent the siege weapons and their statuses.
- spells: Contains classes that handle the behavior of siege weapons (renamed from spells).
- utils: Contains utility classes for common functionalities.
2. Main Plugin Class
Rename SpellPlugin to SiegeWeaponPlugin and update it to reflect the new structure and functionalities.
package com.unistable.siegeweaponplugin;
import com.unistable.siegeweaponplugin.commands.SiegeCommandExecutor;
import com.unistable.siegeweaponplugin.listeners.SiegeInteractionListener;
import com.unistable.siegeweaponplugin.models.SiegeWeapon;
import com.unistable.siegeweaponplugin.spells.Cannon;
import com.unistable.siegeweaponplugin.spells.Mortar;
import com.unistable.siegeweaponplugin.spells.Trebuchet;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.Map;
public class SiegeWeaponPlugin extends JavaPlugin {
private final Map<String, SiegeWeapon> weapons = new HashMap<>();
@Override
public void onEnable() {
// Initialize weapons
initializeWeapons();
// Register listeners
getServer().getPluginManager().registerEvents(new SiegeInteractionListener(this, weapons), this);
// Register commands
SiegeCommandExecutor commandExecutor = new SiegeCommandExecutor(this, weapons);
getCommand("siege").setExecutor(commandExecutor);
}
private void initializeWeapons() {
SiegeWeapon mortar = new Mortar(this);
SiegeWeapon cannon = new Cannon(this);
SiegeWeapon trebuchet = new Trebuchet(this);
weapons.put("mortar", mortar);
weapons.put("cannon", cannon);
weapons.put("trebuchet", trebuchet);
}
}
Key Improvements:
- Centralized Command Handling: All siege-related commands are now handled by a single command executor.
- Weapon Registry: Maintains a map of weapon names to their corresponding
SiegeWeapon instances for easy access.
3. Base Models and Interfaces
Create a base interface SiegeWeapon and an abstract class AbstractSiegeWeapon to encapsulate common functionalities.
SiegeWeapon.java
package com.unistable.siegeweaponplugin.models;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public interface SiegeWeapon {
String getName();
String getItemName();
String getItemDescription();
void load(Player player, ArmorStand armorStand, ItemStack itemInHand);
void shoot(Player player, ArmorStand armorStand);
void align(ArmorStand armorStand, Player player);
}
AbstractSiegeWeapon.java
package com.unistable.siegeweaponplugin.models;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.Map;
public abstract class AbstractSiegeWeapon implements SiegeWeapon {
protected final JavaPlugin plugin;
protected final Map<ArmorStand, WeaponStatus> statusMap = new HashMap<>();
public AbstractSiegeWeapon(JavaPlugin plugin) {
this.plugin = plugin;
}
protected WeaponStatus getStatus(ArmorStand armorStand) {
return statusMap.getOrDefault(armorStand, WeaponStatus.EMPTY);
}
protected void setStatus(ArmorStand armorStand, WeaponStatus status) {
statusMap.put(armorStand, status);
}
protected void adjustItemInHand(Player player, ItemStack itemInHand) {
if (itemInHand.getAmount() > 1) {
itemInHand.setAmount(itemInHand.getAmount() - 1);
} else {
player.getInventory().remove(itemInHand);
}
}
protected void beginCharging(Player player, ArmorStand armorStand, WeaponStatus chargingStatus, WeaponStatus loadedStatus, String chargingMessage, String loadedMessage, long delayTicks) {
setStatus(armorStand, chargingStatus);
player.sendMessage(chargingMessage);
plugin.getServer().getScheduler().runTaskLater(plugin, () -> {
setStatus(armorStand, loadedStatus);
player.sendMessage(loadedMessage);
}, delayTicks);
}
protected enum WeaponStatus {
EMPTY, CHARGING, LOADED
}
}
Key Improvements:
- Unified Interface: All siege weapons implement the
SiegeWeapon interface, ensuring consistent behavior.
- Abstract Class for Common Logic:
AbstractSiegeWeapon encapsulates shared functionalities like status management and item adjustments.
4. Specific Siege Weapons
Implement specific siege weapons by extending AbstractSiegeWeapon.
Cannon.java
package com.unistable.siegeweaponplugin.spells;
import com.unistable.siegeweaponplugin.models.AbstractSiegeWeapon;
import com.unistable.siegeweaponplugin.models.SiegeWeapon;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import net.kyori.adventure.text.Component;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
public class Cannon extends AbstractSiegeWeapon implements SiegeWeapon {
public Cannon(JavaPlugin plugin) {
super(plugin);
}
@Override
public String getName() {
return "Cannon";
}
@Override
public String getItemName() {
return "Пушка";
}
@Override
public String getItemDescription() {
return "Используйте это для размещения пушки.";
}
@Override
public void load(Player player, ArmorStand armorStand, ItemStack itemInHand) {
if (getStatus(armorStand) == WeaponStatus.EMPTY) {
adjustItemInHand(player, itemInHand);
beginCharging(player, armorStand, WeaponStatus.CHARGING, WeaponStatus.LOADED,
Component.text("Пушка заряжается..."),
Component.text("Пушка готова к стрельбе!"),
60L);
} else {
player.sendMessage(Component.text("Пушка уже " + (getStatus(armorStand) == WeaponStatus.CHARGING ? "заряжается" : "заряжена") + "!"));
}
}
@Override
public void shoot(Player player, ArmorStand armorStand) {
if (getStatus(armorStand) == WeaponStatus.LOADED) {
executeShooting(player, armorStand);
setStatus(armorStand, WeaponStatus.EMPTY);
} else {
player.sendMessage(Component.text("Пушка не заряжена!"));
}
}
@Override
public void align(ArmorStand armorStand, Player player) {
armorStand.setRotation(player.getLocation().getYaw(), 0);
}
private void executeShooting(Player player, ArmorStand armorStand) {
Location location = armorStand.getLocation();
Vector direction = player.getLocation().getDirection().normalize();
new DirectCannonSpell(plugin).cast(location, direction);
}
// Implement DirectCannonSpell similarly to your original code
// Ensure it's optimized and placed in the `spells` package
}
Mortar.java
package com.unistable.siegeweaponplugin.spells;
import com.unistable.siegeweaponplugin.models.AbstractSiegeWeapon;
import com.unistable.siegeweaponplugin.models.SiegeWeapon;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import net.kyori.adventure.text.Component;
import org.bukkit.Location;
import org.bukkit.plugin.java.JavaPlugin;
public class Mortar extends AbstractSiegeWeapon implements SiegeWeapon {
public Mortar(JavaPlugin plugin) {
super(plugin);
}
@Override
public String getName() {
return "Mortar";
}
@Override
public String getItemName() {
return "Мортира";
}
@Override
public String getItemDescription() {
return "Используйте это для размещения мортиры.";
}
@Override
public void load(Player player, ArmorStand armorStand, ItemStack itemInHand) {
if (getStatus(armorStand) == WeaponStatus.EMPTY) {
adjustItemInHand(player, itemInHand);
beginCharging(player, armorStand, WeaponStatus.CHARGING, WeaponStatus.LOADED,
Component.text("Мортира заряжается..."),
Component.text("Мортира готова к стрельбе!"),
60L);
} else {
player.sendMessage(Component.text("Мортира уже " + (getStatus(armorStand) == WeaponStatus.CHARGING ? "заряжается" : "заряжена") + "!"));
}
}
@Override
public void shoot(Player player, ArmorStand armorStand) {
if (getStatus(armorStand) == WeaponStatus.LOADED) {
executeShooting(player, armorStand);
setStatus(armorStand, WeaponStatus.EMPTY);
} else {
player.sendMessage(Component.text("Мортира не заряжена!"));
}
}
@Override
public void align(ArmorStand armorStand, Player player) {
armorStand.setRotation(player.getLocation().getYaw(), 0);
}
private void executeShooting(Player player, ArmorStand armorStand) {
Location location = armorStand.getLocation();
Vector direction = player.getLocation().getDirection().normalize();
new MortarBallSpell(plugin).cast(location, direction);
}
// Implement MortarBallSpell similarly to your original code
// Ensure it's optimized and placed in the `spells` package
}
Trebuchet.java
package com.unistable.siegeweaponplugin.spells;
import com.unistable.siegeweaponplugin.models.AbstractSiegeWeapon;
import com.unistable.siegeweaponplugin.models.SiegeWeapon;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import net.kyori.adventure.text.Component;
import org.bukkit.Location;
import org.bukkit.plugin.java.JavaPlugin;
public class Trebuchet extends AbstractSiegeWeapon implements SiegeWeapon {
public Trebuchet(JavaPlugin plugin) {
super(plugin);
}
@Override
public String getName() {
return "Trebuchet";
}
@Override
public String getItemName() {
return "Требушет";
}
@Override
public String getItemDescription() {
return "Используйте это для размещения требушета.";
}
@Override
public void load(Player player, ArmorStand armorStand, ItemStack itemInHand) {
if (getStatus(armorStand) == WeaponStatus.EMPTY) {
adjustItemInHand(player, itemInHand);
beginCharging(player, armorStand, WeaponStatus.CHARGING, WeaponStatus.LOADED,
Component.text("Требушет заряжается..."),
Component.text("Требушет готов к стрельбе!"),
60L);
} else {
player.sendMessage(Component.text("Требушет уже " + (getStatus(armorStand) == WeaponStatus.CHARGING ? "заряжается" : "заряжен") + "!"));
}
}
@Override
public void shoot(Player player, ArmorStand armorStand) {
if (getStatus(armorStand) == WeaponStatus.LOADED) {
executeShooting(player, armorStand);
setStatus(armorStand, WeaponStatus.EMPTY);
} else {
player.sendMessage(Component.text("Требушет не заряжен!"));
}
}
@Override
public void align(ArmorStand armorStand, Player player) {
armorStand.setRotation(player.getLocation().getYaw(), 0);
}
private void executeShooting(Player player, ArmorStand armorStand) {
Location location = armorStand.getLocation();
Vector direction = player.getLocation().getDirection().normalize();
new TrebuchetRockSpell(plugin).cast(location, direction);
}
// Implement TrebuchetRockSpell similarly to your original code
// Ensure it's optimized and placed in the `spells` package
}
Key Improvements:
- Consistent Naming: Changed method names and messages to reflect siege weapons.
- Reusability: Utilized abstract methods to handle common tasks.
5. Event Listeners
Instead of having separate listener classes for each siege weapon, create a unified SiegeInteractionListener that handles interactions for all weapons.
SiegeInteractionListener.java
package com.unistable.siegeweaponplugin.listeners;
import com.unistable.siegeweaponplugin.models.SiegeWeapon;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Map;
public class SiegeInteractionListener implements Listener {
private final JavaPlugin plugin;
private final Map<String, SiegeWeapon> weapons;
private final PlainTextComponentSerializer serializer = PlainTextComponentSerializer.plainText();
public SiegeInteractionListener(JavaPlugin plugin, Map<String, SiegeWeapon> weapons) {
this.plugin = plugin;
this.weapons = weapons;
}
@EventHandler
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
if (!(event.getRightClicked() instanceof ArmorStand clickedEntity)) return;
String entityName = getEntityName(clickedEntity);
SiegeWeapon weapon = weapons.get(entityName.toLowerCase());
if (weapon == null) return;
event.setCancelled(true);
Player player = event.getPlayer();
ItemStack itemInHand = player.getInventory().getItemInMainHand();
// Determine action based on item type and name
if (isLoadingItem(itemInHand, weapon)) {
weapon.load(player, clickedEntity, itemInHand);
} else if (isShootingItem(itemInHand, weapon)) {
weapon.shoot(player, clickedEntity);
} else {
weapon.align(clickedEntity, player);
}
}
private String getEntityName(ArmorStand armorStand) {
if (armorStand.getCustomName() != null) {
return serializer.serialize(armorStand.getCustomName());
}
return "";
}
private boolean isLoadingItem(ItemStack item, SiegeWeapon weapon) {
// Define loading items based on weapon type
switch (weapon.getName().toLowerCase()) {
case "cannon":
return item.getType() == Material.FIREWORK_STAR && "Ядро".equals(serializer.serialize(item.getItemMeta().displayName()));
case "mortar":
return item.getType() == Material.FIREWORK_STAR && "Ядро".equals(serializer.serialize(item.getItemMeta().displayName()));
case "trebuchet":
return item.getType() == Material.COBBLESTONE && "Связка камней".equals(serializer.serialize(item.getItemMeta().displayName()));
default:
return false;
}
}
private boolean isShootingItem(ItemStack item, SiegeWeapon weapon) {
// Define shooting actions based on weapon type
switch (weapon.getName().toLowerCase()) {
case "cannon":
return false; // Example: cannon shooting might not require a specific item
case "mortar":
return false; // Example: mortar shooting might not require a specific item
case "trebuchet":
return false; // Example: trebuchet shooting might not require a specific item
default:
return false;
}
}
}
Key Improvements:
- Unified Listener: Handles all siege weapon interactions, reducing code duplication.
- Dynamic Handling: Determines which weapon to interact with based on the ArmorStand's name.
- Flexible Actions: Determines loading or shooting actions based on the item in hand.
6. Commands Handling
Implement a unified command executor to handle all siege-related commands.
SiegeCommandExecutor.java
package com.unistable.siegeweaponplugin.commands;
import com.unistable.siegeweaponplugin.models.SiegeWeapon;
import com.unistable.siegeweaponplugin.utils.ItemUtils;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Map;
public class SiegeCommandExecutor implements CommandExecutor {
private final JavaPlugin plugin;
private final Map<String, SiegeWeapon> weapons;
public SiegeCommandExecutor(JavaPlugin plugin, Map<String, SiegeWeapon> weapons) {
this.plugin = plugin;
this.weapons = weapons;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player player)) {
sender.sendMessage(Component.text("This command can only be run by a player."));
return true;
}
if (args.length == 0) {
player.sendMessage(Component.text("Usage: /siege <give_cannon|give_mortar|give_trebuchet>"));
return true;
}
switch (args[0].toLowerCase()) {
case "give_cannon":
giveItem(player, createSiegeItem("cannon"));
break;
case "give_mortar":
giveItem(player, createSiegeItem("mortar"));
break;
case "give_trebuchet":
giveItem(player, createSiegeItem("trebuchet"));
break;
default:
SiegeWeapon weapon = weapons.get(args[0].toLowerCase());
if (weapon != null) {
// Implement weapon-specific commands if any
} else {
player.sendMessage(Component.text("Unknown command."));
return false;
}
}
return true;
}
private void giveItem(Player player, ItemStack item) {
player.getInventory().addItem(item);
}
private ItemStack createSiegeItem(String weaponKey) {
SiegeWeapon weapon = weapons.get(weaponKey.toLowerCase());
if (weapon == null) {
throw new IllegalArgumentException("Invalid siege weapon key: " + weaponKey);
}
return ItemUtils.createItem(
Material.ARMOR_STAND,
weapon.getItemName(),
weapon.getItemDescription()
);
}
}
plugin.yml
Ensure your plugin.yml registers the new /siege command.
name: SiegeWeaponPlugin
main: com.unistable.siegeweaponplugin.SiegeWeaponPlugin
version: 1.0
commands:
siege:
description: Siege weapon commands
usage: /siege <give_cannon|give_mortar|give_trebuchet>
Key Improvements:
- Single Command Handler: All siege-related commands are managed centrally.
- Dynamic Item Creation: Uses
ItemUtils to create items based on the weapon's metadata.
7. Utility Classes
Create utility classes to handle repetitive tasks like item creation.
ItemUtils.java
package com.unistable.siegeweaponplugin.utils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.Collections;
public class ItemUtils {
public static ItemStack createItem(Material material, String name, String description) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.displayName(Component.text(name, NamedTextColor.GREEN).decoration(net.kyori.adventure.text.format.TextDecoration.ITALIC, false));
meta.lore(Collections.singletonList(Component.text(description, NamedTextColor.GRAY).decoration(net.kyori.adventure.text.format.TextDecoration.ITALIC, false)));
item.setItemMeta(meta);
}
return item;
}
}
Key Improvements:
- DRY Principle: Centralizes item creation logic to avoid repetition.
- Consistent Formatting: Ensures all items are created with a uniform look and feel.
8. Spells Classes Refactoring
Ensure all spell classes are optimized and extend from any necessary base classes or interfaces. Here's an example of refactoring DirectCannonSpell.
DirectCannonSpell.java
package com.unistable.siegeweaponplugin.spells;
import com.unistable.siegeweaponplugin.models.SiegeWeapon;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
public class DirectCannonSpell implements SiegeSpell {
private final JavaPlugin plugin;
private static final int SPEED = 2; // Increased speed to reduce task duration
private static final int RANGE = 30;
private static final int PARTICLE_COUNT = 10; // Reduced particle count for optimization
public DirectCannonSpell(JavaPlugin plugin) {
this.plugin = plugin;
}
@Override
public void cast(Location startLocation, Vector direction) {
World world = startLocation.getWorld();
if (world == null) return;
world.playSound(startLocation, Sound.ENTITY_GENERIC_EXPLODE, 1.0F, 0.5F);
new BukkitRunnable() {
private int distance = 0;
@Override
public void run() {
if (distance > RANGE) {
this.cancel();
return;
}
Location currentLocation = startLocation.clone().add(direction.clone().multiply(distance));
Material blockType = currentLocation.getBlock().getType();
if (blockType != Material.AIR) {
createCannonballEffect(world, currentLocation, true);
this.cancel();
return;
}
createCannonballEffect(world, currentLocation, false);
distance++;
}
private void createCannonballEffect(World world, Location location, boolean explode) {
world.spawnParticle(Particle.SMOKE_LARGE, location, PARTICLE_COUNT, 0.3, 0.3, 0.3, 0.05);
if (explode) {
world.createExplosion(location, 4.0F, true, true);
}
}
}.runTaskTimer(plugin, 0L, SPEED);
}
}
SiegeSpell.java
Create an interface for siege spells similar to your original Spell interface.
package com.unistable.siegeweaponplugin.spells;
import org.bukkit.Location;
import org.bukkit.util.Vector;
public interface SiegeSpell {
void cast(Location startLocation, Vector direction);
}
Key Improvements:
- Consistent Interfaces: All spells implement the
SiegeSpell interface, ensuring uniformity.
- Optimized Behavior: Simplified the spell casting logic for better performance.
9. Event Naming and Weapon Identification
Ensure that when creating or referencing ArmorStands for siege weapons, their names match the keys used in the weapons map. Utilize utility methods to handle naming consistently.
ArmorStandUtils.java
package com.unistable.siegeweaponplugin.utils;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.ArmorStand;
public class ArmorStandUtils {
public static void setArmorStandName(ArmorStand armorStand, String name) {
armorStand.setCustomName(Component.text(name));
armorStand.setCustomNameVisible(true);
}
public static String getArmorStandName(ArmorStand armorStand) {
return armorStand.getCustomName() != null ? armorStand.getCustomName().content() : "";
}
}
Usage Example:
When spawning an ArmorStand for a siege weapon, set its name accordingly.
ArmorStand armorStand = world.spawn(location, ArmorStand.class);
ArmorStandUtils.setArmorStandName(armorStand, weapon.getName());
10. Final Touches and Best Practices
- Null Checks: Ensure to perform null checks where necessary to prevent potential
NullPointerExceptions.
- Thread Safety: Since Bukkit's API is not thread-safe, ensure all interactions with the API occur on the main thread.
- Logging: Utilize plugin logging for debugging and error reporting.
- Configuration Files: Consider externalizing configurable parameters (like ranges, speeds, cooldowns) to a
config.yml for flexibility.
- Documentation: Comment your code where necessary to explain complex logic.
Complete Refactored Code Examples
Below are complete examples of some refactored classes based on the above structure. Due to space constraints, not all classes are fully expanded, but this should provide a clear direction for the rest.
SiegeWeaponPlugin.java
As provided earlier.
SiegeCommandExecutor.java
As provided earlier.
SiegeInteractionListener.java
As provided earlier.
AbstractSiegeWeapon.java
As provided earlier.
Cannon.java, Mortar.java, Trebuchet.java
As provided earlier, ensure each spell class like DirectCannonSpell, MortarBallSpell, TrebuchetRockSpell, etc., are refactored similarly, implementing SiegeSpell and optimizing their logic.
SiegeSpell.java
As provided earlier.
ItemUtils.java
As provided earlier.
ArmorStandUtils.java
As provided earlier.
Example Spell Class: TrebuchetRockSpell
Here's an optimized version of the TrebuchetRockSpell implementing SiegeSpell.
TrebuchetRockSpell.java
package com.unistable.siegeweaponplugin.spells;
import org.bukkit.*;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
public class TrebuchetRockSpell implements SiegeSpell {
private final JavaPlugin plugin;
private static final int SPEED = 1;
private static final int RANGE = 60;
private static final int DAMAGE = 10;
private static final int PARTICLE_COUNT = 100;
private static final int BLINDNESS_DURATION = 10 * 20;
private static final double DAMAGE_RADIUS = 10.0;
private static final Material ROCK_MATERIAL = Material.STONE;
public TrebuchetRockSpell(JavaPlugin plugin) {
this.plugin = plugin;
}
@Override
public void cast(Location startLocation, Vector direction) {
World world = startLocation.getWorld();
if (world == null) return;
playInitialSounds(world, startLocation);
new BukkitRunnable() {
private int distance = 0;
private boolean falling = false;
private Location fallLocation = null;
@Override
public void run() {
if (!falling) {
Location currentLocation = calculateLocation(startLocation, direction, distance);
if (checkCollision(world, currentLocation)) {
createRockEffect(world, currentLocation, true);
this.cancel();
return;
}
if (distance >= RANGE) {
falling = true;
fallLocation = currentLocation;
return;
}
createRockEffect(world, currentLocation, false);
distance++;
} else {
if (fallLocation == null) return;
fallLocation = fallLocation.clone().add(0, -1, 0);
if (fallLocation.getBlock().getType() != Material.AIR) {
createRockEffect(world, fallLocation, true);
this.cancel();
return;
}
createRockEffect(world, fallLocation, false);
}
}
private Location calculateLocation(Location start, Vector direction, int distance) {
double yOffset = 30 * Math.sin(Math.PI * distance / RANGE);
return start.clone().add(direction.clone().multiply(distance)).add(0, yOffset, 0);
}
private boolean checkCollision(World world, Location location) {
return location.getBlock().getType() != Material.AIR;
}
private void createRockEffect(World world, Location location, boolean explode) {
world.spawnParticle(Particle.BLOCK_CRACK, location, PARTICLE_COUNT, 0.3, 0.3, 0.3, 0.05, ROCK_MATERIAL.createBlockData());
if (explode) {
applyDamageAndEffects(world, location);
}
}
private void applyDamageAndEffects(World world, Location location) {
for (Entity entity : world.getNearbyEntities(location, DAMAGE_RADIUS, DAMAGE_RADIUS, DAMAGE_RADIUS)) {
if (entity instanceof LivingEntity livingEntity) {
livingEntity.damage(DAMAGE);
livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, BLINDNESS_DURATION, 1));
}
}
spawnImpactParticles(world, location);
}
private void spawnImpactParticles(World world, Location location) {
world.spawnParticle(Particle.CLOUD, location, PARTICLE_COUNT);
world.spawnParticle(Particle.BLOCK_CRACK, location, PARTICLE_COUNT, 0.3, 0.3, 0.3, 0.05, ROCK_MATERIAL.createBlockData());
}
private void playInitialSounds(World world, Location location) {
world.playSound(location, Sound.ENTITY_ARROW_SHOOT, 1.0F, 0.5F);
world.playSound(location, Sound.BLOCK_PISTON_EXTEND, 1.0F, 0.5F);
}
}.runTaskTimer(plugin, 0L, SPEED);
}
}
Key Improvements:
- Optimized Collision Detection: Simplified collision logic for better performance.
- Enhanced Particle Effects: Managed particle spawning more efficiently.
- Consistent Sound Playback: Centralized sound playing for better manageability.
11. Final Recommendations
- Error Handling: Implement comprehensive error handling to manage unexpected scenarios gracefully.
- Configuration: Utilize
config.yml to allow server admins to customize settings like ranges, speeds, and cooldowns without modifying the code.
- Testing: Thoroughly test each siege weapon to ensure all functionalities work as expected.
- Documentation: Provide clear documentation for server admins on how to use and configure the plugin.
By following this refactored structure and implementing the optimizations, your siege weapon plugin will be more maintainable, efficient, and easier to expand in the future.