java “插件已在主程序中注册,但无法运行,”

3qpi33ja  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(163)

“我有一个问题,我的插件有两个文件,FireballPlugin.java(主程序)和BlockReset.java(子程序),但是当我在主程序中写入Bukkit.getPluginManager().registerEvents(new BlockReset(), this);注册BlockReset.java时,Intellij没有显示任何错误,但是在游戏中不能工作,但是如果我将Fireball.java和BlockReset.java合并在一起,它就可以工作,这会是什么问题呢?”
下面是我的代码:
[main程序]:

package com.badlyac.NewFireballPlugin;

import com.badlyac.NewFireballPlugin.BlockExplode.BlockReset;
import com.badlyac.NewFireballPlugin.PlayerResistance.AntiFire;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;

public class FireballPlugin extends JavaPlugin implements Listener {

    private double horizontalKnockback;
    private double verticalKnockback;
    private double Speed;
    private int Power;
    private boolean Incendiary;
    private boolean comboMode;
    @SuppressWarnings("FieldCanBeLocal")
    private boolean destroyBlocks;
    private boolean fallDamage;
    @Override
    public void onEnable() {
        Bukkit.getPluginManager().registerEvents(this, this);
        Bukkit.getPluginManager().registerEvents(new GiveItemWhenJoin(), this);
        Bukkit.getPluginManager().registerEvents(new AntiFire(),this);
        Bukkit.getPluginManager().registerEvents(new BlockReset(),this);
        loadConfig();
        getLogger().info(ChatColor.GREEN + "FireballPlugin has been enabled!");
    }

    @Override
    public void onDisable() {
        getLogger().info(ChatColor.RED + "FireballPlugin has been disabled!");
    }

    @EventHandler
    public void Fireball(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("fireball.admin")) {
            if (player.getItemInHand().getType() == Material.FIREBALL) {
                if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                    Location loc = player.getLocation();
                    Vector dir = loc.getDirection().normalize();
                    Fireball fireball = player.getWorld().spawn(loc.add(0, 1.6, 0), Fireball.class);
                    fireball.setVelocity(dir.multiply(0.5 + Speed));
                    fireball.setShooter(player);
                    fireball.setIsIncendiary(Incendiary);
                    fireball.setYield(1 + Power);
                }
            }
        }

        Material material = player.getInventory().getItemInHand().getType();
        if (material == Material.FIREBALL && player.hasPermission("fireball.admin")) {
            event.setCancelled(true);
        }
    }
    @EventHandler
    public void SmallFireball(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("fireball.admin")) {
            if (player.getItemInHand().getType() == Material.BLAZE_POWDER) {
                if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                    Location loc = player.getLocation();
                    Vector dir = loc.getDirection();
                    SmallFireball smallFireball = player.getWorld().spawn(loc.add(0, 1.6, 0), SmallFireball.class);
                    smallFireball.setVelocity(dir.multiply(0.5 + Speed));
                    smallFireball.setShooter(player);
                    smallFireball.setYield(Power);
                    smallFireball.setIsIncendiary(Incendiary);
                }
            }
        }

        Material material = player.getInventory().getItemInHand().getType();
        if (material == Material.BLAZE_POWDER && player.hasPermission("fireball.admin")) {
            event.setCancelled(true);
        }
    }
    @EventHandler
    public void WitherSKull(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("fireball.admin")) {
            if (player.getItemInHand().getType() == Material.SKULL_ITEM) {
                if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                    Location loc = player.getLocation();
                    Vector dir = loc.getDirection();
                    WitherSkull witherSkull = player.getWorld().spawn(loc.add(0, 1.6, 0), WitherSkull.class);
                    witherSkull.setVelocity(dir.multiply(0.5 + Speed));
                    witherSkull.setShooter(player);
                    witherSkull.setYield(Power);
                    witherSkull.setIsIncendiary(Incendiary);
                }
            }
        }

        Material material = player.getInventory().getItemInHand().getType();
        if (material == Material.SKULL_ITEM && player.getItemInHand().getDurability() == 1&& player.hasPermission("fireball.admin")) {
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void onTntLaunch(PlayerInteractEvent event) {
        Player player = event.getPlayer();
            if (player.hasPermission("fireball.admin")) {
                 Material heldMaterial = getHeldMaterial(player);
                if (heldMaterial == Material.TNT) {
                    if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                        TNT(player);
                        event.setCancelled(true);
                    }
                }
            }
            Material material = player.getInventory().getItemInHand().getType();
            if (material == Material.TNT && player.hasPermission("fireball.admin")){
                event.setCancelled(true);
            }
    }
    private Material getHeldMaterial(Player player) {
        ItemStack heldItem = player.getItemInHand();
        return heldItem.getType();
    }

    private void TNT(Player player) {
        TNTPrimed tnt = player.getWorld().spawn(player.getLocation(), TNTPrimed.class);
        tnt.setFuseTicks(50);
        double tntSpeed = 1.3;
        tnt.setVelocity(player.getLocation().getDirection().multiply(tntSpeed));
        tnt.setYield(1 + Power);
        tnt.setIsIncendiary(Incendiary);
    }
    @EventHandler
    public void onExplosion(EntityExplodeEvent event) {
        if (event.getEntity() instanceof TNTPrimed) {
            handleTNTExplosion(event);
        } else if (event.getEntity() instanceof Fireball) {
            handleFireballExplosion(event);
        } else if(event.getEntity() instanceof WitherSkull){
            handleWitherSkullExplosion(event);
        }
    }

    private void handleTNTExplosion(EntityExplodeEvent event) {
        if (!destroyBlocks) {
            event.blockList().clear();
        }
    }

    private void handleFireballExplosion(EntityExplodeEvent event) {
        if (!destroyBlocks) {
            event.blockList().clear();
        }
    }
    private void handleWitherSkullExplosion(EntityExplodeEvent event) {
        if (!destroyBlocks) {
            event.blockList().clear();
        }
    }

    @EventHandler
    public void onEntityDamage(EntityDamageEvent event) {
        if (event.getEntity() instanceof Player && event.getCause() == EntityDamageEvent.DamageCause.FALL) {
            if (!fallDamage) {
                event.setCancelled(true);
            }
        }
    }

    public void loadConfig() {

        saveDefaultConfig();

        FileConfiguration config = getConfig();

        horizontalKnockback = config.getDouble("fireball.knockback.horizontalKnockback",5.0);
        verticalKnockback = config.getDouble("fireball.knockback.verticalKnockback",-2.5);
        Speed =config.getDouble("fireball.Speed",1.5);
        Power = config.getInt("fireball.Power",3);
        Incendiary = config.getBoolean("fireball.Incendiary",false);
        comboMode = config.getBoolean("Combo",false);
        destroyBlocks = config.getBoolean("fireball.destroyBlocks" , false);
        fallDamage = config.getBoolean("fallDamage", false);
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (label.equalsIgnoreCase("fireball")) {
            if (args.length == 8) {
                try {
                    double f1 = Double.parseDouble(args[0]);
                    double f2 = Double.parseDouble(args[1]);
                    double f3 = Double.parseDouble(args[2]);
                    int f4 = Integer.parseInt(args[3]);
                    boolean f5 = Boolean.parseBoolean(args[4]);
                    boolean f6 = Boolean.parseBoolean(args[5]);
                    boolean f7 = Boolean.parseBoolean(args[6]);
                    boolean f8 = Boolean.parseBoolean(args[7]);

                    horizontalKnockback = f1;
                    verticalKnockback = f2;
                    Speed = f3;
                    Power = f4;
                    Incendiary = f5;
                    comboMode = f6;
                    destroyBlocks = f7;
                    fallDamage = f8;

                    setMaxNoDamageTicks(comboMode);

                    FileConfiguration config = getConfig();
                    config.set("fireball.knockback.horizontalKnockback", horizontalKnockback);
                    config.set("fireball.knockback.verticalKnockback", verticalKnockback);
                    config.set("fireball.Speed", Speed);
                    config.set("fireball.Power", Power);
                    config.set("fireball.Incendiary", Incendiary);
                    config.set("Combo", comboMode);
                    config.set("fireball.destroyBlocks", destroyBlocks);
                    config.set("fireball.fallDamage", fallDamage);

                    saveConfig();

                    sender.sendMessage(
                            ChatColor.GREEN + "Fireball settings updated: " + " set vertical:" + verticalKnockback + " set horizontal:" + horizontalKnockback + " set Speed:" + Speed + " set Power:" + Power + " set Incendiary:" + Incendiary + " set ComboMode:" + comboMode + " set DestroyBlocks:" + destroyBlocks + " set FallDamage:" + fallDamage
                    );
                } catch (NumberFormatException e) {
                    sender.sendMessage(ChatColor.RED + "Invalid value! Please enter the correct number!");
                }
            } else {
                Player player = (Player) sender;
                player.sendMessage(ChatColor.RED + "Command usage: /fireball <horizontalKnockback> <verticalKnockback> <Speed> <Power> <Incendiary (true or false)> <ComboMode (true or false)> <DestroyBlocks (true or false)> <FallDamage (true or false)>");
            }
            return true;
        }
        return false;
    }
    private void setMaxNoDamageTicks(boolean comboMode) {
        int ticks = comboMode ? 2 : 11;
        for (World world : Bukkit.getWorlds()) {
            for (LivingEntity entity : world.getLivingEntities()) {
                entity.setMaximumNoDamageTicks(ticks);
            }
        }
    }

    @EventHandler
    public void onEntityDamagebyEntity(EntityDamageByEntityEvent event) {
        if (event.getDamager() instanceof Fireball && event.getEntity() instanceof LivingEntity) {
            Fireball fireball = (Fireball) event.getDamager();
            LivingEntity livingEntity = (Player) event.getEntity();
            livingEntity.damage(0, fireball);
            Vector fireballVelocity = fireball.getVelocity().normalize();
            Vector knockbackVector = new Vector(
                    fireballVelocity.getX() * horizontalKnockback,
                    fireballVelocity.getY() * (verticalKnockback * -1),
                    fireballVelocity.getZ() * horizontalKnockback
            );
            livingEntity.setVelocity(knockbackVector);

            if (livingEntity.getLocation().distanceSquared(fireball.getLocation()) <= fireball.getYield() * fireball.getYield()) {
                livingEntity.setVelocity(knockbackVector);
            }

            event.setDamage(0.0);
        } else if (event.getDamager() instanceof TNTPrimed && event.getEntity() instanceof LivingEntity) {
            if (event.getDamager() instanceof Fireball && event.getEntity() instanceof LivingEntity) {
                TNTPrimed tntPrimed = (TNTPrimed) event.getDamager();
                LivingEntity livingEntity = (Player) event.getEntity();
                livingEntity.damage(0, tntPrimed);
                Vector fireballVelocity = tntPrimed.getVelocity().normalize();
                Vector knockbackVector = new Vector(
                        fireballVelocity.getX() * horizontalKnockback,
                        fireballVelocity.getY() * (verticalKnockback* -1),
                        fireballVelocity.getZ() * horizontalKnockback
                );
                livingEntity.setVelocity(knockbackVector);
                if (livingEntity.getLocation().distanceSquared(tntPrimed.getLocation()) <= tntPrimed.getYield() * tntPrimed.getYield()) {
                    livingEntity.setVelocity(knockbackVector);
                }
            }
            event.setDamage(0.0);
        }
    }
    @EventHandler
    public void onProjectileHit(ProjectileHitEvent event) {
        if (event.getEntityType() == EntityType.FIREBALL) {
            Fireball fireball = (Fireball) event.getEntity();
            if (fireball.getShooter() instanceof Player) {
                Player shooter = (Player) fireball.getShooter();

                Location explosionLocation = fireball.getLocation();
                if (shooter.getLocation().distance(explosionLocation) <= 1.5) {
                    Vector selfKnockback = shooter.getLocation().getDirection().multiply(Speed * horizontalKnockback);
                    selfKnockback.setY(verticalKnockback);
                    shooter.setVelocity(selfKnockback);
                }

                for (Entity entity : explosionLocation.getWorld().getNearbyEntities(explosionLocation, 1.5, 1.5, 1.5)) {
                    if (entity instanceof Player) {
                        Player target = (Player) entity;
                        if (!target.getUniqueId().equals(shooter.getUniqueId())) {
                            Vector knockback = target.getLocation().toVector().subtract(explosionLocation.toVector()).normalize().multiply(Speed * horizontalKnockback);
                            knockback.setY(verticalKnockback);
                            target.setVelocity(knockback);
                        }
                    }
                }
            }
        }
        if (event.getEntityType() == EntityType.WITHER_SKULL) {
            WitherSkull witherSkull = (WitherSkull) event.getEntity();
            if (witherSkull.getShooter() instanceof Player) {
                Player shooter = (Player) witherSkull.getShooter();

                Location explosionLocation = witherSkull.getLocation();
                if (shooter.getLocation().distance(explosionLocation) <= 1.5) {
                    Vector selfKnockback = shooter.getLocation().getDirection().multiply(1 * horizontalKnockback);
                    selfKnockback.setY(verticalKnockback);
                    shooter.setVelocity(selfKnockback);
                }

                for (Entity entity : explosionLocation.getWorld().getNearbyEntities(explosionLocation, 1.5, 1.5, 1.5)) {
                    if (entity instanceof Player) {
                        Player target = (Player) entity;
                        if (!target.getUniqueId().equals(shooter.getUniqueId())) {
                            Vector knockback = target.getLocation().toVector().subtract(explosionLocation.toVector()).normalize().multiply(1 * horizontalKnockback);
                            knockback.setY(verticalKnockback);
                            target.setVelocity(knockback);
                        }
                    }
                }
            }
        }
    }
}

字符串
[sub程序]:

package com.badlyac.NewFireballPlugin.BlockExplode;

import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.Material;

import java.util.HashMap;
import java.util.Map;

public class BlockReset extends JavaPlugin implements Listener {

    final Map<EntityExplodeEvent, Map<Block, BlockData>> explosionsData = new HashMap<>();

    @EventHandler
    public void onEntityExplode(EntityExplodeEvent event) {
        if (event.getEntity() instanceof TNTPrimed || event.getEntity() instanceof org.bukkit.entity.WitherSkull || event.getEntity() instanceof Fireball) {
            saveBlockData(event);
            restoreBlocksLater(event);
        }
    }
    @SuppressWarnings("deprecation")
    private void saveBlockData(EntityExplodeEvent event) {
        Map<Block, BlockData> blockDataBackup = new HashMap<>();
        for (Block block : event.blockList()) {
            BlockState blockState = block.getState();
            BlockData blockData = new BlockData(blockState.getType(), blockState.getData().getData());
            blockDataBackup.put(block, blockData);
        }
        this.explosionsData.put(event, blockDataBackup);
    }

    private void restoreBlocksLater(final EntityExplodeEvent event) {
        (new BukkitRunnable() {
            public void run() {
                BlockReset.this.restoreBlocks(event);
            }
        }).runTaskLater(this, 60L);
    }
    @SuppressWarnings("deprecation")
    private void restoreBlocks(EntityExplodeEvent event) {
        if (this.explosionsData.containsKey(event)) {
            Map<Block, BlockData> blockDataBackup = this.explosionsData.get(event);
            for (Block block : event.blockList()) {
                if (blockDataBackup.containsKey(block)) {
                    BlockData blockData = blockDataBackup.get(block);
                    block.setType(blockData.getType());
                    block.setData(blockData.getData());
                    block.getState().update(true, false);
                }
            }
            this.explosionsData.remove(event);
        }
    }

    private static class BlockData {
        private final Material type;

        private final byte data;

        public BlockData(Material type, byte data) {
            this.type = type;
            this.data = data;
        }

        public Material getType() {
            return this.type;
        }

        public byte getData() {
            return this.data;
        }
    }
}


我试着把它们写在一起,它工作。但它会使程序看起来非常复杂。

km0tfn4u

km0tfn4u1#

**我看到了多个问题,或者至少有几个是我不会这样处理的。

1.通用协议

通常要注册侦听器,

getServer().getPluginManager().registerEvents(new Listener(), this);

字符串
最有可能的是,按照你的方式去做并没有什么坏处。这只是惯例。最好还是坚持惯例。

2.插件示例问题--我确定是这个问题造成的

main类中从JavaPlugin扩展类。不要在其他任何地方扩展它。这意味着在BlockReset类中删除extends JavaPlugin。如果你这样做,你基本上是在一个插件中制作两个插件。我认为这不会起作用。:)

我明白为什么你现在让BlockReset类扩展JavaPlugin了。你需要你的插件的示例。要正确地做到这一点,请将以下内容添加到你的主类:

// So you can get the plugin
public static FireballPlugin getPlugin() {
        return plugin;
    }

// This creates the plugin object
public static FireballPlugin plugin;


另外,在主类的onEnable中添加以下内容:

// This assigns the plugin object to the class
plugin = this;


这应该是您的onEnable中的第一件事。

FireballPlugin.getplugin()


而不是尝试使用JavaPluginthis每当你需要一个插件示例在你的BlockReset类现在。
在此处替换BlockReset类中的this

private void restoreBlocksLater(final EntityExplodeEvent event) {
        (new BukkitRunnable() {
            public void run() {
                // Also fix these type of things
                BlockReset.this.restoreBlocks(event);
            }
        // Right here    |
        //               V
        }).runTaskLater(this, 60L);
    }


该方法的改进版本是

private void restoreBlocksLater(final EntityExplodeEvent event) {
        (new BukkitRunnable() {
            public void run() {
                // This method is within the same class
                restoreBlocks(event);
            }
        // This is the way to do it!
        }).runTaskLater(FireballPlugin.getPlugin(), 60L);
    }


去掉所有其他的this。你不需要这样做,因为Java知道你在谈论那个类中的变量或方法。如果你在谈论另一个类中的变量,你会把OtherClass.variable放进去。this.whatever存在的唯一原因是构造函数。

3.通用协议

通常plugin文件夹是小写的。这不是什么大问题,但这也是惯例。如果你使用构建系统,你应该这样做,你必须用小写的大写。我不认为你可以在工件名称中使用大写的。如果你使用的是名为IntelliJ的IDE和Minecraft Development插件,它都是自动生成的。
布局通常应该是com.example.yourplugin.YourPlugin,所以像这样:com.badlyac.newfireballplugin.FireballPlugin
但是,你有这样的:com.badlyac.NewFireballPlugin.FireballPlugin

固定类

这里是你通过修复前两个问题而修复的类。你可以决定是否修复第三个问题。
主要类别:

package com.badlyac.NewFireballPlugin;

import com.badlyac.NewFireballPlugin.BlockExplode.BlockReset;
import com.badlyac.NewFireballPlugin.PlayerResistance.AntiFire;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;

// Only place JavaPlugin should be used
public class FireballPlugin extends JavaPlugin implements Listener {

    // So you can get the plugin
    public static FireballPlugin getPlugin() {
        return plugin;
    }

    // This creates the plugin object
    public static FireballPlugin plugin;

    private double horizontalKnockback;
    private double verticalKnockback;
    private double Speed;
    private int Power;
    private boolean Incendiary;
    private boolean comboMode;
    @SuppressWarnings("FieldCanBeLocal")
    private boolean destroyBlocks;
    private boolean fallDamage;

    @Override
    public void onEnable() {
        // This assigns the plugin object to this class
        plugin = this;
        getServer().getPluginManager().registerEvents(this, this);
        getServer().getPluginManager().registerEvents(new GiveItemWhenJoin(), this);
        getServer().getPluginManager().registerEvents(new AntiFire(),this);
        getServer().getPluginManager().registerEvents(new BlockReset(),this);
        loadConfig();
        getLogger().info(ChatColor.GREEN + "FireballPlugin has been enabled!");
    }

    @Override
    public void onDisable() {
        getLogger().info(ChatColor.RED + "FireballPlugin has been disabled!");
    }

    @EventHandler
    public void Fireball(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("fireball.admin")) {
            if (player.getItemInHand().getType() == Material.FIREBALL) {
                if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                    Location loc = player.getLocation();
                    Vector dir = loc.getDirection().normalize();
                    Fireball fireball = player.getWorld().spawn(loc.add(0, 1.6, 0), Fireball.class);
                    fireball.setVelocity(dir.multiply(0.5 + Speed));
                    fireball.setShooter(player);
                    fireball.setIsIncendiary(Incendiary);
                    fireball.setYield(1 + Power);
                }
            }
        }

        Material material = player.getInventory().getItemInHand().getType();
        if (material == Material.FIREBALL && player.hasPermission("fireball.admin")) {
            event.setCancelled(true);
        }
    }
    @EventHandler
    public void SmallFireball(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("fireball.admin")) {
            if (player.getItemInHand().getType() == Material.BLAZE_POWDER) {
                if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                    Location loc = player.getLocation();
                    Vector dir = loc.getDirection();
                    SmallFireball smallFireball = player.getWorld().spawn(loc.add(0, 1.6, 0), SmallFireball.class);
                    smallFireball.setVelocity(dir.multiply(0.5 + Speed));
                    smallFireball.setShooter(player);
                    smallFireball.setYield(Power);
                    smallFireball.setIsIncendiary(Incendiary);
                }
            }
        }

        Material material = player.getInventory().getItemInHand().getType();
        if (material == Material.BLAZE_POWDER && player.hasPermission("fireball.admin")) {
            event.setCancelled(true);
        }
    }
    @EventHandler
    public void WitherSKull(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("fireball.admin")) {
            if (player.getItemInHand().getType() == Material.SKULL_ITEM) {
                if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                    Location loc = player.getLocation();
                    Vector dir = loc.getDirection();
                    WitherSkull witherSkull = player.getWorld().spawn(loc.add(0, 1.6, 0), WitherSkull.class);
                    witherSkull.setVelocity(dir.multiply(0.5 + Speed));
                    witherSkull.setShooter(player);
                    witherSkull.setYield(Power);
                    witherSkull.setIsIncendiary(Incendiary);
                }
            }
        }

        Material material = player.getInventory().getItemInHand().getType();
        if (material == Material.SKULL_ITEM && player.getItemInHand().getDurability() == 1&& player.hasPermission("fireball.admin")) {
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void onTntLaunch(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("fireball.admin")) {
            Material heldMaterial = getHeldMaterial(player);
            if (heldMaterial == Material.TNT) {
                if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                    TNT(player);
                    event.setCancelled(true);
                }
            }
        }
        Material material = player.getInventory().getItemInHand().getType();
        if (material == Material.TNT && player.hasPermission("fireball.admin")){
            event.setCancelled(true);
        }
    }
    private Material getHeldMaterial(Player player) {
        ItemStack heldItem = player.getItemInHand();
        return heldItem.getType();
    }

    private void TNT(Player player) {
        TNTPrimed tnt = player.getWorld().spawn(player.getLocation(), TNTPrimed.class);
        tnt.setFuseTicks(50);
        double tntSpeed = 1.3;
        tnt.setVelocity(player.getLocation().getDirection().multiply(tntSpeed));
        tnt.setYield(1 + Power);
        tnt.setIsIncendiary(Incendiary);
    }
    @EventHandler
    public void onExplosion(EntityExplodeEvent event) {
        if (event.getEntity() instanceof TNTPrimed) {
            handleTNTExplosion(event);
        } else if (event.getEntity() instanceof Fireball) {
            handleFireballExplosion(event);
        } else if(event.getEntity() instanceof WitherSkull){
            handleWitherSkullExplosion(event);
        }
    }

    private void handleTNTExplosion(EntityExplodeEvent event) {
        if (!destroyBlocks) {
            event.blockList().clear();
        }
    }

    private void handleFireballExplosion(EntityExplodeEvent event) {
        if (!destroyBlocks) {
            event.blockList().clear();
        }
    }
    private void handleWitherSkullExplosion(EntityExplodeEvent event) {
        if (!destroyBlocks) {
            event.blockList().clear();
        }
    }

    @EventHandler
    public void onEntityDamage(EntityDamageEvent event) {
        if (event.getEntity() instanceof Player && event.getCause() == EntityDamageEvent.DamageCause.FALL) {
            if (!fallDamage) {
                event.setCancelled(true);
            }
        }
    }

    public void loadConfig() {

        saveDefaultConfig();

        FileConfiguration config = getConfig();

        horizontalKnockback = config.getDouble("fireball.knockback.horizontalKnockback",5.0);
        verticalKnockback = config.getDouble("fireball.knockback.verticalKnockback",-2.5);
        Speed =config.getDouble("fireball.Speed",1.5);
        Power = config.getInt("fireball.Power",3);
        Incendiary = config.getBoolean("fireball.Incendiary",false);
        comboMode = config.getBoolean("Combo",false);
        destroyBlocks = config.getBoolean("fireball.destroyBlocks" , false);
        fallDamage = config.getBoolean("fallDamage", false);
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (label.equalsIgnoreCase("fireball")) {
            if (args.length == 8) {
                try {
                    double f1 = Double.parseDouble(args[0]);
                    double f2 = Double.parseDouble(args[1]);
                    double f3 = Double.parseDouble(args[2]);
                    int f4 = Integer.parseInt(args[3]);
                    boolean f5 = Boolean.parseBoolean(args[4]);
                    boolean f6 = Boolean.parseBoolean(args[5]);
                    boolean f7 = Boolean.parseBoolean(args[6]);
                    boolean f8 = Boolean.parseBoolean(args[7]);

                    horizontalKnockback = f1;
                    verticalKnockback = f2;
                    Speed = f3;
                    Power = f4;
                    Incendiary = f5;
                    comboMode = f6;
                    destroyBlocks = f7;
                    fallDamage = f8;

                    setMaxNoDamageTicks(comboMode);

                    FileConfiguration config = getConfig();
                    config.set("fireball.knockback.horizontalKnockback", horizontalKnockback);
                    config.set("fireball.knockback.verticalKnockback", verticalKnockback);
                    config.set("fireball.Speed", Speed);
                    config.set("fireball.Power", Power);
                    config.set("fireball.Incendiary", Incendiary);
                    config.set("Combo", comboMode);
                    config.set("fireball.destroyBlocks", destroyBlocks);
                    config.set("fireball.fallDamage", fallDamage);

                    saveConfig();

                    sender.sendMessage(
                            ChatColor.GREEN + "Fireball settings updated: " + " set vertical:" + verticalKnockback + " set horizontal:" + horizontalKnockback + " set Speed:" + Speed + " set Power:" + Power + " set Incendiary:" + Incendiary + " set ComboMode:" + comboMode + " set DestroyBlocks:" + destroyBlocks + " set FallDamage:" + fallDamage
                    );
                } catch (NumberFormatException e) {
                    sender.sendMessage(ChatColor.RED + "Invalid value! Please enter the correct number!");
                }
            } else {
                Player player = (Player) sender;
                player.sendMessage(ChatColor.RED + "Command usage: /fireball <horizontalKnockback> <verticalKnockback> <Speed> <Power> <Incendiary (true or false)> <ComboMode (true or false)> <DestroyBlocks (true or false)> <FallDamage (true or false)>");
            }
            return true;
        }
        return false;
    }
    private void setMaxNoDamageTicks(boolean comboMode) {
        int ticks = comboMode ? 2 : 11;
        for (World world : Bukkit.getWorlds()) {
            for (LivingEntity entity : world.getLivingEntities()) {
                entity.setMaximumNoDamageTicks(ticks);
            }
        }
    }

    @EventHandler
    public void onEntityDamagebyEntity(EntityDamageByEntityEvent event) {
        if (event.getDamager() instanceof Fireball && event.getEntity() instanceof LivingEntity) {
            Fireball fireball = (Fireball) event.getDamager();
            LivingEntity livingEntity = (Player) event.getEntity();
            livingEntity.damage(0, fireball);
            Vector fireballVelocity = fireball.getVelocity().normalize();
            Vector knockbackVector = new Vector(
                    fireballVelocity.getX() * horizontalKnockback,
                    fireballVelocity.getY() * (verticalKnockback * -1),
                    fireballVelocity.getZ() * horizontalKnockback
            );
            livingEntity.setVelocity(knockbackVector);

            if (livingEntity.getLocation().distanceSquared(fireball.getLocation()) <= fireball.getYield() * fireball.getYield()) {
                livingEntity.setVelocity(knockbackVector);
            }

            event.setDamage(0.0);
        } else if (event.getDamager() instanceof TNTPrimed && event.getEntity() instanceof LivingEntity) {
            if (event.getDamager() instanceof Fireball && event.getEntity() instanceof LivingEntity) {
                TNTPrimed tntPrimed = (TNTPrimed) event.getDamager();
                LivingEntity livingEntity = (Player) event.getEntity();
                livingEntity.damage(0, tntPrimed);
                Vector fireballVelocity = tntPrimed.getVelocity().normalize();
                Vector knockbackVector = new Vector(
                        fireballVelocity.getX() * horizontalKnockback,
                        fireballVelocity.getY() * (verticalKnockback* -1),
                        fireballVelocity.getZ() * horizontalKnockback
                );
                livingEntity.setVelocity(knockbackVector);
                if (livingEntity.getLocation().distanceSquared(tntPrimed.getLocation()) <= tntPrimed.getYield() * tntPrimed.getYield()) {
                    livingEntity.setVelocity(knockbackVector);
                }
            }
            event.setDamage(0.0);
        }
    }
    @EventHandler
    public void onProjectileHit(ProjectileHitEvent event) {
        if (event.getEntityType() == EntityType.FIREBALL) {
            Fireball fireball = (Fireball) event.getEntity();
            if (fireball.getShooter() instanceof Player) {
                Player shooter = (Player) fireball.getShooter();

                Location explosionLocation = fireball.getLocation();
                if (shooter.getLocation().distance(explosionLocation) <= 1.5) {
                    Vector selfKnockback = shooter.getLocation().getDirection().multiply(Speed * horizontalKnockback);
                    selfKnockback.setY(verticalKnockback);
                    shooter.setVelocity(selfKnockback);
                }

                for (Entity entity : explosionLocation.getWorld().getNearbyEntities(explosionLocation, 1.5, 1.5, 1.5)) {
                    if (entity instanceof Player) {
                        Player target = (Player) entity;
                        if (!target.getUniqueId().equals(shooter.getUniqueId())) {
                            Vector knockback = target.getLocation().toVector().subtract(explosionLocation.toVector()).normalize().multiply(Speed * horizontalKnockback);
                            knockback.setY(verticalKnockback);
                            target.setVelocity(knockback);
                        }
                    }
                }
            }
        }
        if (event.getEntityType() == EntityType.WITHER_SKULL) {
            WitherSkull witherSkull = (WitherSkull) event.getEntity();
            if (witherSkull.getShooter() instanceof Player) {
                Player shooter = (Player) witherSkull.getShooter();

                Location explosionLocation = witherSkull.getLocation();
                if (shooter.getLocation().distance(explosionLocation) <= 1.5) {
                    Vector selfKnockback = shooter.getLocation().getDirection().multiply(1 * horizontalKnockback);
                    selfKnockback.setY(verticalKnockback);
                    shooter.setVelocity(selfKnockback);
                }

                for (Entity entity : explosionLocation.getWorld().getNearbyEntities(explosionLocation, 1.5, 1.5, 1.5)) {
                    if (entity instanceof Player) {
                        Player target = (Player) entity;
                        if (!target.getUniqueId().equals(shooter.getUniqueId())) {
                            Vector knockback = target.getLocation().toVector().subtract(explosionLocation.toVector()).normalize().multiply(1 * horizontalKnockback);
                            knockback.setY(verticalKnockback);
                            target.setVelocity(knockback);
                        }
                    }
                }
            }
        }
    }
}


子程序:

package com.badlyac.NewFireballPlugin.BlockExplode;

import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.Material;

import java.util.HashMap;
import java.util.Map;

// No JavaPlugin allowed here!
public class BlockReset implements Listener {

    final Map<EntityExplodeEvent, Map<Block, BlockData>> explosionsData = new HashMap<>();

    @EventHandler
    public void onEntityExplode(EntityExplodeEvent event) {
        if (event.getEntity() instanceof TNTPrimed || event.getEntity() instanceof org.bukkit.entity.WitherSkull || event.getEntity() instanceof Fireball) {
            saveBlockData(event);
            restoreBlocksLater(event);
        }
    }
    @SuppressWarnings("deprecation")
    private void saveBlockData(EntityExplodeEvent event) {
        Map<Block, BlockData> blockDataBackup = new HashMap<>();
        for (Block block : event.blockList()) {
            BlockState blockState = block.getState();
            BlockData blockData = new BlockData(blockState.getType(), blockState.getData().getData());
            blockDataBackup.put(block, blockData);
        }
        // No this'es
        explosionsData.put(event, blockDataBackup);
    }

    private void restoreBlocksLater(final EntityExplodeEvent event) {
        (new BukkitRunnable() {
            public void run() {
                // Get rid of Class.this
                restoreBlocks(event);
            }
        // Plugin instance issue fixed here
        }).runTaskLater(FireballPlugin.getPlugin(), 60L);
    }
    @SuppressWarnings("deprecation")
    private void restoreBlocks(EntityExplodeEvent event) {
        if (this.explosionsData.containsKey(event)) {
            // Got rid of a this
            Map<Block, BlockData> blockDataBackup = explosionsData.get(event);
            for (Block block : event.blockList()) {
                if (blockDataBackup.containsKey(block)) {
                    BlockData blockData = blockDataBackup.get(block);
                    block.setType(blockData.getType());
                    block.setData(blockData.getData());
                    block.getState().update(true, false);
                }
            }
            // Got rid of a this
            explosionsData.remove(event);
        }
    }

    private static class BlockData {
        private final Material type;

        private final byte data;

        public BlockData(Material type, byte data) {
            // Now this is where those this'es go
            this.type = type;
            this.data = data;
        }

        public Material getType() {
            // No this needed here
            return type;
        }

        public byte getData() {
            // Not here either
            return data;
        }
    }
}


唉,写了这么多。希望能解决你的问题,把事情弄清楚!

相关问题